use std::{
any::{Any, TypeId},
cell::Cell,
future::Future,
path::PathBuf,
rc::Rc,
sync::Arc,
time::Duration,
};
use rustc_hash::FxHashMap;
use super::{
AdaptiveColor, Environment, Memo, Owner, Signal, SignalEquals, Tokens, cleanup, computed,
reactive::with_data,
signal_with,
task::{
self, Action, Answer, ClipboardImage, ClipboardItem, DialogAnswer, Executor, FileAnswer,
ImageSize,
},
};
use crate::{
Command, Dialog, EdgeInsets, LayoutAnimation, NodeId, Points, Size,
canvas::CanvasFont,
color::Hsla,
platform::{Appearance, Idiom, Lifecycle, Locale, LocaleSettings, Os},
time::Instant,
};
pub(crate) type MeasureFn = Rc<dyn Fn(&CanvasFont, &str) -> crate::canvas::TextMetrics>;
#[derive(Default)]
pub(crate) struct Ambient {
executor: Option<Rc<Executor>>,
env: Option<EnvSignals>,
tokens: Option<Signal<Arc<Tokens>>>,
globals: FxHashMap<TypeId, Box<dyn Any>>,
insets: FxHashMap<NodeId, Signal<EdgeInsets>>,
measure: Option<MeasureFn>,
storage: Option<crate::storage::Store>,
data_dir: Option<std::path::PathBuf>,
displays: Option<Signal<Arc<[crate::desktop::Display]>>>,
perf_monitor: Option<Signal<bool>>,
perf_stats: Option<Signal<Option<crate::platform::PerfStats>>>,
main_close_press: Option<Signal<(u64, crate::desktop::CloseReason)>>,
app_url: Option<crate::url_scheme::AppUrlCell>,
}
impl Ambient {
pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
self.insets.keys().copied().collect()
}
}
struct EnvSignals {
env: Signal<Environment>,
window: Memo<Size<Points>>,
horizontal_size_class: Memo<crate::platform::SizeClass>,
vertical_size_class: Memo<crate::platform::SizeClass>,
safe_area: Memo<EdgeInsets>,
title_bar: Memo<crate::geometry::Edges<crate::geometry::Points>>,
window_state: Memo<Option<crate::desktop::WindowState>>,
keyboard_height: Memo<Points>,
keyboard_duration: Memo<f32>,
dark: Memo<bool>,
font_scale: Memo<f32>,
reduce_motion: Memo<bool>,
screen_reader: Memo<bool>,
rtl: Memo<bool>,
pixel_ratio: Memo<f32>,
locale: Memo<Locale>,
locale_settings: Memo<LocaleSettings>,
lifecycle: Memo<Lifecycle>,
wake_count: Memo<u32>,
screen_color: Memo<bool>,
shaders: Memo<bool>,
}
impl EnvSignals {
fn new(env: Environment) -> Self {
Owner::detached().run(|| {
let signal = super::signal(env);
macro_rules! part {
($field:ident) => {
computed(move || signal.with(|e| e.$field))
};
}
Self {
env: signal,
window: part!(window),
horizontal_size_class: computed(move || {
signal.with(|e| {
e.horizontal_size_class.unwrap_or_else(|| {
crate::platform::SizeClass::from_length(e.window.width)
})
})
}),
vertical_size_class: computed(move || {
signal.with(|e| {
e.vertical_size_class.unwrap_or_else(|| {
crate::platform::SizeClass::from_length(e.window.height)
})
})
}),
safe_area: part!(safe_area),
title_bar: part!(title_bar),
window_state: part!(window_state),
keyboard_height: part!(keyboard_height),
keyboard_duration: part!(keyboard_duration),
dark: part!(dark),
font_scale: part!(font_scale),
reduce_motion: part!(reduce_motion),
screen_reader: part!(screen_reader),
rtl: part!(rtl),
pixel_ratio: part!(pixel_ratio),
locale: part!(locale),
locale_settings: part!(locale_settings),
lifecycle: part!(lifecycle),
wake_count: part!(wake_count),
screen_color: part!(screen_color),
shaders: part!(shaders),
}
})
}
}
impl super::Runtime {
pub(crate) fn set_services(&self, executor: Rc<Executor>) {
let _entered = self.enter();
with_data(|d| d.ambient.executor = Some(executor));
}
pub(crate) fn set_app_url(&self, app_url: crate::url_scheme::AppUrlCell) {
let _entered = self.enter();
with_data(|d| d.ambient.app_url = Some(app_url));
}
pub(crate) fn set_storage(&self, storage: crate::storage::Store) {
let _entered = self.enter();
with_data(|d| d.ambient.storage = Some(storage));
}
pub(crate) fn set_data_dir(&self, dir: Option<std::path::PathBuf>) {
let _entered = self.enter();
with_data(|d| d.ambient.data_dir = dir);
}
pub(crate) fn set_measure(&self, measure: MeasureFn) {
let _entered = self.enter();
with_data(|d| d.ambient.measure = Some(measure));
}
pub(crate) fn set_environment(&self, env: Environment) {
let _entered = self.enter();
let signal = with_data(|d| d.ambient.env.as_ref().map(|e| e.env));
match signal {
Some(signal) => signal.set(env),
None => {
let signals = EnvSignals::new(env);
with_data(|d| d.ambient.env = Some(signals));
}
}
}
pub(crate) fn set_displays(&self, displays: Arc<[crate::desktop::Display]>) {
let _entered = self.enter();
let signal = displays_signal();
if signal.with_untracked(|d| **d != *displays) {
signal.set(displays);
}
}
pub(crate) fn set_perf_monitor(&self, enabled: bool) {
let _entered = self.enter();
let signal = perf_monitor_signal();
if signal.get_untracked() != enabled {
signal.set(enabled);
}
}
pub(crate) fn set_perf_stats(&self, stats: Option<crate::platform::PerfStats>) {
let _entered = self.enter();
let signal = perf_stats_signal();
if signal.get_untracked() != stats {
signal.set(stats);
}
}
pub(crate) fn main_close_pressed(&self, reason: crate::desktop::CloseReason) {
let _entered = self.enter();
main_close_press_signal().update(|(count, last)| {
*count += 1;
*last = reason;
});
}
pub(crate) fn fit_window_placement(
&self,
placement: crate::desktop::WindowPlacement,
) -> crate::desktop::WindowPlacement {
let _entered = self.enter();
displays_signal().with_untracked(|d| placement.fit_on_displays(d))
}
pub(crate) fn set_tokens(&self, tokens: Arc<Tokens>) {
let _entered = self.enter();
let signal = with_data(|d| d.ambient.tokens);
match signal {
Some(signal) => signal.set(tokens),
None => {
let signal = Owner::detached().run(|| signal_with(tokens, SignalEquals::Never));
with_data(|d| d.ambient.tokens = Some(signal));
}
}
}
pub(crate) fn inset_hosts(&self) -> Vec<NodeId> {
let _entered = self.enter();
with_data(|d| d.ambient.inset_hosts())
}
pub(crate) fn set_insets(&self, host: NodeId, insets: EdgeInsets) {
let _entered = self.enter();
if let Some(signal) = with_data(|d| d.ambient.insets.get(&host).copied()) {
signal.set(insets);
}
}
pub(crate) fn forget_host(&self, host: NodeId) {
let _entered = self.enter();
with_data(|d| d.ambient.insets.remove(&host));
}
}
fn env<T: Clone + 'static>(part: impl FnOnce(&EnvSignals) -> Memo<T>) -> T {
let memo = with_data(|d| d.ambient.env.as_ref().map(part));
memo.expect("the core sets the environment before components run")
.get()
}
pub(super) fn executor() -> Rc<Executor> {
with_data(|d| d.ambient.executor.clone()).expect("the core sets the executor")
}
fn act(action: Action) {
executor().act(action);
}
pub(super) fn act_if_running(action: Action) {
if let Some(executor) = super::reactive::try_with_data(|d| d.ambient.executor.clone()).flatten()
{
executor.act(action);
}
}
pub fn window() -> Size<Points> {
env(|e| e.window)
}
pub fn horizontal_size_class() -> crate::platform::SizeClass {
env(|e| e.horizontal_size_class)
}
pub fn vertical_size_class() -> crate::platform::SizeClass {
env(|e| e.vertical_size_class)
}
pub fn safe_area() -> EdgeInsets {
env(|e| e.safe_area)
}
pub fn keyboard_height() -> Points {
env(|e| e.keyboard_height)
}
pub fn keyboard_duration() -> f32 {
env(|e| e.keyboard_duration)
}
pub fn dark() -> bool {
env(|e| e.dark)
}
pub fn color(color: impl Into<AdaptiveColor>) -> Hsla {
let color = color.into();
if dark() { color.dark } else { color.light }
}
pub fn font_scale() -> f32 {
env(|e| e.font_scale)
}
pub fn reduce_motion() -> bool {
env(|e| e.reduce_motion)
}
pub fn screen_reader() -> bool {
env(|e| e.screen_reader)
}
pub fn reads_active_descendants() -> bool {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.reads_active_descendants)
}
pub fn shaders_available() -> bool {
env(|e| e.shaders)
}
#[doc(hidden)]
pub fn layout_rtl() -> bool {
env(|e| e.rtl)
}
pub fn pixel_ratio() -> f32 {
env(|e| e.pixel_ratio)
}
pub fn round_to_nearest_pixel(points: Points) -> Points {
let ratio = pixel_ratio().max(f32::MIN_POSITIVE);
Points((points.0 * ratio).round() / ratio)
}
pub fn locale() -> Locale {
env(|e| e.locale)
}
pub fn locale_settings() -> LocaleSettings {
env(|e| e.locale_settings)
}
pub fn lifecycle() -> Lifecycle {
env(|e| e.lifecycle)
}
pub fn wake_count() -> u32 {
env(|e| e.wake_count)
}
pub fn os() -> Os {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.os)
}
pub fn platform_name() -> &'static str {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.platform_name())
}
pub(crate) fn has_tab_bar() -> bool {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| matches!(e.os, Os::Ios | Os::Android) && e.tab_bar)
}
pub fn try_os() -> Option<Os> {
super::reactive::try_with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.flatten()
.map(|env| env.with_untracked(|e| e.os))
}
pub fn os_version() -> (u16, u16) {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.os_version)
}
pub fn idiom() -> Idiom {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.idiom.reported_on(e.os))
}
pub fn cell_size() -> Option<Size<Points>> {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.cell)
}
pub fn is_catalyst() -> bool {
os().is_catalyst()
}
pub fn is_desktop() -> bool {
with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| e.idiom.desktop_on(e.os))
}
pub fn tokens() -> Arc<Tokens> {
with_data(|d| d.ambient.tokens)
.expect("the core sets the tokens")
.get()
}
pub fn set_tokens(tokens: impl Into<Tokens>) {
act(Action::Tokens(tokens.into()));
}
pub fn measure_text(font: &str, text: &str) -> Points {
text_metrics(font, text).width
}
pub fn text_measurer() -> impl Fn(&str, &str) -> Points + Clone {
let measure = with_data(|d| d.ambient.measure.clone()).expect("the core sets the text engine");
move |font, text| {
let font = CanvasFont::parse(font).unwrap_or_default();
measure(&font, text).width
}
}
pub fn text_metrics(font: &str, text: &str) -> crate::canvas::TextMetrics {
let font = CanvasFont::parse(font).unwrap_or_default();
let measure = with_data(|d| d.ambient.measure.clone()).expect("the core sets the text engine");
measure(&font, text)
}
pub fn global<G: Default + 'static>() -> Signal<G> {
let id = TypeId::of::<G>();
if let Some(signal) = with_data(|d| {
d.ambient
.globals
.get(&id)
.and_then(|g| g.downcast_ref::<Signal<G>>().copied())
}) {
return signal;
}
let signal = Owner::detached().run(|| signal_with(G::default(), SignalEquals::Never));
with_data(|d| d.ambient.globals.insert(id, Box::new(signal)));
signal
}
pub fn try_global<G: Default + 'static>() -> Option<Signal<G>> {
super::reactive::try_with_data(|_| ())?;
Some(global::<G>())
}
pub(crate) fn insets_of(host: NodeId) -> EdgeInsets {
let existing = with_data(|d| d.ambient.insets.get(&host).copied());
let signal = existing.unwrap_or_else(|| {
let signal = Owner::detached().run(|| super::signal(safe_area()));
with_data(|d| d.ambient.insets.insert(host, signal));
signal
});
signal.get()
}
#[doc(hidden)]
pub fn dialog(dialog: Dialog) -> DialogAnswer {
let (answer, slot) = DialogAnswer::new();
act(Action::Dialog(dialog, slot));
answer
}
pub fn dismiss_keyboard() {
act(Action::Command(crate::ROOT_ID, Command::Blur));
}
pub fn animate_layout(animation: LayoutAnimation) {
act(Action::Command(
crate::ROOT_ID,
Command::LayoutAnimation(animation),
));
}
pub fn announce_for_accessibility(message: impl Into<String>) {
act(super::services::announce(message.into()));
}
pub fn haptic(haptic: crate::Haptic) {
act(super::services::haptic(haptic));
}
pub(crate) fn with_storage<R>(f: impl FnOnce(&crate::storage::Store) -> R) -> R {
let storage = with_data(|d| {
d.ambient
.storage
.get_or_insert_with(|| crate::storage::Store::new(None))
.clone()
});
f(&storage)
}
pub fn data_dir() -> Option<std::path::PathBuf> {
with_data(|d| d.ambient.data_dir.clone())
}
pub fn log_file() -> Option<std::path::PathBuf> {
crate::log_file::path().map(std::path::Path::to_path_buf)
}
pub fn open_url(url: impl Into<String>) -> Answer<bool> {
let (answer, action) = super::services::open_url(url.into());
act(action);
answer
}
pub fn set_clipboard(text: impl Into<String>) {
act(super::services::set_clipboard(text.into()));
}
pub fn set_clipboard_item(item: ClipboardItem) {
act(super::services::set_clipboard_item(item));
}
pub fn clipboard_string() -> Answer<String> {
let (answer, action) = super::services::clipboard_string();
act(action);
answer
}
pub(crate) fn clipboard_checked_string() -> Answer<Option<String>> {
let (answer, action) = super::services::clipboard_checked_string();
act(action);
answer
}
pub fn clipboard_has_string() -> Answer<bool> {
let (answer, action) = super::services::clipboard_has_string();
act(action);
answer
}
pub fn set_clipboard_image(uri: impl Into<String>) {
act(super::services::set_clipboard_image(uri.into()));
}
pub fn clipboard_image() -> Answer<Option<ClipboardImage>> {
let (answer, action) = super::services::clipboard_image();
act(action);
answer
}
pub(crate) fn clipboard_checked_image() -> Answer<Result<Option<ClipboardImage>, usize>> {
let (answer, action) = super::services::clipboard_checked_image();
act(action);
answer
}
pub fn clipboard_has_image() -> Answer<bool> {
let (answer, action) = super::services::clipboard_has_image();
act(action);
answer
}
pub(crate) fn render_canvas(
request: crate::canvas::render::RenderRequest,
) -> Answer<Result<Vec<u8>, super::JsError>> {
let (answer, action) = super::services::render_canvas(request);
act(action);
answer
}
pub fn can_pick_screen_color() -> bool {
env(|e| e.screen_color)
}
pub fn pick_screen_color() -> Answer<Option<crate::Hsla>> {
let (answer, action) = super::services::pick_screen_color();
act(action);
answer
}
pub fn share(
request: crate::share::ShareRequest,
) -> Answer<Result<crate::share::ShareOutcome, crate::share::ShareError>> {
let (answer, action) = super::services::share(request);
act(action);
answer
}
pub fn open_auth_session(
request: crate::auth_session::AuthSessionRequest,
) -> Answer<Result<crate::auth_session::AuthSessionOutcome, crate::auth_session::AuthSessionError>>
{
let (answer, slot) = Answer::new();
act(Action::AuthSession(request, slot));
answer
}
pub fn close_auth_session() {
act(Action::CloseAuthSession);
}
pub fn share_available() -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::ShareAvailable(slot));
answer
}
pub fn clipboard_files() -> Answer<Vec<String>> {
let (answer, action) = super::services::clipboard_files();
act(action);
answer
}
pub fn register_font(data: impl Into<Vec<u8>>) -> Answer<Result<String, String>> {
let (answer, action) = super::services::register_font(data.into());
act(action);
answer
}
pub fn pick_paths(
dialog: crate::file_dialog::OpenDialog,
) -> Answer<Result<Option<Vec<PathBuf>>, String>> {
file_request(
crate::file_dialog::FileRequest::OpenDialog(dialog),
FileAnswer::OpenDialog,
)
}
pub fn pick_save_path(
dialog: crate::file_dialog::SaveDialog,
) -> Answer<Result<Option<PathBuf>, String>> {
file_request(
crate::file_dialog::FileRequest::SaveDialog(dialog),
FileAnswer::SaveDialog,
)
}
pub fn open_path(path: impl Into<PathBuf>) -> Answer<Result<(), String>> {
file_request(
crate::file_dialog::FileRequest::OpenPath(path.into()),
FileAnswer::Done,
)
}
pub fn reveal_path(path: impl Into<PathBuf>) -> Answer<Result<(), String>> {
file_request(
crate::file_dialog::FileRequest::RevealPath(path.into()),
FileAnswer::Done,
)
}
pub fn move_to_trash(path: impl Into<PathBuf>) -> Answer<Result<Option<PathBuf>, String>> {
file_request(
crate::file_dialog::FileRequest::MoveToTrash(path.into()),
FileAnswer::Trash,
)
}
fn file_request<T>(
request: crate::file_dialog::FileRequest,
answer: impl FnOnce(super::AnswerSlot<T>) -> FileAnswer,
) -> Answer<T> {
let (answer, action) = super::services::file_request(request, answer);
act(action);
answer
}
pub fn pick_images(request: crate::picker::PickRequest) -> Answer<Vec<crate::picker::PickedFile>> {
let (answer, action) = super::services::pick_images(request);
act(action);
answer
}
pub fn pick_files(
request: crate::picker::FilePickRequest,
) -> Answer<Vec<crate::picker::PickedFile>> {
let (answer, action) = super::services::pick_files(request);
act(action);
answer
}
pub fn speech_available() -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::Speech(super::SpeechAction::Available(slot)));
answer
}
pub fn notification_permission() -> Answer<crate::notifications::NotificationPermission> {
let (answer, slot) = Answer::new();
act(Action::Notification(
super::NotificationAction::Permission {
ask: false,
answer: slot,
},
));
answer
}
pub fn request_notification_permission() -> Answer<crate::notifications::NotificationPermission> {
let (answer, slot) = Answer::new();
act(Action::Notification(
super::NotificationAction::Permission {
ask: true,
answer: slot,
},
));
answer
}
pub fn show_notification(notification: crate::notifications::Notification) -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::Notification(super::NotificationAction::Show {
notification,
answer: slot,
}));
answer
}
pub fn close_notification(id: impl Into<String>) {
act(Action::Notification(super::NotificationAction::Close(
id.into(),
)));
}
pub fn close_all_notifications() {
act(Action::Notification(super::NotificationAction::CloseAll));
}
pub fn set_badge(count: u32) {
act(Action::Notification(super::NotificationAction::SetBadge(
count,
)));
}
pub fn next_notification_press() -> Answer<String> {
let (answer, slot) = Answer::new();
act(Action::Notification(super::NotificationAction::NextPress(
slot,
)));
answer
}
pub fn next_open_files() -> Answer<Vec<std::path::PathBuf>> {
let (answer, slot) = Answer::new();
act(Action::NextOpenFiles(slot));
answer
}
pub fn next_second_instance() -> Answer<crate::single_instance::SecondInstance> {
let (answer, slot) = Answer::new();
act(Action::NextSecondInstance(slot));
answer
}
pub fn next_url_scheme_open() -> Answer<String> {
let (answer, slot) = Answer::new();
act(Action::NextUrlSchemeOpen(slot));
answer
}
pub fn next_app_url_change() -> Answer<crate::url_scheme::AppUrlChange> {
let (answer, slot) = Answer::new();
act(Action::NextAppUrlChange(slot));
answer
}
pub fn app_url() -> Answer<Option<String>> {
let (answer, slot) = Answer::new();
act(Action::AppUrl(slot));
answer
}
pub fn set_app_url(url: impl Into<String>) -> Result<(), String> {
set_app_url_with(url, crate::url_scheme::HistoryBehavior::Replace)
}
pub fn set_app_url_with(
url: impl Into<String>,
history: crate::url_scheme::HistoryBehavior,
) -> Result<(), String> {
let mut url = url.into();
crate::url_scheme::check_address(&url)?;
if try_os() == Some(Os::Web)
&& let Some(base) = with_data(|d| d.ambient.app_url.as_ref().and_then(|a| a.page_base()))
{
url = crate::url_scheme::resolve_on_page(&url, &base)?;
}
act(Action::SetAppUrl(url, history));
Ok(())
}
pub(crate) fn set_app_url_from_js(url: String, history: crate::url_scheme::HistoryBehavior) {
act(Action::SetAppUrl(url, history));
}
pub fn web_input_available() -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::WebInputAvailable(slot));
answer
}
pub fn web_evaluate_available() -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::WebEvaluateAvailable(slot));
answer
}
pub fn web_view_available() -> Answer<bool> {
let (answer, slot) = Answer::new();
act(Action::WebViewAvailable(slot));
answer
}
pub fn recognize_speech(request: crate::speech::SpeechRequest) -> SpeechRecognition {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (sink, events) = crate::speech::channel();
let executor = executor();
executor.act(Action::Speech(super::SpeechAction::Start {
id,
request,
sink,
}));
SpeechRecognition {
id,
events,
executor: Rc::downgrade(&executor),
ended: false,
}
}
#[must_use = "a dropped recognition is aborted"]
pub struct SpeechRecognition {
id: u32,
events: crate::speech::SpeechEvents,
executor: std::rc::Weak<Executor>,
ended: bool,
}
impl std::fmt::Debug for SpeechRecognition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpeechRecognition")
.field("id", &self.id)
.field("ended", &self.ended)
.finish_non_exhaustive()
}
}
impl SpeechRecognition {
pub async fn next(&mut self) -> Option<crate::speech::SpeechEvent> {
std::future::poll_fn(|cx| self.poll_next(cx)).await
}
pub fn poll_next(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<crate::speech::SpeechEvent>> {
let poll = self.events.poll_next(cx);
if let std::task::Poll::Ready(None | Some(crate::speech::SpeechEvent::End { .. })) = poll {
self.ended = true;
}
poll
}
pub fn stop(&self) {
if !self.ended {
self.act(super::SpeechAction::Stop(self.id));
}
}
pub fn abort(&self) {
if !self.ended {
self.act(super::SpeechAction::Abort(self.id));
}
}
fn act(&self, action: super::SpeechAction) {
if let Some(executor) = self.executor.upgrade() {
executor.act(Action::Speech(action));
}
}
}
impl Drop for SpeechRecognition {
fn drop(&mut self) {
self.abort();
}
}
pub(crate) fn host_call(
name: String,
args: crate::JsonValue,
) -> Answer<Result<crate::JsonValue, super::JsError>> {
let (answer, action) = super::services::host_call(name, args);
act(action);
answer
}
pub(crate) fn host_post(name: String, args: crate::JsonValue) {
act(Action::HostPost { name, args });
}
pub(crate) fn forget_host_calls() {
act(Action::ForgetHostCalls);
}
pub fn image_size(src: impl Into<String>) -> Answer<Result<ImageSize, String>> {
let (answer, action) = super::services::image_size(src.into());
act(action);
answer
}
pub fn prefetch_image(src: impl Into<String>) -> super::Prefetch {
let (answer, action) = super::services::prefetch(src.into());
act(action);
answer
}
pub fn fetch(request: impl Into<crate::platform::HttpRequest>) -> super::Fetch {
let (answer, action) = super::services::fetch(request.into());
act(action);
answer
}
pub(crate) fn act_locale(locale: Option<crate::platform::Locale>) {
act(Action::Locale(locale));
}
pub fn set_color_scheme(appearance: Appearance) {
act(Action::Appearance(appearance));
}
pub fn set_builtin_scrollbars(source: super::ScrollbarSource, theme: Option<super::AnyValue>) {
act(Action::BuiltInScrollbars(source, theme));
}
pub struct Spawned<T>(task::Task<T>);
impl<T> Spawned<T> {
pub fn cancel(self) {
self.0.handle().cancel();
}
}
impl<T> Future for Spawned<T> {
type Output = T;
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<T> {
std::pin::Pin::new(&mut self.0).poll(cx)
}
}
pub fn spawn<T: 'static>(future: impl Future<Output = T> + 'static) -> Spawned<T> {
let executor = executor();
let owner = Owner::current();
let cancel = Rc::new(Cell::new(None));
let release = Release(cancel.clone());
let task = task::spawn_future(
&executor,
Owned {
owner,
future: Box::pin(async move {
let _release = release;
future.await
}),
},
);
let handle = task.handle();
cancel.set(super::reactive::removable_cleanup(move || handle.cancel()));
Spawned(task)
}
struct Release(Rc<Cell<Option<super::reactive::RemovableCleanup>>>);
impl Drop for Release {
fn drop(&mut self) {
if let Some(cancel) = self.0.take() {
cancel.remove();
}
}
}
pub fn run_on_main_thread<R: Send + 'static>(
f: impl FnOnce() -> R + Send + 'static,
) -> crate::main_thread::OnMainThread<R> {
let (task, result) = crate::main_thread::task(f);
act(Action::MainThread(task));
result
}
pub(super) fn owned(
owner: Owner,
future: impl Future<Output = ()> + 'static,
) -> std::pin::Pin<Box<dyn Future<Output = ()>>> {
Box::pin(Owned {
owner,
future: Box::pin(future),
})
}
struct Owned<F> {
owner: Owner,
future: std::pin::Pin<Box<F>>,
}
impl<F: Future> Future for Owned<F> {
type Output = F::Output;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<F::Output> {
let this = self.get_mut();
this.owner.scope(|| this.future.as_mut().poll(cx))
}
}
pub fn set_timeout(delay: Duration, f: impl FnOnce() + 'static) -> Spawned<()> {
let owner = Owner::current();
spawn(async move {
timer(delay).await;
owner.run(f);
})
}
pub fn set_interval(period: Duration, f: impl Fn() + 'static) -> Spawned<()> {
let owner = Owner::current();
spawn(async move {
let mut next = crate::time::now() + period;
loop {
timer_until(next).await;
next = (next + period).max(crate::time::now());
owner.run(&f);
}
})
}
pub fn request_animation_frame(f: impl FnOnce(Instant) + 'static) -> Spawned<()> {
let owner = Owner::current();
spawn(async move {
let at = next_frame().await;
owner.run(move || f(at));
})
}
pub fn timer(delay: Duration) -> Delay {
timer_until(crate::time::now() + delay)
}
pub fn timer_until(at: Instant) -> Delay {
Delay {
at,
timer: None,
#[cfg(not(target_arch = "wasm32"))]
elsewhere: None,
}
}
#[derive(Debug)]
pub struct Delay {
at: Instant,
timer: Option<task::TimerKey>,
#[cfg(not(target_arch = "wasm32"))]
elsewhere: Option<std::pin::Pin<Box<tokio::time::Sleep>>>,
}
impl Future for Delay {
type Output = ();
fn poll(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<()> {
#[cfg(not(target_arch = "wasm32"))]
if let Some(sleep) = &mut self.elsewhere {
return sleep.as_mut().poll(cx);
}
if crate::time::now() >= self.at {
self.timer = None;
return std::task::Poll::Ready(());
}
if let Some(timer) = &self.timer {
timer.set_waker(cx.waker());
return std::task::Poll::Pending;
}
match super::reactive::try_with_data(|d| d.ambient.executor.clone()).flatten() {
Some(executor) => {
self.timer = Some(executor.add_timer(self.at, cx.waker().clone()));
std::task::Poll::Pending
}
#[cfg(not(target_arch = "wasm32"))]
None => {
let at = self.at;
let sleep = self
.elsewhere
.insert(Box::pin(tokio::time::sleep_until(at.into())));
sleep.as_mut().poll(cx)
}
#[cfg(target_arch = "wasm32")]
None => std::task::Poll::Pending,
}
}
}
pub fn next_frame() -> Answer<Instant> {
let (answer, action) = super::services::frame();
act(action);
answer
}
pub fn after_answer(f: impl FnOnce() + 'static) {
executor().after_answer(task::AfterAnswer {
owner: Owner::current(),
f: Box::new(f),
});
}
#[cfg(not(target_arch = "wasm32"))]
pub fn blocking<R: Send + 'static>(
f: impl FnOnce() -> R + Send + 'static,
) -> tokio::task::JoinHandle<R> {
match tokio::runtime::Handle::try_current() {
Ok(runtime) => runtime.spawn_blocking(f),
Err(_) => match executor().runtime() {
Some(runtime) => runtime.spawn_blocking(f),
None => tokio::task::spawn_blocking(f),
},
}
}
#[cfg(not(target_arch = "wasm32"))]
pub fn background<F>(future: F) -> tokio::task::JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
tokio::spawn(future)
}
pub fn animated_value(value: f32) -> super::AnimatedValue {
super::AnimatedValue::new(&executor(), value)
}
pub fn motion() -> super::Motion {
super::Motion::new(&executor())
}
pub fn element_ref() -> super::ElementRef {
super::ElementRef::new(&executor())
}
pub fn component_ref<C: super::Component>() -> super::ComponentRef<C> {
super::ComponentRef::new(&executor())
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct KeyOptions {
pub when: crate::keymap::When,
pub repeat: bool,
pub pass_through: bool,
pub for_focus: bool,
}
pub fn apple_keys() -> bool {
let (os, apple) = with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| (e.os, e.apple_keyboard));
crate::keymap::apple_keys(os, apple)
}
pub fn try_apple_keys() -> Option<bool> {
super::reactive::try_with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.flatten()
.map(|env| env.with_untracked(|e| crate::keymap::apple_keys(e.os, e.apple_keyboard)))
}
#[track_caller]
pub fn on_key(keystroke: &str, handler: impl Fn(&str) + 'static) {
on_key_with(keystroke, KeyOptions::default(), handler);
}
#[track_caller]
pub fn on_key_with(keystroke: &str, options: KeyOptions, handler: impl Fn(&str) + 'static) {
let os = os();
let parsed = crate::keymap::Keystroke::parse_with(keystroke, apple_keys())
.unwrap_or_else(|e| panic!("on_key: {e}"));
if let Some(why) = parsed.reserved(os) {
panic!("on_key: {keystroke:?} cannot be bound: {why}");
}
let owner = Owner::current();
let handler: super::keys::KeyHandler = Rc::new(move |k: &str| owner.run(|| handler(k)));
let window = super::use_context::<super::desktop::WindowRef>().and_then(|w| w.dialog_root());
let keys = executor().keys.clone();
let id = keys.borrow_mut().add(
|id| {
crate::keymap::KeyBinding::new(id, parsed, options.when, options.repeat)
.passing_through(options.pass_through)
.focus_keys(options.for_focus)
},
keystroke.into(),
handler,
window,
owner,
);
let weak = Rc::downgrade(&keys);
cleanup(move || {
if let Some(keys) = weak.upgrade() {
let removed = keys.borrow_mut().remove(id);
drop(removed);
}
});
}
pub fn watch_scroll(
target: impl Fn() -> Option<NodeId> + 'static,
handler: impl Fn(&crate::element::ScrollEvent) + 'static,
) {
let owner = Owner::current();
let handler = Rc::new(move |e: &crate::element::ScrollEvent| owner.run(|| handler(e)));
add_watch(Rc::new(target), handler);
}
impl super::ElementRef {
pub fn on_focus_in(&self, listener: impl Fn() + 'static) {
let element = *self;
watch_focus(
move || element.node(),
move |within| {
if within {
listener();
}
},
);
}
pub fn on_focus_out(&self, listener: impl Fn() + 'static) {
let element = *self;
watch_focus(
move || element.node(),
move |within| {
if !within {
listener();
}
},
);
}
}
fn watch_focus(target: impl Fn() -> Option<NodeId> + 'static, handler: impl Fn(bool) + 'static) {
let owner = Owner::current();
let handler = Rc::new(move |within: bool| owner.run(|| handler(within)));
let watches = executor().watches.clone();
let id = watches.borrow_mut().add_focus(Rc::new(target), handler);
let weak = Rc::downgrade(&watches);
cleanup(move || {
if let Some(watches) = weak.upgrade() {
let removed = watches.borrow_mut().remove_focus(id);
drop(removed);
}
});
}
impl super::NodeRef {
pub fn scroll_to(&self, offset: crate::geometry::Point<Points>, animated: bool) {
act(Action::Command(
self.0,
Command::ScrollTo {
x: offset.x,
y: offset.y,
animated,
},
));
}
}
#[doc(hidden)]
pub fn watch_order(
elements: impl Fn() -> Vec<super::ElementRef> + 'static,
handler: impl Fn(&[usize]) + 'static,
) -> super::OrderWatch {
let owner = Owner::current();
let handler = Rc::new(move |order: &[usize]| owner.run(|| handler(order)));
let watches = executor().watches.clone();
let (id, dirty) = watches.borrow_mut().add_order(Rc::new(elements), handler);
let weak = Rc::downgrade(&watches);
cleanup(move || {
if let Some(watches) = weak.upgrade() {
let removed = watches.borrow_mut().remove_order(id);
drop(removed);
}
});
super::OrderWatch::new(dirty)
}
fn add_watch(target: Rc<dyn Fn() -> Option<NodeId>>, handler: super::watch::ScrollHandler) {
let watches = executor().watches.clone();
let id = watches.borrow_mut().add(target, handler);
let weak = Rc::downgrade(&watches);
cleanup(move || {
if let Some(watches) = weak.upgrade() {
let removed = watches.borrow_mut().remove(id);
drop(removed);
}
});
}
#[track_caller]
pub fn key_label(keystroke: &str) -> String {
let parsed = crate::keymap::Keystroke::parse_with(keystroke, apple_keys())
.unwrap_or_else(|e| panic!("key_label: {e}"));
keystroke_label(parsed)
}
pub fn keystroke_label(keystroke: crate::keymap::Keystroke) -> String {
let (os, apple, ctrl) = with_data(|d| d.ambient.env.as_ref().map(|e| e.env))
.expect("the core sets the environment")
.with_untracked(|e| {
(
e.os,
crate::keymap::apple_keys(e.os, e.apple_keyboard),
e.ctrl_for_command,
)
});
keystroke.pressed(ctrl).label(os, apple)
}
pub fn on_back_press(f: impl Fn() -> bool + 'static) {
let owner = Owner::current();
let listener: super::back::BackListener = Rc::new(move || owner.run(&f));
let back = &executor().back;
let id = back.borrow_mut().add(listener);
let subscription = super::back::BackSubscription::new(back, id);
cleanup(move || drop(subscription));
}
pub(crate) fn title_bar() -> crate::geometry::Edges<crate::geometry::Points> {
env(|e| e.title_bar)
}
pub(crate) fn window_state() -> Option<crate::desktop::WindowState> {
env(|e| e.window_state)
}
pub(crate) fn displays() -> Vec<crate::desktop::Display> {
displays_signal().with(|d| d.to_vec())
}
fn displays_signal() -> Signal<Arc<[crate::desktop::Display]>> {
if let Some(signal) = with_data(|d| d.ambient.displays) {
return signal;
}
let signal = Owner::detached().run(|| super::signal(Arc::from(Vec::new())));
with_data(|d| d.ambient.displays = Some(signal));
signal
}
pub fn fps_enabled() -> bool {
perf_monitor_signal().get()
}
pub fn set_fps_enabled(enabled: bool) {
act(super::services::perf_monitor(enabled));
}
pub fn perf_stats() -> Option<crate::platform::PerfStats> {
perf_stats_signal().get()
}
fn perf_stats_signal() -> Signal<Option<crate::platform::PerfStats>> {
if let Some(signal) = with_data(|d| d.ambient.perf_stats) {
return signal;
}
let signal = Owner::detached().run(|| super::signal(None));
with_data(|d| d.ambient.perf_stats = Some(signal));
signal
}
pub fn set_fps_mode(mode: crate::FpsMode) {
act(super::services::perf_monitor_mode(mode));
}
fn perf_monitor_signal() -> Signal<bool> {
if let Some(signal) = with_data(|d| d.ambient.perf_monitor) {
return signal;
}
let signal = Owner::detached().run(|| super::signal(false));
with_data(|d| d.ambient.perf_monitor = Some(signal));
signal
}
pub(crate) fn main_close_press_signal() -> Signal<(u64, crate::desktop::CloseReason)> {
if let Some(signal) = with_data(|d| d.ambient.main_close_press) {
return signal;
}
let signal =
Owner::detached().run(|| super::signal((0, crate::desktop::CloseReason::default())));
with_data(|d| d.ambient.main_close_press = Some(signal));
signal
}
pub(crate) fn view_menus() -> Rc<std::cell::RefCell<super::menus::ViewMenus>> {
executor().menus.clone()
}
pub(crate) fn desktop_command(command: crate::desktop::DesktopCommand) {
act(Action::Command(
crate::ROOT_ID,
Command::Desktop(Box::new(command)),
));
}
pub(crate) fn login_item_request(
enabled: Option<bool>,
) -> Answer<Result<bool, crate::desktop::LaunchAtLoginError>> {
let (answer, slot) = Answer::new();
act(Action::LoginItem(enabled, slot));
answer
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{element::Runtime, geometry::px};
#[test]
fn captured_text_measurer_works_without_runtime_entry() {
let runtime = Runtime::default();
runtime.set_measure(Rc::new(|_, text| crate::canvas::TextMetrics {
width: px(text.chars().count() as f32),
..Default::default()
}));
let measure = {
let _entered = runtime.enter();
text_measurer()
};
assert_eq!(measure("16px sans-serif", "选择 text"), px(7.0));
}
}