use super::*;
#[cfg(not(target_arch = "wasm32"))]
pub struct AppRunner {
pub(super) event_loop: EventLoop<RuntimeEvent>,
pub(super) runtime: Runtime,
pub(super) root_window: WindowHandle,
pub(super) root_window_pending: bool,
pub(super) status: AppRunStatus,
pub(super) relaunched_process: Option<RelaunchedProcess>,
}
#[cfg(not(target_arch = "wasm32"))]
impl AppRunner {
pub fn pump(&mut self, timeout: Option<Duration>) -> Result<AppRunStatus, AppError> {
if matches!(self.status, AppRunStatus::Exited(_)) {
return Ok(self.status);
}
let status = self.event_loop.pump_app_events(timeout, &mut self.runtime);
if let Some(error) = self.runtime.fatal_error.take() {
self.status = AppRunStatus::Exited(1);
self.runtime.relaunch_request.take();
self.runtime.finalize_process_services();
return Err(error);
}
self.status = match status {
PumpStatus::Continue => AppRunStatus::Continue,
PumpStatus::Exit(code) => AppRunStatus::Exited(code),
};
if matches!(self.status, AppRunStatus::Exited(_)) {
self.runtime.finalize_process_services();
if let Some(request) = self.runtime.relaunch_request.take() {
self.relaunched_process = Some(
request
.spawn()
.map_err(|error| AppError::Platform(error.to_string()))?,
);
}
}
Ok(self.status)
}
pub fn waker(&self) -> AppRunnerWaker {
AppRunnerWaker {
proxy: self.runtime.event_proxy.clone(),
}
}
pub const fn root_window(&self) -> WindowHandle {
self.root_window
}
pub const fn is_ready(&self) -> bool {
self.runtime.ready
}
pub fn current_window(&self) -> Option<WindowHandle> {
self.runtime.current_handle()
}
pub fn cursor_screen_position(&self) -> Result<Point, PlatformError> {
cursor_screen_position(&self.runtime.displays)
}
pub fn app_info(&self) -> Option<&AppInfo> {
self.runtime.app_info.as_ref()
}
pub fn app_paths(&self) -> Option<&AppPaths> {
self.runtime.app_paths.as_ref()
}
pub fn system_info(&self) -> &SystemInfo {
&self.runtime.system_info
}
pub const fn desktop_integration_support(&self) -> DesktopIntegrationSupport {
DesktopIntegrationSupport::current()
}
pub fn application_menus(&self) -> &[Menu] {
self.runtime
.external_menus
.as_deref()
.unwrap_or(&self.runtime.menus)
}
pub fn window_menus(&self, handle: WindowHandle) -> Option<&[Menu]> {
let application_menus = self.application_menus();
if self.runtime.current_handle() == Some(handle) {
return Some(
self.runtime
.config
.window_menus
.as_deref()
.unwrap_or(application_menus),
);
}
if let Some(window_id) = self.runtime.window_handles.get(&handle)
&& let Some(entry) = self.runtime.windows.get(window_id)
{
return Some(
entry
.config
.window_menus
.as_deref()
.unwrap_or(application_menus),
);
}
self.runtime
.pending_windows
.iter()
.find(|request| request.handle == handle)
.map(|request| {
request
.options
.window_menus
.as_deref()
.unwrap_or(application_menus)
})
}
pub const fn system_preferences(&self) -> SystemPreferences {
self.runtime.system_preferences
}
pub fn window_registry(&self) -> WindowRegistry {
self.runtime.window_registry()
}
pub fn active_window(&self) -> Option<WindowHandle> {
self.runtime.active_window_handle()
}
pub fn open_window<V: View>(
&mut self,
options: WindowOptions,
view: V,
) -> Result<WindowHandle, AppError> {
if !matches!(self.status, AppRunStatus::Continue) {
return Err(AppError::Window(
"cannot open a window after the application event loop exited".to_owned(),
));
}
validate_window_options(&options).map_err(|error| AppError::Window(error.to_string()))?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| AppError::Window("application event loop is closed".to_owned()))?;
let request = if self.root_window_pending {
self.root_window_pending = false;
WindowRequest::with_handle(view, options, None, self.root_window)
} else {
WindowRequest::new(view, options)
};
let handle = request.handle;
self.runtime.pending_windows.push_back(request);
Ok(handle)
}
pub fn open_system_popover<V: View>(
&mut self,
parent: WindowHandle,
anchor: ElementId,
options: WindowOptions,
view: V,
) -> Result<WindowHandle, AppError> {
if !matches!(self.status, AppRunStatus::Continue) {
return Err(AppError::Window(
"cannot open a popover after the application event loop exited".to_owned(),
));
}
validate_window_options(&options).map_err(|error| AppError::Window(error.to_string()))?;
if options.kind != WindowKind::SystemPopover || options.popover.is_none() {
return Err(AppError::Window(
WindowCommandError::InvalidPopoverConfiguration.to_string(),
));
}
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| AppError::Window("application event loop is closed".to_owned()))?;
let mut request = WindowRequest::with_parent(view, options, Some(parent));
request.popover_anchor_element = Some(anchor);
let handle = request.handle;
self.runtime.pending_windows.push_back(request);
Ok(handle)
}
pub fn invalidate_window(&mut self, handle: WindowHandle) -> bool {
if !matches!(self.status, AppRunStatus::Continue) {
return false;
}
if self
.runtime
.pending_windows
.iter()
.any(|request| request.handle == handle)
{
return true;
}
self.runtime.invalidate_external(handle)
}
pub fn focus_element(&mut self, handle: WindowHandle, element: ElementId) -> bool {
if !matches!(self.status, AppRunStatus::Continue) {
return false;
}
self.runtime.focus_external(handle, element)
}
pub fn prompt(
&mut self,
window: WindowHandle,
level: PromptLevel,
message: impl Into<Arc<str>>,
detail: Option<&str>,
buttons: &[PromptButton],
) -> Result<PlatformResponse<usize>, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue)
|| !self.runtime.window_handles.contains_key(&window)
{
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) =
PlatformRequest::prompt(window, level, message, detail.map(Arc::from), buttons)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn prompt_application(
&mut self,
level: PromptLevel,
message: impl Into<Arc<str>>,
detail: Option<&str>,
buttons: &[PromptButton],
) -> Result<PlatformResponse<usize>, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue) {
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) =
PlatformRequest::application_prompt(level, message, detail.map(Arc::from), buttons)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn prompt_for_paths(
&mut self,
window: WindowHandle,
options: PathPromptOptions,
) -> Result<PathPromptResponse, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue)
|| !self.runtime.window_handles.contains_key(&window)
{
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) = PlatformRequest::open_paths(window, options)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn prompt_for_paths_application(
&mut self,
options: PathPromptOptions,
) -> Result<PathPromptResponse, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue) {
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) = PlatformRequest::application_open_paths(options)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn prompt_for_new_path(
&mut self,
window: WindowHandle,
options: SavePathOptions,
) -> Result<SavePathResponse, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue)
|| !self.runtime.window_handles.contains_key(&window)
{
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) = PlatformRequest::save_path(window, options)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn prompt_for_new_path_application(
&mut self,
options: SavePathOptions,
) -> Result<SavePathResponse, PlatformError> {
if !matches!(self.status, AppRunStatus::Continue) {
return Err(PlatformError::Unavailable);
}
if self.runtime.platform_requests.len() == crate::MAX_PENDING_PLATFORM_REQUESTS {
return Err(PlatformError::PendingQueueFull);
}
let (request, response) = PlatformRequest::application_save_path(options)?;
self.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.map_err(|_| PlatformError::Unavailable)?;
self.runtime.platform_requests.push_back(request);
Ok(response)
}
pub fn close_window(&mut self, handle: WindowHandle) -> bool {
if !matches!(self.status, AppRunStatus::Continue) {
return false;
}
let pending = self
.runtime
.pending_windows
.iter()
.position(|request| request.handle == handle);
let mounted = self.runtime.window_handles.contains_key(&handle)
|| self.runtime.current_handle() == Some(handle);
if pending.is_none() && !mounted {
return false;
}
if self
.runtime
.event_proxy
.send_event(RuntimeEvent::ExternalCommandsReady)
.is_err()
{
return false;
}
if let Some(index) = pending {
self.runtime.pending_windows.remove(index);
} else if !self.runtime.close_requests.contains(&handle) {
self.runtime.close_requests.push(handle);
}
true
}
pub fn invalidate_root(&mut self) -> bool {
self.invalidate_window(self.root_window)
}
pub const fn status(&self) -> AppRunStatus {
self.status
}
pub const fn relaunched_process(&self) -> Option<RelaunchedProcess> {
self.relaunched_process
}
}
pub type App = EventContext;
pub struct Application {
pub(super) app_info: Option<AppInfo>,
pub(super) app_paths: Option<AppPaths>,
pub(super) keymap: Keymap,
pub(super) menus: Vec<Menu>,
pub(super) globals: GlobalStore,
pub(super) assets: Assets,
pub(super) fonts: Vec<FontSource>,
pub(super) application_callbacks: ApplicationCallbacks,
pub(super) quit_mode: QuitMode,
}
impl Application {
pub fn new() -> Self {
Self {
app_info: None,
app_paths: None,
keymap: Keymap::default(),
menus: Vec::new(),
globals: GlobalStore::default(),
assets: Assets::default(),
fonts: Vec::new(),
application_callbacks: ApplicationCallbacks::default(),
quit_mode: QuitMode::Default,
}
}
pub fn quit_mode(mut self, mode: QuitMode) -> Self {
self.quit_mode = mode;
self
}
pub fn with_quit_mode(self, mode: QuitMode) -> Self {
self.quit_mode(mode)
}
pub fn app_info(mut self, info: AppInfo) -> Self {
self.app_info = Some(info);
self
}
pub fn with_app_info(self, info: AppInfo) -> Self {
self.app_info(info)
}
pub fn app_paths(mut self, paths: AppPaths) -> Self {
self.app_paths = Some(paths);
self
}
pub fn with_app_paths(self, paths: AppPaths) -> Self {
self.app_paths(paths)
}
pub fn with_assets(mut self, source: impl crate::AssetSource) -> Self {
self.assets = Assets::new(source);
self
}
pub fn assets(mut self, assets: Assets) -> Self {
self.assets = assets;
self
}
pub fn font(mut self, font: impl Into<FontSource>) -> Self {
self.fonts.push(font.into());
self
}
pub fn fonts(mut self, fonts: impl IntoIterator<Item = impl Into<FontSource>>) -> Self {
self.fonts.extend(fonts.into_iter().map(Into::into));
self
}
pub fn bind_keys(mut self, bindings: impl IntoIterator<Item = KeyBinding>) -> Self {
self.keymap.add_bindings(bindings);
self
}
pub fn keymap(mut self, keymap: Keymap) -> Self {
self.keymap = keymap;
self
}
pub fn menu(mut self, menu: Menu) -> Self {
self.menus.push(menu);
self
}
pub fn menus(mut self, menus: impl IntoIterator<Item = Menu>) -> Self {
self.menus = menus.into_iter().collect();
self
}
pub fn global<G: Global>(self, global: G) -> Self {
self.globals.set(global);
self
}
pub fn on_open_urls(
mut self,
callback: impl FnMut(OpenUrls, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.open_urls = Some(Box::new(callback));
self
}
pub fn on_reopen(mut self, callback: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
self.application_callbacks.reopen = Some(Box::new(callback));
self
}
pub fn on_system_wake(mut self, callback: impl FnMut(&mut EventContext) + 'static) -> Self {
self.application_callbacks.system_wake = Some(Box::new(callback));
self
}
pub fn on_keyboard_layout_change(
mut self,
callback: impl FnMut(&KeyboardLayout, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.keyboard_layout = Some(Box::new(callback));
self
}
pub fn on_system_notification_response(
mut self,
callback: impl FnMut(SystemNotificationResponse, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.system_notification_response = Some(Box::new(callback));
self
}
pub fn on_global_shortcut(
mut self,
callback: impl FnMut(GlobalShortcutEvent, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.global_shortcut = Some(Box::new(callback));
self
}
pub fn on_second_instance(
mut self,
callback: impl FnMut(SecondInstanceEvent, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.second_instance = Some(Box::new(callback));
self
}
pub fn on_power_event(
mut self,
callback: impl FnMut(PowerEvent, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.power_event = Some(Box::new(callback));
self
}
pub fn on_tray_event(
mut self,
callback: impl FnMut(TrayEvent, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.tray_event = Some(Box::new(callback));
self
}
pub fn on_window_closed(
mut self,
callback: impl FnMut(WindowHandle, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.window_closed = Some(Box::new(callback));
self
}
pub fn on_before_quit(
mut self,
callback: impl FnMut(QuitRequest, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.before_quit = Some(Box::new(callback));
self
}
pub fn on_will_quit(
mut self,
callback: impl FnMut(QuitRequest, &mut EventContext) + 'static,
) -> Self {
self.application_callbacks.will_quit = Some(Box::new(callback));
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn into_runner(self) -> Result<AppRunner, AppError> {
let event_loop = EventLoop::with_user_event().build()?;
event_loop.set_control_flow(ControlFlow::Wait);
let root_window = WindowHandle::next();
let runtime = Runtime::new(
RuntimeStartup {
initial_window: None,
app_info: self.app_info,
app_paths: self.app_paths,
globals: self.globals,
keymap: self.keymap,
menus: self.menus,
assets: self.assets,
fonts: self.fonts,
application_callbacks: self.application_callbacks,
quit_mode: self.quit_mode,
},
event_loop.create_proxy(),
)?;
Ok(AppRunner {
event_loop,
runtime,
root_window,
root_window_pending: true,
status: AppRunStatus::Continue,
relaunched_process: None,
})
}
pub fn run(
mut self,
on_finish_launching: impl FnOnce(&mut App) + 'static,
) -> Result<(), AppError> {
self.application_callbacks.finish_launching = Some(Box::new(on_finish_launching));
#[cfg(not(target_arch = "wasm32"))]
{
let AppRunner {
event_loop,
mut runtime,
..
} = self.into_runner()?;
let run_result = event_loop.run_app(&mut runtime);
let fatal_error = runtime.fatal_error.take();
let relaunch = runtime.relaunch_request.take();
runtime.finalize_process_services();
drop(runtime);
run_result?;
if let Some(error) = fatal_error {
return Err(error);
}
if let Some(request) = relaunch {
request
.spawn()
.map_err(|error| AppError::Platform(error.to_string()))?;
}
Ok(())
}
#[cfg(target_arch = "wasm32")]
{
let event_loop = EventLoop::with_user_event().build()?;
event_loop.set_control_flow(ControlFlow::Wait);
let mut runtime = Runtime::new(
RuntimeStartup {
initial_window: None,
app_info: self.app_info,
app_paths: self.app_paths,
globals: self.globals,
keymap: self.keymap,
menus: self.menus,
assets: self.assets,
fonts: self.fonts,
application_callbacks: self.application_callbacks,
quit_mode: self.quit_mode,
},
event_loop.create_proxy(),
)?;
event_loop.run_app(&mut runtime)?;
if runtime.relaunch_request.is_some() {
return Err(AppError::Platform(
"application relaunch is unavailable on WebAssembly".to_owned(),
));
}
match runtime.fatal_error.take() {
Some(error) => Err(error),
None => Ok(()),
}
}
}
}
impl Default for Application {
fn default() -> Self {
Self::new()
}
}