edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | use std::{ |
| 2 | any::{TypeId, type_name}, |
| 3 | cell::{BorrowMutError, Ref, RefCell, RefMut}, |
| 4 | marker::PhantomData, |
| 5 | mem, |
| 6 | ops::{Deref, DerefMut}, |
| 7 | path::{Path, PathBuf}, |
| 8 | rc::{Rc, Weak}, |
| 9 | sync::{Arc, atomic::Ordering::SeqCst}, |
| 10 | time::{Duration, Instant}, |
| 11 | }; |
| 12 | |
| 13 | use anyhow::{Context as _, Result, anyhow}; |
| 14 | use derive_more::{Deref, DerefMut}; |
| 15 | use futures::{ |
| 16 | Future, FutureExt, |
| 17 | channel::oneshot, |
| 18 | future::{LocalBoxFuture, Shared}, |
| 19 | }; |
| 20 | use itertools::Itertools; |
| 21 | use parking_lot::RwLock; |
| 22 | use slotmap::SlotMap; |
| 23 | |
| 24 | pub use async_context::*; |
| 25 | use collections::{FxHashMap, FxHashSet, HashMap, VecDeque}; |
| 26 | pub use context::*; |
| 27 | pub use entity_map::*; |
| 28 | use http_client::{HttpClient, Url}; |
| 29 | use smallvec::SmallVec; |
| 30 | #[cfg(any(test, feature = "test-support"))] |
| 31 | pub use test_context::*; |
| 32 | use util::{ResultExt, debug_panic}; |
| 33 | |
| 34 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 35 | use crate::InspectorElementRegistry; |
| 36 | use crate::{ |
| 37 | Action, ActionBuildError, ActionRegistry, Any, AnyView, AnyWindowHandle, AppContext, Asset, |
| 38 | AssetSource, BackgroundExecutor, Bounds, ClipboardItem, CursorStyle, DispatchPhase, DisplayId, |
| 39 | EventEmitter, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, |
| 40 | Keymap, Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform, |
| 41 | PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, PromptBuilder, |
| 42 | PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, |
| 43 | Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, Task, |
| 44 | TextSystem, Window, WindowAppearance, WindowHandle, WindowId, WindowInvalidator, |
| 45 | colors::{Colors, GlobalColors}, |
| 46 | current_platform, hash, init_app_menus, |
| 47 | }; |
| 48 | |
| 49 | mod async_context; |
| 50 | mod context; |
| 51 | mod entity_map; |
| 52 | #[cfg(any(test, feature = "test-support"))] |
| 53 | mod test_context; |
| 54 | |
| 55 | /// The duration for which futures returned from [Context::on_app_quit] can run before the application fully quits. |
| 56 | pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100); |
| 57 | |
| 58 | /// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows. |
| 59 | /// Strongly consider removing after stabilization. |
| 60 | #[doc(hidden)] |
| 61 | pub struct AppCell { |
| 62 | app: RefCell<App>, |
| 63 | } |
| 64 | |
| 65 | impl AppCell { |
| 66 | #[doc(hidden)] |
| 67 | #[track_caller] |
| 68 | pub fn borrow(&self) -> AppRef<'_> { |
| 69 | if option_env!("TRACK_THREAD_BORROWS").is_some() { |
| 70 | let thread_id = std::thread::current().id(); |
| 71 | eprintln!("borrowed {thread_id:?}"); |
| 72 | } |
| 73 | AppRef(self.app.borrow()) |
| 74 | } |
| 75 | |
| 76 | #[doc(hidden)] |
| 77 | #[track_caller] |
| 78 | pub fn borrow_mut(&self) -> AppRefMut<'_> { |
| 79 | if option_env!("TRACK_THREAD_BORROWS").is_some() { |
| 80 | let thread_id = std::thread::current().id(); |
| 81 | eprintln!("borrowed {thread_id:?}"); |
| 82 | } |
| 83 | AppRefMut(self.app.borrow_mut()) |
| 84 | } |
| 85 | |
| 86 | #[doc(hidden)] |
| 87 | #[track_caller] |
| 88 | pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> { |
| 89 | if option_env!("TRACK_THREAD_BORROWS").is_some() { |
| 90 | let thread_id = std::thread::current().id(); |
| 91 | eprintln!("borrowed {thread_id:?}"); |
| 92 | } |
| 93 | Ok(AppRefMut(self.app.try_borrow_mut()?)) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | #[doc(hidden)] |
| 98 | #[derive(Deref, DerefMut)] |
| 99 | pub struct AppRef<'a>(Ref<'a, App>); |
| 100 | |
| 101 | impl Drop for AppRef<'_> { |
| 102 | fn drop(&mut self) { |
| 103 | if option_env!("TRACK_THREAD_BORROWS").is_some() { |
| 104 | let thread_id = std::thread::current().id(); |
| 105 | eprintln!("dropped borrow from {thread_id:?}"); |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | #[doc(hidden)] |
| 111 | #[derive(Deref, DerefMut)] |
| 112 | pub struct AppRefMut<'a>(RefMut<'a, App>); |
| 113 | |
| 114 | impl Drop for AppRefMut<'_> { |
| 115 | fn drop(&mut self) { |
| 116 | if option_env!("TRACK_THREAD_BORROWS").is_some() { |
| 117 | let thread_id = std::thread::current().id(); |
| 118 | eprintln!("dropped {thread_id:?}"); |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | /// A reference to a GPUI application, typically constructed in the `main` function of your app. |
| 124 | /// You won't interact with this type much outside of initial configuration and startup. |
| 125 | pub struct Application(Rc<AppCell>); |
| 126 | |
| 127 | /// Represents an application before it is fully launched. Once your app is |
| 128 | /// configured, you'll start the app with `App::run`. |
| 129 | impl Application { |
| 130 | /// Builds an app with the given asset source. |
| 131 | #[allow(clippy::new_without_default)] |
| 132 | pub fn new() -> Self { |
| 133 | #[cfg(any(test, feature = "test-support"))] |
| 134 | log::info!("GPUI was compiled in test mode"); |
| 135 | |
| 136 | Self(App::new_app( |
| 137 | current_platform(false), |
| 138 | Arc::new(()), |
| 139 | Arc::new(NullHttpClient), |
| 140 | )) |
| 141 | } |
| 142 | |
| 143 | /// Build an app in headless mode. This prevents opening windows, |
| 144 | /// but makes it possible to run an application in an context like |
| 145 | /// SSH, where GUI applications are not allowed. |
| 146 | pub fn headless() -> Self { |
| 147 | Self(App::new_app( |
| 148 | current_platform(true), |
| 149 | Arc::new(()), |
| 150 | Arc::new(NullHttpClient), |
| 151 | )) |
| 152 | } |
| 153 | |
| 154 | /// Assign |
| 155 | pub fn with_assets(self, asset_source: impl AssetSource) -> Self { |
| 156 | let mut context_lock = self.0.borrow_mut(); |
| 157 | let asset_source = Arc::new(asset_source); |
| 158 | context_lock.asset_source = asset_source.clone(); |
| 159 | context_lock.svg_renderer = SvgRenderer::new(asset_source); |
| 160 | drop(context_lock); |
| 161 | self |
| 162 | } |
| 163 | |
| 164 | /// Sets the HTTP client for the application. |
| 165 | pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self { |
| 166 | let mut context_lock = self.0.borrow_mut(); |
| 167 | context_lock.http_client = http_client; |
| 168 | drop(context_lock); |
| 169 | self |
| 170 | } |
| 171 | |
| 172 | /// Start the application. The provided callback will be called once the |
| 173 | /// app is fully launched. |
| 174 | pub fn run<F>(self, on_finish_launching: F) |
| 175 | where |
| 176 | F: 'static + FnOnce(&mut App), |
| 177 | { |
| 178 | let this = self.0.clone(); |
| 179 | let platform = self.0.borrow().platform.clone(); |
| 180 | platform.run(Box::new(move || { |
| 181 | let cx = &mut *this.borrow_mut(); |
| 182 | on_finish_launching(cx); |
| 183 | })); |
| 184 | } |
| 185 | |
| 186 | /// Register a handler to be invoked when the platform instructs the application |
| 187 | /// to open one or more URLs. |
| 188 | pub fn on_open_urls<F>(&self, mut callback: F) -> &Self |
| 189 | where |
| 190 | F: 'static + FnMut(Vec<String>), |
| 191 | { |
| 192 | self.0.borrow().platform.on_open_urls(Box::new(callback)); |
| 193 | self |
| 194 | } |
| 195 | |
| 196 | /// Invokes a handler when an already-running application is launched. |
| 197 | /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock. |
| 198 | pub fn on_reopen<F>(&self, mut callback: F) -> &Self |
| 199 | where |
| 200 | F: 'static + FnMut(&mut App), |
| 201 | { |
| 202 | let this = Rc::downgrade(&self.0); |
| 203 | self.0.borrow_mut().platform.on_reopen(Box::new(move || { |
| 204 | if let Some(app) = this.upgrade() { |
| 205 | callback(&mut app.borrow_mut()); |
| 206 | } |
| 207 | })); |
| 208 | self |
| 209 | } |
| 210 | |
| 211 | /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background. |
| 212 | pub fn background_executor(&self) -> BackgroundExecutor { |
| 213 | self.0.borrow().background_executor.clone() |
| 214 | } |
| 215 | |
| 216 | /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground. |
| 217 | pub fn foreground_executor(&self) -> ForegroundExecutor { |
| 218 | self.0.borrow().foreground_executor.clone() |
| 219 | } |
| 220 | |
| 221 | /// Returns a reference to the [`TextSystem`] associated with this app. |
| 222 | pub fn text_system(&self) -> Arc<TextSystem> { |
| 223 | self.0.borrow().text_system.clone() |
| 224 | } |
| 225 | |
| 226 | /// Returns the file URL of the executable with the specified name in the application bundle |
| 227 | pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> { |
| 228 | self.0.borrow().path_for_auxiliary_executable(name) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>; |
| 233 | type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>; |
| 234 | pub(crate) type KeystrokeObserver = |
| 235 | Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>; |
| 236 | type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>; |
| 237 | type WindowClosedHandler = Box<dyn FnMut(&mut App)>; |
| 238 | type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>; |
| 239 | type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>; |
| 240 | |
| 241 | #[doc(hidden)] |
| 242 | #[derive(Clone, PartialEq, Eq)] |
| 243 | pub struct SystemWindowTab { |
| 244 | pub id: WindowId, |
| 245 | pub title: SharedString, |
| 246 | pub handle: AnyWindowHandle, |
| 247 | pub last_active_at: Instant, |
| 248 | } |
| 249 | |
| 250 | impl SystemWindowTab { |
| 251 | /// Create a new instance of the window tab. |
| 252 | pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self { |
| 253 | Self { |
| 254 | id: handle.id, |
| 255 | title, |
| 256 | handle, |
| 257 | last_active_at: Instant::now(), |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | /// A controller for managing window tabs. |
| 263 | #[derive(Default)] |
| 264 | pub struct SystemWindowTabController { |
| 265 | visible: Option<bool>, |
| 266 | tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>, |
| 267 | } |
| 268 | |
| 269 | impl Global for SystemWindowTabController {} |
| 270 | |
| 271 | impl SystemWindowTabController { |
| 272 | /// Create a new instance of the window tab controller. |
| 273 | pub fn new() -> Self { |
| 274 | Self { |
| 275 | visible: None, |
| 276 | tab_groups: FxHashMap::default(), |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// Initialize the global window tab controller. |
| 281 | pub fn init(cx: &mut App) { |
| 282 | cx.set_global(SystemWindowTabController::new()); |
| 283 | } |
| 284 | |
| 285 | /// Get all tab groups. |
| 286 | pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> { |
| 287 | &self.tab_groups |
| 288 | } |
| 289 | |
| 290 | /// Get the next tab group window handle. |
| 291 | pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> { |
| 292 | let controller = cx.global::<SystemWindowTabController>(); |
| 293 | let current_group = controller |
| 294 | .tab_groups |
| 295 | .iter() |
| 296 | .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group)); |
| 297 | |
| 298 | let current_group = current_group?; |
| 299 | let mut group_ids: Vec<_> = controller.tab_groups.keys().collect(); |
| 300 | let idx = group_ids.iter().position(|g| *g == current_group)?; |
| 301 | let next_idx = (idx + 1) % group_ids.len(); |
| 302 | |
| 303 | controller |
| 304 | .tab_groups |
| 305 | .get(group_ids[next_idx]) |
| 306 | .and_then(|tabs| { |
| 307 | tabs.iter() |
| 308 | .max_by_key(|tab| tab.last_active_at) |
| 309 | .or_else(|| tabs.first()) |
| 310 | .map(|tab| &tab.handle) |
| 311 | }) |
| 312 | } |
| 313 | |
| 314 | /// Get the previous tab group window handle. |
| 315 | pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> { |
| 316 | let controller = cx.global::<SystemWindowTabController>(); |
| 317 | let current_group = controller |
| 318 | .tab_groups |
| 319 | .iter() |
| 320 | .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group)); |
| 321 | |
| 322 | let current_group = current_group?; |
| 323 | let mut group_ids: Vec<_> = controller.tab_groups.keys().collect(); |
| 324 | let idx = group_ids.iter().position(|g| *g == current_group)?; |
| 325 | let prev_idx = if idx == 0 { |
| 326 | group_ids.len() - 1 |
| 327 | } else { |
| 328 | idx - 1 |
| 329 | }; |
| 330 | |
| 331 | controller |
| 332 | .tab_groups |
| 333 | .get(group_ids[prev_idx]) |
| 334 | .and_then(|tabs| { |
| 335 | tabs.iter() |
| 336 | .max_by_key(|tab| tab.last_active_at) |
| 337 | .or_else(|| tabs.first()) |
| 338 | .map(|tab| &tab.handle) |
| 339 | }) |
| 340 | } |
| 341 | |
| 342 | /// Get all tabs in the same window. |
| 343 | pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> { |
| 344 | let tab_group = self |
| 345 | .tab_groups |
| 346 | .iter() |
| 347 | .find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| *group))?; |
| 348 | |
| 349 | self.tab_groups.get(&tab_group) |
| 350 | } |
| 351 | |
| 352 | /// Initialize the visibility of the system window tab controller. |
| 353 | pub fn init_visible(cx: &mut App, visible: bool) { |
| 354 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 355 | if controller.visible.is_none() { |
| 356 | controller.visible = Some(visible); |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /// Get the visibility of the system window tab controller. |
| 361 | pub fn is_visible(&self) -> bool { |
| 362 | self.visible.unwrap_or(false) |
| 363 | } |
| 364 | |
| 365 | /// Set the visibility of the system window tab controller. |
| 366 | pub fn set_visible(cx: &mut App, visible: bool) { |
| 367 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 368 | controller.visible = Some(visible); |
| 369 | } |
| 370 | |
| 371 | /// Update the last active of a window. |
| 372 | pub fn update_last_active(cx: &mut App, id: WindowId) { |
| 373 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 374 | for windows in controller.tab_groups.values_mut() { |
| 375 | for tab in windows.iter_mut() { |
| 376 | if tab.id == id { |
| 377 | tab.last_active_at = Instant::now(); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | /// Update the position of a tab within its group. |
| 384 | pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) { |
| 385 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 386 | for (_, windows) in controller.tab_groups.iter_mut() { |
| 387 | if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) { |
| 388 | if ix < windows.len() && current_pos != ix { |
| 389 | let window_tab = windows.remove(current_pos); |
| 390 | windows.insert(ix, window_tab); |
| 391 | } |
| 392 | break; |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// Update the title of a tab. |
| 398 | pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) { |
| 399 | let controller = cx.global::<SystemWindowTabController>(); |
| 400 | let tab = controller |
| 401 | .tab_groups |
| 402 | .values() |
| 403 | .flat_map(|windows| windows.iter()) |
| 404 | .find(|tab| tab.id == id); |
| 405 | |
| 406 | if tab.map_or(true, |t| t.title == title) { |
| 407 | return; |
| 408 | } |
| 409 | |
| 410 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 411 | for windows in controller.tab_groups.values_mut() { |
| 412 | for tab in windows.iter_mut() { |
| 413 | if tab.id == id { |
| 414 | tab.title = title; |
| 415 | return; |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | /// Insert a tab into a tab group. |
| 422 | pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) { |
| 423 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 424 | let Some(tab) = tabs.clone().into_iter().find(|tab| tab.id == id) else { |
| 425 | return; |
| 426 | }; |
| 427 | |
| 428 | let mut expected_tab_ids: Vec<_> = tabs |
| 429 | .iter() |
| 430 | .filter(|tab| tab.id != id) |
| 431 | .map(|tab| tab.id) |
| 432 | .sorted() |
| 433 | .collect(); |
| 434 | |
| 435 | let mut tab_group_id = None; |
| 436 | for (group_id, group_tabs) in &controller.tab_groups { |
| 437 | let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect(); |
| 438 | if tab_ids == expected_tab_ids { |
| 439 | tab_group_id = Some(*group_id); |
| 440 | break; |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | if let Some(tab_group_id) = tab_group_id { |
| 445 | if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) { |
| 446 | tabs.push(tab); |
| 447 | } |
| 448 | } else { |
| 449 | let new_group_id = controller.tab_groups.len(); |
| 450 | controller.tab_groups.insert(new_group_id, tabs); |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | /// Remove a tab from a tab group. |
| 455 | pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> { |
| 456 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 457 | let mut removed_tab = None; |
| 458 | |
| 459 | controller.tab_groups.retain(|_, tabs| { |
| 460 | if let Some(pos) = tabs.iter().position(|tab| tab.id == id) { |
| 461 | removed_tab = Some(tabs.remove(pos)); |
| 462 | } |
| 463 | !tabs.is_empty() |
| 464 | }); |
| 465 | |
| 466 | removed_tab |
| 467 | } |
| 468 | |
| 469 | /// Move a tab to a new tab group. |
| 470 | pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) { |
| 471 | let mut removed_tab = Self::remove_tab(cx, id); |
| 472 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 473 | |
| 474 | if let Some(tab) = removed_tab { |
| 475 | let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1); |
| 476 | controller.tab_groups.insert(new_group_id, vec![tab]); |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// Merge all tab groups into a single group. |
| 481 | pub fn merge_all_windows(cx: &mut App, id: WindowId) { |
| 482 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 483 | let Some(initial_tabs) = controller.tabs(id) else { |
| 484 | return; |
| 485 | }; |
| 486 | |
| 487 | let mut all_tabs = initial_tabs.clone(); |
| 488 | for tabs in controller.tab_groups.values() { |
| 489 | all_tabs.extend( |
| 490 | tabs.iter() |
| 491 | .filter(|tab| !initial_tabs.contains(tab)) |
| 492 | .cloned(), |
| 493 | ); |
| 494 | } |
| 495 | |
| 496 | controller.tab_groups.clear(); |
| 497 | controller.tab_groups.insert(0, all_tabs); |
| 498 | } |
| 499 | |
| 500 | /// Selects the next tab in the tab group in the trailing direction. |
| 501 | pub fn select_next_tab(cx: &mut App, id: WindowId) { |
| 502 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 503 | let Some(tabs) = controller.tabs(id) else { |
| 504 | return; |
| 505 | }; |
| 506 | |
| 507 | let current_index = tabs.iter().position(|tab| tab.id == id).unwrap(); |
| 508 | let next_index = (current_index + 1) % tabs.len(); |
| 509 | |
| 510 | let _ = &tabs[next_index].handle.update(cx, |_, window, _| { |
| 511 | window.activate_window(); |
| 512 | }); |
| 513 | } |
| 514 | |
| 515 | /// Selects the previous tab in the tab group in the leading direction. |
| 516 | pub fn select_previous_tab(cx: &mut App, id: WindowId) { |
| 517 | let mut controller = cx.global_mut::<SystemWindowTabController>(); |
| 518 | let Some(tabs) = controller.tabs(id) else { |
| 519 | return; |
| 520 | }; |
| 521 | |
| 522 | let current_index = tabs.iter().position(|tab| tab.id == id).unwrap(); |
| 523 | let previous_index = if current_index == 0 { |
| 524 | tabs.len() - 1 |
| 525 | } else { |
| 526 | current_index - 1 |
| 527 | }; |
| 528 | |
| 529 | let _ = &tabs[previous_index].handle.update(cx, |_, window, _| { |
| 530 | window.activate_window(); |
| 531 | }); |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// Contains the state of the full application, and passed as a reference to a variety of callbacks. |
| 536 | /// Other [Context] derefs to this type. |
| 537 | /// You need a reference to an `App` to access the state of a [Entity]. |
| 538 | pub struct App { |
| 539 | pub(crate) this: Weak<AppCell>, |
| 540 | pub(crate) platform: Rc<dyn Platform>, |
| 541 | text_system: Arc<TextSystem>, |
| 542 | flushing_effects: bool, |
| 543 | pending_updates: usize, |
| 544 | pub(crate) actions: Rc<ActionRegistry>, |
| 545 | pub(crate) active_drag: Option<AnyDrag>, |
| 546 | pub(crate) background_executor: BackgroundExecutor, |
| 547 | pub(crate) foreground_executor: ForegroundExecutor, |
| 548 | pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>, |
| 549 | asset_source: Arc<dyn AssetSource>, |
| 550 | pub(crate) svg_renderer: SvgRenderer, |
| 551 | http_client: Arc<dyn HttpClient>, |
| 552 | pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>, |
| 553 | pub(crate) entities: EntityMap, |
| 554 | pub(crate) window_update_stack: Vec<WindowId>, |
| 555 | pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>, |
| 556 | pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>, |
| 557 | pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>, |
| 558 | pub(crate) focus_handles: Arc<FocusMap>, |
| 559 | pub(crate) keymap: Rc<RefCell<Keymap>>, |
| 560 | pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>, |
| 561 | pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>, |
| 562 | pub(crate) global_action_listeners: |
| 563 | FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>, |
| 564 | pending_effects: VecDeque<Effect>, |
| 565 | pub(crate) pending_notifications: FxHashSet<EntityId>, |
| 566 | pub(crate) pending_global_notifications: FxHashSet<TypeId>, |
| 567 | pub(crate) observers: SubscriberSet<EntityId, Handler>, |
| 568 | // TypeId is the type of the event that the listener callback expects |
| 569 | pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>, |
| 570 | pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>, |
| 571 | pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>, |
| 572 | pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>, |
| 573 | pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>, |
| 574 | pub(crate) global_observers: SubscriberSet<TypeId, Handler>, |
| 575 | pub(crate) quit_observers: SubscriberSet<(), QuitHandler>, |
| 576 | pub(crate) restart_observers: SubscriberSet<(), Handler>, |
| 577 | pub(crate) restart_path: Option<PathBuf>, |
| 578 | pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>, |
| 579 | pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests. |
| 580 | pub(crate) propagate_event: bool, |
| 581 | pub(crate) prompt_builder: Option<PromptBuilder>, |
| 582 | pub(crate) window_invalidators_by_entity: |
| 583 | FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>, |
| 584 | pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>, |
| 585 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 586 | pub(crate) inspector_renderer: Option<crate::InspectorRenderer>, |
| 587 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 588 | pub(crate) inspector_element_registry: InspectorElementRegistry, |
| 589 | #[cfg(any(test, feature = "test-support", debug_assertions))] |
| 590 | pub(crate) name: Option<&'static str>, |
| 591 | quitting: bool, |
| 592 | } |
| 593 | |
| 594 | impl App { |
| 595 | #[allow(clippy::new_ret_no_self)] |
| 596 | pub(crate) fn new_app( |
| 597 | platform: Rc<dyn Platform>, |
| 598 | asset_source: Arc<dyn AssetSource>, |
| 599 | http_client: Arc<dyn HttpClient>, |
| 600 | ) -> Rc<AppCell> { |
| 601 | let executor = platform.background_executor(); |
| 602 | let foreground_executor = platform.foreground_executor(); |
| 603 | assert!( |
| 604 | executor.is_main_thread(), |
| 605 | "must construct App on main thread" |
| 606 | ); |
| 607 | |
| 608 | let text_system = Arc::new(TextSystem::new(platform.text_system())); |
| 609 | let entities = EntityMap::new(); |
| 610 | let keyboard_layout = platform.keyboard_layout(); |
| 611 | let keyboard_mapper = platform.keyboard_mapper(); |
| 612 | |
| 613 | let app = Rc::new_cyclic(|this| AppCell { |
| 614 | app: RefCell::new(App { |
| 615 | this: this.clone(), |
| 616 | platform: platform.clone(), |
| 617 | text_system, |
| 618 | actions: Rc::new(ActionRegistry::default()), |
| 619 | flushing_effects: false, |
| 620 | pending_updates: 0, |
| 621 | active_drag: None, |
| 622 | background_executor: executor, |
| 623 | foreground_executor, |
| 624 | svg_renderer: SvgRenderer::new(asset_source.clone()), |
| 625 | loading_assets: Default::default(), |
| 626 | asset_source, |
| 627 | http_client, |
| 628 | globals_by_type: FxHashMap::default(), |
| 629 | entities, |
| 630 | new_entity_observers: SubscriberSet::new(), |
| 631 | windows: SlotMap::with_key(), |
| 632 | window_update_stack: Vec::new(), |
| 633 | window_handles: FxHashMap::default(), |
| 634 | focus_handles: Arc::new(RwLock::new(SlotMap::with_key())), |
| 635 | keymap: Rc::new(RefCell::new(Keymap::default())), |
| 636 | keyboard_layout, |
| 637 | keyboard_mapper, |
| 638 | global_action_listeners: FxHashMap::default(), |
| 639 | pending_effects: VecDeque::new(), |
| 640 | pending_notifications: FxHashSet::default(), |
| 641 | pending_global_notifications: FxHashSet::default(), |
| 642 | observers: SubscriberSet::new(), |
| 643 | tracked_entities: FxHashMap::default(), |
| 644 | window_invalidators_by_entity: FxHashMap::default(), |
| 645 | event_listeners: SubscriberSet::new(), |
| 646 | release_listeners: SubscriberSet::new(), |
| 647 | keystroke_observers: SubscriberSet::new(), |
| 648 | keystroke_interceptors: SubscriberSet::new(), |
| 649 | keyboard_layout_observers: SubscriberSet::new(), |
| 650 | global_observers: SubscriberSet::new(), |
| 651 | quit_observers: SubscriberSet::new(), |
| 652 | restart_observers: SubscriberSet::new(), |
| 653 | restart_path: None, |
| 654 | window_closed_observers: SubscriberSet::new(), |
| 655 | layout_id_buffer: Default::default(), |
| 656 | propagate_event: true, |
| 657 | prompt_builder: Some(PromptBuilder::Default), |
| 658 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 659 | inspector_renderer: None, |
| 660 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 661 | inspector_element_registry: InspectorElementRegistry::default(), |
| 662 | quitting: false, |
| 663 | |
| 664 | #[cfg(any(test, feature = "test-support", debug_assertions))] |
| 665 | name: None, |
| 666 | }), |
| 667 | }); |
| 668 | |
| 669 | init_app_menus(platform.as_ref(), &app.borrow()); |
| 670 | SystemWindowTabController::init(&mut app.borrow_mut()); |
| 671 | |
| 672 | platform.on_keyboard_layout_change(Box::new({ |
| 673 | let app = Rc::downgrade(&app); |
| 674 | move || { |
| 675 | if let Some(app) = app.upgrade() { |
| 676 | let cx = &mut app.borrow_mut(); |
| 677 | cx.keyboard_layout = cx.platform.keyboard_layout(); |
| 678 | cx.keyboard_mapper = cx.platform.keyboard_mapper(); |
| 679 | cx.keyboard_layout_observers |
| 680 | .clone() |
| 681 | .retain(&(), move |callback| (callback)(cx)); |
| 682 | } |
| 683 | } |
| 684 | })); |
| 685 | |
| 686 | platform.on_quit(Box::new({ |
| 687 | let cx = app.clone(); |
| 688 | move || { |
| 689 | cx.borrow_mut().shutdown(); |
| 690 | } |
| 691 | })); |
| 692 | |
| 693 | app |
| 694 | } |
| 695 | |
| 696 | /// Quit the application gracefully. Handlers registered with [`Context::on_app_quit`] |
| 697 | /// will be given 100ms to complete before exiting. |
| 698 | pub fn shutdown(&mut self) { |
| 699 | let mut futures = Vec::new(); |
| 700 | |
| 701 | for observer in self.quit_observers.remove(&()) { |
| 702 | futures.push(observer(self)); |
| 703 | } |
| 704 | |
| 705 | self.windows.clear(); |
| 706 | self.window_handles.clear(); |
| 707 | self.flush_effects(); |
| 708 | self.quitting = true; |
| 709 | |
| 710 | let futures = futures::future::join_all(futures); |
| 711 | if self |
| 712 | .background_executor |
| 713 | .block_with_timeout(SHUTDOWN_TIMEOUT, futures) |
| 714 | .is_err() |
| 715 | { |
| 716 | log::error!("timed out waiting on app_will_quit"); |
| 717 | } |
| 718 | |
| 719 | self.quitting = false; |
| 720 | } |
| 721 | |
| 722 | /// Get the id of the current keyboard layout |
| 723 | pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout { |
| 724 | self.keyboard_layout.as_ref() |
| 725 | } |
| 726 | |
| 727 | /// Get the current keyboard mapper. |
| 728 | pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> { |
| 729 | &self.keyboard_mapper |
| 730 | } |
| 731 | |
| 732 | /// Invokes a handler when the current keyboard layout changes |
| 733 | pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription |
| 734 | where |
| 735 | F: 'static + FnMut(&mut App), |
| 736 | { |
| 737 | let (subscription, activate) = self.keyboard_layout_observers.insert( |
| 738 | (), |
| 739 | Box::new(move |cx| { |
| 740 | callback(cx); |
| 741 | true |
| 742 | }), |
| 743 | ); |
| 744 | activate(); |
| 745 | subscription |
| 746 | } |
| 747 | |
| 748 | /// Gracefully quit the application via the platform's standard routine. |
| 749 | pub fn quit(&self) { |
| 750 | self.platform.quit(); |
| 751 | } |
| 752 | |
| 753 | /// Schedules all windows in the application to be redrawn. This can be called |
| 754 | /// multiple times in an update cycle and still result in a single redraw. |
| 755 | pub fn refresh_windows(&mut self) { |
| 756 | self.pending_effects.push_back(Effect::RefreshWindows); |
| 757 | } |
| 758 | |
| 759 | pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R { |
| 760 | self.start_update(); |
| 761 | let result = update(self); |
| 762 | self.finish_update(); |
| 763 | result |
| 764 | } |
| 765 | |
| 766 | pub(crate) fn start_update(&mut self) { |
| 767 | self.pending_updates += 1; |
| 768 | } |
| 769 | |
| 770 | pub(crate) fn finish_update(&mut self) { |
| 771 | if !self.flushing_effects && self.pending_updates == 1 { |
| 772 | self.flushing_effects = true; |
| 773 | self.flush_effects(); |
| 774 | self.flushing_effects = false; |
| 775 | } |
| 776 | self.pending_updates -= 1; |
| 777 | } |
| 778 | |
| 779 | /// Arrange a callback to be invoked when the given entity calls `notify` on its respective context. |
| 780 | pub fn observe<W>( |
| 781 | &mut self, |
| 782 | entity: &Entity<W>, |
| 783 | mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static, |
| 784 | ) -> Subscription |
| 785 | where |
| 786 | W: 'static, |
| 787 | { |
| 788 | self.observe_internal(entity, move |e, cx| { |
| 789 | on_notify(e, cx); |
| 790 | true |
| 791 | }) |
| 792 | } |
| 793 | |
| 794 | pub(crate) fn detect_accessed_entities<R>( |
| 795 | &mut self, |
| 796 | callback: impl FnOnce(&mut App) -> R, |
| 797 | ) -> (R, FxHashSet<EntityId>) { |
| 798 | let accessed_entities_start = self.entities.accessed_entities.borrow().clone(); |
| 799 | let result = callback(self); |
| 800 | let accessed_entities_end = self.entities.accessed_entities.borrow().clone(); |
| 801 | let entities_accessed_in_callback = accessed_entities_end |
| 802 | .difference(&accessed_entities_start) |
| 803 | .copied() |
| 804 | .collect::<FxHashSet<EntityId>>(); |
| 805 | (result, entities_accessed_in_callback) |
| 806 | } |
| 807 | |
| 808 | pub(crate) fn record_entities_accessed( |
| 809 | &mut self, |
| 810 | window_handle: AnyWindowHandle, |
| 811 | invalidator: WindowInvalidator, |
| 812 | entities: &FxHashSet<EntityId>, |
| 813 | ) { |
| 814 | let mut tracked_entities = |
| 815 | std::mem::take(self.tracked_entities.entry(window_handle.id).or_default()); |
| 816 | for entity in tracked_entities.iter() { |
| 817 | self.window_invalidators_by_entity |
| 818 | .entry(*entity) |
| 819 | .and_modify(|windows| { |
| 820 | windows.remove(&window_handle.id); |
| 821 | }); |
| 822 | } |
| 823 | for entity in entities.iter() { |
| 824 | self.window_invalidators_by_entity |
| 825 | .entry(*entity) |
| 826 | .or_default() |
| 827 | .insert(window_handle.id, invalidator.clone()); |
| 828 | } |
| 829 | tracked_entities.clear(); |
| 830 | tracked_entities.extend(entities.iter().copied()); |
| 831 | self.tracked_entities |
| 832 | .insert(window_handle.id, tracked_entities); |
| 833 | } |
| 834 | |
| 835 | pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription { |
| 836 | let (subscription, activate) = self.observers.insert(key, value); |
| 837 | self.defer(move |_| activate()); |
| 838 | subscription |
| 839 | } |
| 840 | |
| 841 | pub(crate) fn observe_internal<W>( |
| 842 | &mut self, |
| 843 | entity: &Entity<W>, |
| 844 | mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static, |
| 845 | ) -> Subscription |
| 846 | where |
| 847 | W: 'static, |
| 848 | { |
| 849 | let entity_id = entity.entity_id(); |
| 850 | let handle = entity.downgrade(); |
| 851 | self.new_observer( |
| 852 | entity_id, |
| 853 | Box::new(move |cx| { |
| 854 | if let Some(entity) = handle.upgrade() { |
| 855 | on_notify(entity, cx) |
| 856 | } else { |
| 857 | false |
| 858 | } |
| 859 | }), |
| 860 | ) |
| 861 | } |
| 862 | |
| 863 | /// Arrange for the given callback to be invoked whenever the given entity emits an event of a given type. |
| 864 | /// The callback is provided a handle to the emitting entity and a reference to the emitted event. |
| 865 | pub fn subscribe<T, Event>( |
| 866 | &mut self, |
| 867 | entity: &Entity<T>, |
| 868 | mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static, |
| 869 | ) -> Subscription |
| 870 | where |
| 871 | T: 'static + EventEmitter<Event>, |
| 872 | Event: 'static, |
| 873 | { |
| 874 | self.subscribe_internal(entity, move |entity, event, cx| { |
| 875 | on_event(entity, event, cx); |
| 876 | true |
| 877 | }) |
| 878 | } |
| 879 | |
| 880 | pub(crate) fn new_subscription( |
| 881 | &mut self, |
| 882 | key: EntityId, |
| 883 | value: (TypeId, Listener), |
| 884 | ) -> Subscription { |
| 885 | let (subscription, activate) = self.event_listeners.insert(key, value); |
| 886 | self.defer(move |_| activate()); |
| 887 | subscription |
| 888 | } |
| 889 | pub(crate) fn subscribe_internal<T, Evt>( |
| 890 | &mut self, |
| 891 | entity: &Entity<T>, |
| 892 | mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static, |
| 893 | ) -> Subscription |
| 894 | where |
| 895 | T: 'static + EventEmitter<Evt>, |
| 896 | Evt: 'static, |
| 897 | { |
| 898 | let entity_id = entity.entity_id(); |
| 899 | let handle = entity.downgrade(); |
| 900 | self.new_subscription( |
| 901 | entity_id, |
| 902 | ( |
| 903 | TypeId::of::<Evt>(), |
| 904 | Box::new(move |event, cx| { |
| 905 | let event: &Evt = event.downcast_ref().expect("invalid event type"); |
| 906 | if let Some(entity) = handle.upgrade() { |
| 907 | on_event(entity, event, cx) |
| 908 | } else { |
| 909 | false |
| 910 | } |
| 911 | }), |
| 912 | ), |
| 913 | ) |
| 914 | } |
| 915 | |
| 916 | /// Returns handles to all open windows in the application. |
| 917 | /// Each handle could be downcast to a handle typed for the root view of that window. |
| 918 | /// To find all windows of a given type, you could filter on |
| 919 | pub fn windows(&self) -> Vec<AnyWindowHandle> { |
| 920 | self.windows |
| 921 | .keys() |
| 922 | .flat_map(|window_id| self.window_handles.get(&window_id).copied()) |
| 923 | .collect() |
| 924 | } |
| 925 | |
| 926 | /// Returns the window handles ordered by their appearance on screen, front to back. |
| 927 | /// |
| 928 | /// The first window in the returned list is the active/topmost window of the application. |
| 929 | /// |
| 930 | /// This method returns None if the platform doesn't implement the method yet. |
| 931 | pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> { |
| 932 | self.platform.window_stack() |
| 933 | } |
| 934 | |
| 935 | /// Returns a handle to the window that is currently focused at the platform level, if one exists. |
| 936 | pub fn active_window(&self) -> Option<AnyWindowHandle> { |
| 937 | self.platform.active_window() |
| 938 | } |
| 939 | |
| 940 | /// Opens a new window with the given option and the root view returned by the given function. |
| 941 | /// The function is invoked with a `Window`, which can be used to interact with window-specific |
| 942 | /// functionality. |
| 943 | pub fn open_window<V: 'static + Render>( |
| 944 | &mut self, |
| 945 | options: crate::WindowOptions, |
| 946 | build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>, |
| 947 | ) -> anyhow::Result<WindowHandle<V>> { |
| 948 | self.update(|cx| { |
| 949 | let id = cx.windows.insert(None); |
| 950 | let handle = WindowHandle::new(id); |
| 951 | match Window::new(handle.into(), options, cx) { |
| 952 | Ok(mut window) => { |
| 953 | cx.window_update_stack.push(id); |
| 954 | let root_view = build_root_view(&mut window, cx); |
| 955 | cx.window_update_stack.pop(); |
| 956 | window.root.replace(root_view.into()); |
| 957 | window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx)); |
| 958 | |
| 959 | // allow a window to draw at least once before returning |
| 960 | // this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame |
| 961 | // on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash |
| 962 | // where DispatchTree::root_node_id asserts on empty nodes |
| 963 | let clear = window.draw(cx); |
| 964 | clear.clear(); |
| 965 | |
| 966 | cx.window_handles.insert(id, window.handle); |
| 967 | cx.windows.get_mut(id).unwrap().replace(Box::new(window)); |
| 968 | Ok(handle) |
| 969 | } |
| 970 | Err(e) => { |
| 971 | cx.windows.remove(id); |
| 972 | Err(e) |
| 973 | } |
| 974 | } |
| 975 | }) |
| 976 | } |
| 977 | |
| 978 | /// Instructs the platform to activate the application by bringing it to the foreground. |
| 979 | pub fn activate(&self, ignoring_other_apps: bool) { |
| 980 | self.platform.activate(ignoring_other_apps); |
| 981 | } |
| 982 | |
| 983 | /// Hide the application at the platform level. |
| 984 | pub fn hide(&self) { |
| 985 | self.platform.hide(); |
| 986 | } |
| 987 | |
| 988 | /// Hide other applications at the platform level. |
| 989 | pub fn hide_other_apps(&self) { |
| 990 | self.platform.hide_other_apps(); |
| 991 | } |
| 992 | |
| 993 | /// Unhide other applications at the platform level. |
| 994 | pub fn unhide_other_apps(&self) { |
| 995 | self.platform.unhide_other_apps(); |
| 996 | } |
| 997 | |
| 998 | /// Returns the list of currently active displays. |
| 999 | pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> { |
| 1000 | self.platform.displays() |
| 1001 | } |
| 1002 | |
| 1003 | /// Returns the primary display that will be used for new windows. |
| 1004 | pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> { |
| 1005 | self.platform.primary_display() |
| 1006 | } |
| 1007 | |
| 1008 | /// Returns whether `screen_capture_sources` may work. |
| 1009 | pub fn is_screen_capture_supported(&self) -> bool { |
| 1010 | self.platform.is_screen_capture_supported() |
| 1011 | } |
| 1012 | |
| 1013 | /// Returns a list of available screen capture sources. |
| 1014 | pub fn screen_capture_sources( |
| 1015 | &self, |
| 1016 | ) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> { |
| 1017 | self.platform.screen_capture_sources() |
| 1018 | } |
| 1019 | |
| 1020 | /// Returns the display with the given ID, if one exists. |
| 1021 | pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> { |
| 1022 | self.displays() |
| 1023 | .iter() |
| 1024 | .find(|display| display.id() == id) |
| 1025 | .cloned() |
| 1026 | } |
| 1027 | |
| 1028 | /// Returns the appearance of the application's windows. |
| 1029 | pub fn window_appearance(&self) -> WindowAppearance { |
| 1030 | self.platform.window_appearance() |
| 1031 | } |
| 1032 | |
| 1033 | /// Writes data to the primary selection buffer. |
| 1034 | /// Only available on Linux. |
| 1035 | #[cfg(any(target_os = "linux", target_os = "freebsd"))] |
| 1036 | pub fn write_to_primary(&self, item: ClipboardItem) { |
| 1037 | self.platform.write_to_primary(item) |
| 1038 | } |
| 1039 | |
| 1040 | /// Writes data to the platform clipboard. |
| 1041 | pub fn write_to_clipboard(&self, item: ClipboardItem) { |
| 1042 | self.platform.write_to_clipboard(item) |
| 1043 | } |
| 1044 | |
| 1045 | /// Reads data from the primary selection buffer. |
| 1046 | /// Only available on Linux. |
| 1047 | #[cfg(any(target_os = "linux", target_os = "freebsd"))] |
| 1048 | pub fn read_from_primary(&self) -> Option<ClipboardItem> { |
| 1049 | self.platform.read_from_primary() |
| 1050 | } |
| 1051 | |
| 1052 | /// Reads data from the platform clipboard. |
| 1053 | pub fn read_from_clipboard(&self) -> Option<ClipboardItem> { |
| 1054 | self.platform.read_from_clipboard() |
| 1055 | } |
| 1056 | |
| 1057 | /// Writes credentials to the platform keychain. |
| 1058 | pub fn write_credentials( |
| 1059 | &self, |
| 1060 | url: &str, |
| 1061 | username: &str, |
| 1062 | password: &[u8], |
| 1063 | ) -> Task<Result<()>> { |
| 1064 | self.platform.write_credentials(url, username, password) |
| 1065 | } |
| 1066 | |
| 1067 | /// Reads credentials from the platform keychain. |
| 1068 | pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> { |
| 1069 | self.platform.read_credentials(url) |
| 1070 | } |
| 1071 | |
| 1072 | /// Deletes credentials from the platform keychain. |
| 1073 | pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> { |
| 1074 | self.platform.delete_credentials(url) |
| 1075 | } |
| 1076 | |
| 1077 | /// Directs the platform's default browser to open the given URL. |
| 1078 | pub fn open_url(&self, url: &str) { |
| 1079 | self.platform.open_url(url); |
| 1080 | } |
| 1081 | |
| 1082 | /// Registers the given URL scheme (e.g. `zed` for `zed://` urls) to be |
| 1083 | /// opened by the current app. |
| 1084 | /// |
| 1085 | /// On some platforms (e.g. macOS) you may be able to register URL schemes |
| 1086 | /// as part of app distribution, but this method exists to let you register |
| 1087 | /// schemes at runtime. |
| 1088 | pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> { |
| 1089 | self.platform.register_url_scheme(scheme) |
| 1090 | } |
| 1091 | |
| 1092 | /// Returns the full pathname of the current app bundle. |
| 1093 | /// |
| 1094 | /// Returns an error if the app is not being run from a bundle. |
| 1095 | pub fn app_path(&self) -> Result<PathBuf> { |
| 1096 | self.platform.app_path() |
| 1097 | } |
| 1098 | |
| 1099 | /// On Linux, returns the name of the compositor in use. |
| 1100 | /// |
| 1101 | /// Returns an empty string on other platforms. |
| 1102 | pub fn compositor_name(&self) -> &'static str { |
| 1103 | self.platform.compositor_name() |
| 1104 | } |
| 1105 | |
| 1106 | /// Returns the file URL of the executable with the specified name in the application bundle |
| 1107 | pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> { |
| 1108 | self.platform.path_for_auxiliary_executable(name) |
| 1109 | } |
| 1110 | |
| 1111 | /// Displays a platform modal for selecting paths. |
| 1112 | /// |
| 1113 | /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel. |
| 1114 | /// If cancelled, a `None` will be relayed instead. |
| 1115 | /// May return an error on Linux if the file picker couldn't be opened. |
| 1116 | pub fn prompt_for_paths( |
| 1117 | &self, |
| 1118 | options: PathPromptOptions, |
| 1119 | ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> { |
| 1120 | self.platform.prompt_for_paths(options) |
| 1121 | } |
| 1122 | |
| 1123 | /// Displays a platform modal for selecting a new path where a file can be saved. |
| 1124 | /// |
| 1125 | /// The provided directory will be used to set the initial location. |
| 1126 | /// When a path is selected, it is relayed asynchronously via the returned oneshot channel. |
| 1127 | /// If cancelled, a `None` will be relayed instead. |
| 1128 | /// May return an error on Linux if the file picker couldn't be opened. |
| 1129 | pub fn prompt_for_new_path( |
| 1130 | &self, |
| 1131 | directory: &Path, |
| 1132 | suggested_name: Option<&str>, |
| 1133 | ) -> oneshot::Receiver<Result<Option<PathBuf>>> { |
| 1134 | self.platform.prompt_for_new_path(directory, suggested_name) |
| 1135 | } |
| 1136 | |
| 1137 | /// Reveals the specified path at the platform level, such as in Finder on macOS. |
| 1138 | pub fn reveal_path(&self, path: &Path) { |
| 1139 | self.platform.reveal_path(path) |
| 1140 | } |
| 1141 | |
| 1142 | /// Opens the specified path with the system's default application. |
| 1143 | pub fn open_with_system(&self, path: &Path) { |
| 1144 | self.platform.open_with_system(path) |
| 1145 | } |
| 1146 | |
| 1147 | /// Returns whether the user has configured scrollbars to auto-hide at the platform level. |
| 1148 | pub fn should_auto_hide_scrollbars(&self) -> bool { |
| 1149 | self.platform.should_auto_hide_scrollbars() |
| 1150 | } |
| 1151 | |
| 1152 | /// Restarts the application. |
| 1153 | pub fn restart(&mut self) { |
| 1154 | self.restart_observers |
| 1155 | .clone() |
| 1156 | .retain(&(), |observer| observer(self)); |
| 1157 | self.platform.restart(self.restart_path.take()) |
| 1158 | } |
| 1159 | |
| 1160 | /// Sets the path to use when restarting the application. |
| 1161 | pub fn set_restart_path(&mut self, path: PathBuf) { |
| 1162 | self.restart_path = Some(path); |
| 1163 | } |
| 1164 | |
| 1165 | /// Returns the HTTP client for the application. |
| 1166 | pub fn http_client(&self) -> Arc<dyn HttpClient> { |
| 1167 | self.http_client.clone() |
| 1168 | } |
| 1169 | |
| 1170 | /// Sets the HTTP client for the application. |
| 1171 | pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) { |
| 1172 | self.http_client = new_client; |
| 1173 | } |
| 1174 | |
| 1175 | /// Returns the SVG renderer used by the application. |
| 1176 | pub fn svg_renderer(&self) -> SvgRenderer { |
| 1177 | self.svg_renderer.clone() |
| 1178 | } |
| 1179 | |
| 1180 | pub(crate) fn push_effect(&mut self, effect: Effect) { |
| 1181 | match &effect { |
| 1182 | Effect::Notify { emitter } => { |
| 1183 | if !self.pending_notifications.insert(*emitter) { |
| 1184 | return; |
| 1185 | } |
| 1186 | } |
| 1187 | Effect::NotifyGlobalObservers { global_type } => { |
| 1188 | if !self.pending_global_notifications.insert(*global_type) { |
| 1189 | return; |
| 1190 | } |
| 1191 | } |
| 1192 | _ => {} |
| 1193 | }; |
| 1194 | |
| 1195 | self.pending_effects.push_back(effect); |
| 1196 | } |
| 1197 | |
| 1198 | /// Called at the end of [`App::update`] to complete any side effects |
| 1199 | /// such as notifying observers, emitting events, etc. Effects can themselves |
| 1200 | /// cause effects, so we continue looping until all effects are processed. |
| 1201 | fn flush_effects(&mut self) { |
| 1202 | loop { |
| 1203 | self.release_dropped_entities(); |
| 1204 | self.release_dropped_focus_handles(); |
| 1205 | if let Some(effect) = self.pending_effects.pop_front() { |
| 1206 | match effect { |
| 1207 | Effect::Notify { emitter } => { |
| 1208 | self.apply_notify_effect(emitter); |
| 1209 | } |
| 1210 | |
| 1211 | Effect::Emit { |
| 1212 | emitter, |
| 1213 | event_type, |
| 1214 | event, |
| 1215 | } => self.apply_emit_effect(emitter, event_type, event), |
| 1216 | |
| 1217 | Effect::RefreshWindows => { |
| 1218 | self.apply_refresh_effect(); |
| 1219 | } |
| 1220 | |
| 1221 | Effect::NotifyGlobalObservers { global_type } => { |
| 1222 | self.apply_notify_global_observers_effect(global_type); |
| 1223 | } |
| 1224 | |
| 1225 | Effect::Defer { callback } => { |
| 1226 | self.apply_defer_effect(callback); |
| 1227 | } |
| 1228 | Effect::EntityCreated { |
| 1229 | entity, |
| 1230 | tid, |
| 1231 | window, |
| 1232 | } => { |
| 1233 | self.apply_entity_created_effect(entity, tid, window); |
| 1234 | } |
| 1235 | } |
| 1236 | } else { |
| 1237 | #[cfg(any(test, feature = "test-support"))] |
| 1238 | for window in self |
| 1239 | .windows |
| 1240 | .values() |
| 1241 | .filter_map(|window| { |
| 1242 | let window = window.as_deref()?; |
| 1243 | window.invalidator.is_dirty().then_some(window.handle) |
| 1244 | }) |
| 1245 | .collect::<Vec<_>>() |
| 1246 | { |
| 1247 | self.update_window(window, |_, window, cx| window.draw(cx).clear()) |
| 1248 | .unwrap(); |
| 1249 | } |
| 1250 | |
| 1251 | if self.pending_effects.is_empty() { |
| 1252 | break; |
| 1253 | } |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | /// Repeatedly called during `flush_effects` to release any entities whose |
| 1259 | /// reference count has become zero. We invoke any release observers before dropping |
| 1260 | /// each entity. |
| 1261 | fn release_dropped_entities(&mut self) { |
| 1262 | loop { |
| 1263 | let dropped = self.entities.take_dropped(); |
| 1264 | if dropped.is_empty() { |
| 1265 | break; |
| 1266 | } |
| 1267 | |
| 1268 | for (entity_id, mut entity) in dropped { |
| 1269 | self.observers.remove(&entity_id); |
| 1270 | self.event_listeners.remove(&entity_id); |
| 1271 | for release_callback in self.release_listeners.remove(&entity_id) { |
| 1272 | release_callback(entity.as_mut(), self); |
| 1273 | } |
| 1274 | } |
| 1275 | } |
| 1276 | } |
| 1277 | |
| 1278 | /// Repeatedly called during `flush_effects` to handle a focused handle being dropped. |
| 1279 | fn release_dropped_focus_handles(&mut self) { |
| 1280 | self.focus_handles |
| 1281 | .clone() |
| 1282 | .write() |
| 1283 | .retain(|handle_id, focus| { |
| 1284 | if focus.ref_count.load(SeqCst) == 0 { |
| 1285 | for window_handle in self.windows() { |
| 1286 | window_handle |
| 1287 | .update(self, |_, window, _| { |
| 1288 | if window.focus == Some(handle_id) { |
| 1289 | window.blur(); |
| 1290 | } |
| 1291 | }) |
| 1292 | .unwrap(); |
| 1293 | } |
| 1294 | false |
| 1295 | } else { |
| 1296 | true |
| 1297 | } |
| 1298 | }); |
| 1299 | } |
| 1300 | |
| 1301 | fn apply_notify_effect(&mut self, emitter: EntityId) { |
| 1302 | self.pending_notifications.remove(&emitter); |
| 1303 | |
| 1304 | self.observers |
| 1305 | .clone() |
| 1306 | .retain(&emitter, |handler| handler(self)); |
| 1307 | } |
| 1308 | |
| 1309 | fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) { |
| 1310 | self.event_listeners |
| 1311 | .clone() |
| 1312 | .retain(&emitter, |(stored_type, handler)| { |
| 1313 | if *stored_type == event_type { |
| 1314 | handler(event.as_ref(), self) |
| 1315 | } else { |
| 1316 | true |
| 1317 | } |
| 1318 | }); |
| 1319 | } |
| 1320 | |
| 1321 | fn apply_refresh_effect(&mut self) { |
| 1322 | for window in self.windows.values_mut() { |
| 1323 | if let Some(window) = window.as_deref_mut() { |
| 1324 | window.refreshing = true; |
| 1325 | window.invalidator.set_dirty(true); |
| 1326 | } |
| 1327 | } |
| 1328 | } |
| 1329 | |
| 1330 | fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) { |
| 1331 | self.pending_global_notifications.remove(&type_id); |
| 1332 | self.global_observers |
| 1333 | .clone() |
| 1334 | .retain(&type_id, |observer| observer(self)); |
| 1335 | } |
| 1336 | |
| 1337 | fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) { |
| 1338 | callback(self); |
| 1339 | } |
| 1340 | |
| 1341 | fn apply_entity_created_effect( |
| 1342 | &mut self, |
| 1343 | entity: AnyEntity, |
| 1344 | tid: TypeId, |
| 1345 | window: Option<WindowId>, |
| 1346 | ) { |
| 1347 | self.new_entity_observers.clone().retain(&tid, |observer| { |
| 1348 | if let Some(id) = window { |
| 1349 | self.update_window_id(id, { |
| 1350 | let entity = entity.clone(); |
| 1351 | |_, window, cx| (observer)(entity, &mut Some(window), cx) |
| 1352 | }) |
| 1353 | .expect("All windows should be off the stack when flushing effects"); |
| 1354 | } else { |
| 1355 | (observer)(entity.clone(), &mut None, self) |
| 1356 | } |
| 1357 | true |
| 1358 | }); |
| 1359 | } |
| 1360 | |
| 1361 | fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T> |
| 1362 | where |
| 1363 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 1364 | { |
| 1365 | self.update(|cx| { |
| 1366 | let mut window = cx.windows.get_mut(id)?.take()?; |
| 1367 | |
| 1368 | let root_view = window.root.clone().unwrap(); |
| 1369 | |
| 1370 | cx.window_update_stack.push(window.handle.id); |
| 1371 | let result = update(root_view, &mut window, cx); |
| 1372 | cx.window_update_stack.pop(); |
| 1373 | |
| 1374 | if window.removed { |
| 1375 | cx.window_handles.remove(&id); |
| 1376 | cx.windows.remove(id); |
| 1377 | |
| 1378 | cx.window_closed_observers.clone().retain(&(), |callback| { |
| 1379 | callback(cx); |
| 1380 | true |
| 1381 | }); |
| 1382 | } else { |
| 1383 | cx.windows.get_mut(id)?.replace(window); |
| 1384 | } |
| 1385 | |
| 1386 | Some(result) |
| 1387 | }) |
| 1388 | .context("window not found") |
| 1389 | } |
| 1390 | |
| 1391 | /// Creates an `AsyncApp`, which can be cloned and has a static lifetime |
| 1392 | /// so it can be held across `await` points. |
| 1393 | pub fn to_async(&self) -> AsyncApp { |
| 1394 | AsyncApp { |
| 1395 | app: self.this.clone(), |
| 1396 | background_executor: self.background_executor.clone(), |
| 1397 | foreground_executor: self.foreground_executor.clone(), |
| 1398 | } |
| 1399 | } |
| 1400 | |
| 1401 | /// Obtains a reference to the executor, which can be used to spawn futures. |
| 1402 | pub fn background_executor(&self) -> &BackgroundExecutor { |
| 1403 | &self.background_executor |
| 1404 | } |
| 1405 | |
| 1406 | /// Obtains a reference to the executor, which can be used to spawn futures. |
| 1407 | pub fn foreground_executor(&self) -> &ForegroundExecutor { |
| 1408 | if self.quitting { |
| 1409 | panic!("Can't spawn on main thread after on_app_quit") |
| 1410 | }; |
| 1411 | &self.foreground_executor |
| 1412 | } |
| 1413 | |
| 1414 | /// Spawns the future returned by the given function on the main thread. The closure will be invoked |
| 1415 | /// with [AsyncApp], which allows the application state to be accessed across await points. |
| 1416 | #[track_caller] |
| 1417 | pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R> |
| 1418 | where |
| 1419 | AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static, |
| 1420 | R: 'static, |
| 1421 | { |
| 1422 | if self.quitting { |
| 1423 | debug_panic!("Can't spawn on main thread after on_app_quit") |
| 1424 | }; |
| 1425 | |
| 1426 | let mut cx = self.to_async(); |
| 1427 | |
| 1428 | self.foreground_executor |
| 1429 | .spawn(async move { f(&mut cx).await }) |
| 1430 | } |
| 1431 | |
| 1432 | /// Schedules the given function to be run at the end of the current effect cycle, allowing entities |
| 1433 | /// that are currently on the stack to be returned to the app. |
| 1434 | pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) { |
| 1435 | self.push_effect(Effect::Defer { |
| 1436 | callback: Box::new(f), |
| 1437 | }); |
| 1438 | } |
| 1439 | |
| 1440 | /// Accessor for the application's asset source, which is provided when constructing the `App`. |
| 1441 | pub fn asset_source(&self) -> &Arc<dyn AssetSource> { |
| 1442 | &self.asset_source |
| 1443 | } |
| 1444 | |
| 1445 | /// Accessor for the text system. |
| 1446 | pub fn text_system(&self) -> &Arc<TextSystem> { |
| 1447 | &self.text_system |
| 1448 | } |
| 1449 | |
| 1450 | /// Check whether a global of the given type has been assigned. |
| 1451 | pub fn has_global<G: Global>(&self) -> bool { |
| 1452 | self.globals_by_type.contains_key(&TypeId::of::<G>()) |
| 1453 | } |
| 1454 | |
| 1455 | /// Access the global of the given type. Panics if a global for that type has not been assigned. |
| 1456 | #[track_caller] |
| 1457 | pub fn global<G: Global>(&self) -> &G { |
| 1458 | self.globals_by_type |
| 1459 | .get(&TypeId::of::<G>()) |
| 1460 | .map(|any_state| any_state.downcast_ref::<G>().unwrap()) |
| 1461 | .with_context(|| format!("no state of type {} exists", type_name::<G>())) |
| 1462 | .unwrap() |
| 1463 | } |
| 1464 | |
| 1465 | /// Access the global of the given type if a value has been assigned. |
| 1466 | pub fn try_global<G: Global>(&self) -> Option<&G> { |
| 1467 | self.globals_by_type |
| 1468 | .get(&TypeId::of::<G>()) |
| 1469 | .map(|any_state| any_state.downcast_ref::<G>().unwrap()) |
| 1470 | } |
| 1471 | |
| 1472 | /// Access the global of the given type mutably. Panics if a global for that type has not been assigned. |
| 1473 | #[track_caller] |
| 1474 | pub fn global_mut<G: Global>(&mut self) -> &mut G { |
| 1475 | let global_type = TypeId::of::<G>(); |
| 1476 | self.push_effect(Effect::NotifyGlobalObservers { global_type }); |
| 1477 | self.globals_by_type |
| 1478 | .get_mut(&global_type) |
| 1479 | .and_then(|any_state| any_state.downcast_mut::<G>()) |
| 1480 | .with_context(|| format!("no state of type {} exists", type_name::<G>())) |
| 1481 | .unwrap() |
| 1482 | } |
| 1483 | |
| 1484 | /// Access the global of the given type mutably. A default value is assigned if a global of this type has not |
| 1485 | /// yet been assigned. |
| 1486 | pub fn default_global<G: Global + Default>(&mut self) -> &mut G { |
| 1487 | let global_type = TypeId::of::<G>(); |
| 1488 | self.push_effect(Effect::NotifyGlobalObservers { global_type }); |
| 1489 | self.globals_by_type |
| 1490 | .entry(global_type) |
| 1491 | .or_insert_with(|| Box::<G>::default()) |
| 1492 | .downcast_mut::<G>() |
| 1493 | .unwrap() |
| 1494 | } |
| 1495 | |
| 1496 | /// Sets the value of the global of the given type. |
| 1497 | pub fn set_global<G: Global>(&mut self, global: G) { |
| 1498 | let global_type = TypeId::of::<G>(); |
| 1499 | self.push_effect(Effect::NotifyGlobalObservers { global_type }); |
| 1500 | self.globals_by_type.insert(global_type, Box::new(global)); |
| 1501 | } |
| 1502 | |
| 1503 | /// Clear all stored globals. Does not notify global observers. |
| 1504 | #[cfg(any(test, feature = "test-support"))] |
| 1505 | pub fn clear_globals(&mut self) { |
| 1506 | self.globals_by_type.drain(); |
| 1507 | } |
| 1508 | |
| 1509 | /// Remove the global of the given type from the app context. Does not notify global observers. |
| 1510 | pub fn remove_global<G: Global>(&mut self) -> G { |
| 1511 | let global_type = TypeId::of::<G>(); |
| 1512 | self.push_effect(Effect::NotifyGlobalObservers { global_type }); |
| 1513 | *self |
| 1514 | .globals_by_type |
| 1515 | .remove(&global_type) |
| 1516 | .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>())) |
| 1517 | .downcast() |
| 1518 | .unwrap() |
| 1519 | } |
| 1520 | |
| 1521 | /// Register a callback to be invoked when a global of the given type is updated. |
| 1522 | pub fn observe_global<G: Global>( |
| 1523 | &mut self, |
| 1524 | mut f: impl FnMut(&mut Self) + 'static, |
| 1525 | ) -> Subscription { |
| 1526 | let (subscription, activate) = self.global_observers.insert( |
| 1527 | TypeId::of::<G>(), |
| 1528 | Box::new(move |cx| { |
| 1529 | f(cx); |
| 1530 | true |
| 1531 | }), |
| 1532 | ); |
| 1533 | self.defer(move |_| activate()); |
| 1534 | subscription |
| 1535 | } |
| 1536 | |
| 1537 | /// Move the global of the given type to the stack. |
| 1538 | #[track_caller] |
| 1539 | pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> { |
| 1540 | GlobalLease::new( |
| 1541 | self.globals_by_type |
| 1542 | .remove(&TypeId::of::<G>()) |
| 1543 | .with_context(|| format!("no global registered of type {}", type_name::<G>())) |
| 1544 | .unwrap(), |
| 1545 | ) |
| 1546 | } |
| 1547 | |
| 1548 | /// Restore the global of the given type after it is moved to the stack. |
| 1549 | pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) { |
| 1550 | let global_type = TypeId::of::<G>(); |
| 1551 | |
| 1552 | self.push_effect(Effect::NotifyGlobalObservers { global_type }); |
| 1553 | self.globals_by_type.insert(global_type, lease.global); |
| 1554 | } |
| 1555 | |
| 1556 | pub(crate) fn new_entity_observer( |
| 1557 | &self, |
| 1558 | key: TypeId, |
| 1559 | value: NewEntityListener, |
| 1560 | ) -> Subscription { |
| 1561 | let (subscription, activate) = self.new_entity_observers.insert(key, value); |
| 1562 | activate(); |
| 1563 | subscription |
| 1564 | } |
| 1565 | |
| 1566 | /// Arrange for the given function to be invoked whenever a view of the specified type is created. |
| 1567 | /// The function will be passed a mutable reference to the view along with an appropriate context. |
| 1568 | pub fn observe_new<T: 'static>( |
| 1569 | &self, |
| 1570 | on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>), |
| 1571 | ) -> Subscription { |
| 1572 | self.new_entity_observer( |
| 1573 | TypeId::of::<T>(), |
| 1574 | Box::new( |
| 1575 | move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| { |
| 1576 | any_entity |
| 1577 | .downcast::<T>() |
| 1578 | .unwrap() |
| 1579 | .update(cx, |entity_state, cx| { |
| 1580 | on_new(entity_state, window.as_deref_mut(), cx) |
| 1581 | }) |
| 1582 | }, |
| 1583 | ), |
| 1584 | ) |
| 1585 | } |
| 1586 | |
| 1587 | /// Observe the release of a entity. The callback is invoked after the entity |
| 1588 | /// has no more strong references but before it has been dropped. |
| 1589 | pub fn observe_release<T>( |
| 1590 | &self, |
| 1591 | handle: &Entity<T>, |
| 1592 | on_release: impl FnOnce(&mut T, &mut App) + 'static, |
| 1593 | ) -> Subscription |
| 1594 | where |
| 1595 | T: 'static, |
| 1596 | { |
| 1597 | let (subscription, activate) = self.release_listeners.insert( |
| 1598 | handle.entity_id(), |
| 1599 | Box::new(move |entity, cx| { |
| 1600 | let entity = entity.downcast_mut().expect("invalid entity type"); |
| 1601 | on_release(entity, cx) |
| 1602 | }), |
| 1603 | ); |
| 1604 | activate(); |
| 1605 | subscription |
| 1606 | } |
| 1607 | |
| 1608 | /// Observe the release of a entity. The callback is invoked after the entity |
| 1609 | /// has no more strong references but before it has been dropped. |
| 1610 | pub fn observe_release_in<T>( |
| 1611 | &self, |
| 1612 | handle: &Entity<T>, |
| 1613 | window: &Window, |
| 1614 | on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static, |
| 1615 | ) -> Subscription |
| 1616 | where |
| 1617 | T: 'static, |
| 1618 | { |
| 1619 | let window_handle = window.handle; |
| 1620 | self.observe_release(handle, move |entity, cx| { |
| 1621 | let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx)); |
| 1622 | }) |
| 1623 | } |
| 1624 | |
| 1625 | /// Register a callback to be invoked when a keystroke is received by the application |
| 1626 | /// in any window. Note that this fires after all other action and event mechanisms have resolved |
| 1627 | /// and that this API will not be invoked if the event's propagation is stopped. |
| 1628 | pub fn observe_keystrokes( |
| 1629 | &mut self, |
| 1630 | mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static, |
| 1631 | ) -> Subscription { |
| 1632 | fn inner( |
| 1633 | keystroke_observers: &SubscriberSet<(), KeystrokeObserver>, |
| 1634 | handler: KeystrokeObserver, |
| 1635 | ) -> Subscription { |
| 1636 | let (subscription, activate) = keystroke_observers.insert((), handler); |
| 1637 | activate(); |
| 1638 | subscription |
| 1639 | } |
| 1640 | |
| 1641 | inner( |
| 1642 | &self.keystroke_observers, |
| 1643 | Box::new(move |event, window, cx| { |
| 1644 | f(event, window, cx); |
| 1645 | true |
| 1646 | }), |
| 1647 | ) |
| 1648 | } |
| 1649 | |
| 1650 | /// Register a callback to be invoked when a keystroke is received by the application |
| 1651 | /// in any window. Note that this fires _before_ all other action and event mechanisms have resolved |
| 1652 | /// unlike [`App::observe_keystrokes`] which fires after. This means that `cx.stop_propagation` calls |
| 1653 | /// within interceptors will prevent action dispatch |
| 1654 | pub fn intercept_keystrokes( |
| 1655 | &mut self, |
| 1656 | mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static, |
| 1657 | ) -> Subscription { |
| 1658 | fn inner( |
| 1659 | keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>, |
| 1660 | handler: KeystrokeObserver, |
| 1661 | ) -> Subscription { |
| 1662 | let (subscription, activate) = keystroke_interceptors.insert((), handler); |
| 1663 | activate(); |
| 1664 | subscription |
| 1665 | } |
| 1666 | |
| 1667 | inner( |
| 1668 | &self.keystroke_interceptors, |
| 1669 | Box::new(move |event, window, cx| { |
| 1670 | f(event, window, cx); |
| 1671 | true |
| 1672 | }), |
| 1673 | ) |
| 1674 | } |
| 1675 | |
| 1676 | /// Register key bindings. |
| 1677 | pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) { |
| 1678 | self.keymap.borrow_mut().add_bindings(bindings); |
| 1679 | self.pending_effects.push_back(Effect::RefreshWindows); |
| 1680 | } |
| 1681 | |
| 1682 | /// Clear all key bindings in the app. |
| 1683 | pub fn clear_key_bindings(&mut self) { |
| 1684 | self.keymap.borrow_mut().clear(); |
| 1685 | self.pending_effects.push_back(Effect::RefreshWindows); |
| 1686 | } |
| 1687 | |
| 1688 | /// Get all key bindings in the app. |
| 1689 | pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> { |
| 1690 | self.keymap.clone() |
| 1691 | } |
| 1692 | |
| 1693 | /// Register a global handler for actions invoked via the keyboard. These handlers are run at |
| 1694 | /// the end of the bubble phase for actions, and so will only be invoked if there are no other |
| 1695 | /// handlers or if they called `cx.propagate()`. |
| 1696 | pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) { |
| 1697 | self.global_action_listeners |
| 1698 | .entry(TypeId::of::<A>()) |
| 1699 | .or_default() |
| 1700 | .push(Rc::new(move |action, phase, cx| { |
| 1701 | if phase == DispatchPhase::Bubble { |
| 1702 | let action = action.downcast_ref().unwrap(); |
| 1703 | listener(action, cx) |
| 1704 | } |
| 1705 | })); |
| 1706 | } |
| 1707 | |
| 1708 | /// Event handlers propagate events by default. Call this method to stop dispatching to |
| 1709 | /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is |
| 1710 | /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by |
| 1711 | /// calling this method before effects are flushed. |
| 1712 | pub fn stop_propagation(&mut self) { |
| 1713 | self.propagate_event = false; |
| 1714 | } |
| 1715 | |
| 1716 | /// Action handlers stop propagation by default during the bubble phase of action dispatch |
| 1717 | /// dispatching to action handlers higher in the element tree. This is the opposite of |
| 1718 | /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling |
| 1719 | /// this method before effects are flushed. |
| 1720 | pub fn propagate(&mut self) { |
| 1721 | self.propagate_event = true; |
| 1722 | } |
| 1723 | |
| 1724 | /// Build an action from some arbitrary data, typically a keymap entry. |
| 1725 | pub fn build_action( |
| 1726 | &self, |
| 1727 | name: &str, |
| 1728 | data: Option<serde_json::Value>, |
| 1729 | ) -> std::result::Result<Box<dyn Action>, ActionBuildError> { |
| 1730 | self.actions.build_action(name, data) |
| 1731 | } |
| 1732 | |
| 1733 | /// Get all action names that have been registered. Note that registration only allows for |
| 1734 | /// actions to be built dynamically, and is unrelated to binding actions in the element tree. |
| 1735 | pub fn all_action_names(&self) -> &[&'static str] { |
| 1736 | self.actions.all_action_names() |
| 1737 | } |
| 1738 | |
| 1739 | /// Returns key bindings that invoke the given action on the currently focused element, without |
| 1740 | /// checking context. Bindings are returned in the order they were added. For display, the last |
| 1741 | /// binding should take precedence. |
| 1742 | pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> { |
| 1743 | RefCell::borrow(&self.keymap).all_bindings_for_input(input) |
| 1744 | } |
| 1745 | |
| 1746 | /// Get all non-internal actions that have been registered, along with their schemas. |
| 1747 | pub fn action_schemas( |
| 1748 | &self, |
| 1749 | generator: &mut schemars::SchemaGenerator, |
| 1750 | ) -> Vec<(&'static str, Option<schemars::Schema>)> { |
| 1751 | self.actions.action_schemas(generator) |
| 1752 | } |
| 1753 | |
| 1754 | /// Get a map from a deprecated action name to the canonical name. |
| 1755 | pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> { |
| 1756 | self.actions.deprecated_aliases() |
| 1757 | } |
| 1758 | |
| 1759 | /// Get a map from an action name to the deprecation messages. |
| 1760 | pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> { |
| 1761 | self.actions.deprecation_messages() |
| 1762 | } |
| 1763 | |
| 1764 | /// Get a map from an action name to the documentation. |
| 1765 | pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> { |
| 1766 | self.actions.documentation() |
| 1767 | } |
| 1768 | |
| 1769 | /// Register a callback to be invoked when the application is about to quit. |
| 1770 | /// It is not possible to cancel the quit event at this point. |
| 1771 | pub fn on_app_quit<Fut>( |
| 1772 | &self, |
| 1773 | mut on_quit: impl FnMut(&mut App) -> Fut + 'static, |
| 1774 | ) -> Subscription |
| 1775 | where |
| 1776 | Fut: 'static + Future<Output = ()>, |
| 1777 | { |
| 1778 | let (subscription, activate) = self.quit_observers.insert( |
| 1779 | (), |
| 1780 | Box::new(move |cx| { |
| 1781 | let future = on_quit(cx); |
| 1782 | future.boxed_local() |
| 1783 | }), |
| 1784 | ); |
| 1785 | activate(); |
| 1786 | subscription |
| 1787 | } |
| 1788 | |
| 1789 | /// Register a callback to be invoked when the application is about to restart. |
| 1790 | /// |
| 1791 | /// These callbacks are called before any `on_app_quit` callbacks. |
| 1792 | pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription { |
| 1793 | let (subscription, activate) = self.restart_observers.insert( |
| 1794 | (), |
| 1795 | Box::new(move |cx| { |
| 1796 | on_restart(cx); |
| 1797 | true |
| 1798 | }), |
| 1799 | ); |
| 1800 | activate(); |
| 1801 | subscription |
| 1802 | } |
| 1803 | |
| 1804 | /// Register a callback to be invoked when a window is closed |
| 1805 | /// The window is no longer accessible at the point this callback is invoked. |
| 1806 | pub fn on_window_closed(&self, mut on_closed: impl FnMut(&mut App) + 'static) -> Subscription { |
| 1807 | let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed)); |
| 1808 | activate(); |
| 1809 | subscription |
| 1810 | } |
| 1811 | |
| 1812 | pub(crate) fn clear_pending_keystrokes(&mut self) { |
| 1813 | for window in self.windows() { |
| 1814 | window |
| 1815 | .update(self, |_, window, _| { |
| 1816 | window.clear_pending_keystrokes(); |
| 1817 | }) |
| 1818 | .ok(); |
| 1819 | } |
| 1820 | } |
| 1821 | |
| 1822 | /// Checks if the given action is bound in the current context, as defined by the app's current focus, |
| 1823 | /// the bindings in the element tree, and any global action listeners. |
| 1824 | pub fn is_action_available(&mut self, action: &dyn Action) -> bool { |
| 1825 | let mut action_available = false; |
| 1826 | if let Some(window) = self.active_window() |
| 1827 | && let Ok(window_action_available) = |
| 1828 | window.update(self, |_, window, cx| window.is_action_available(action, cx)) |
| 1829 | { |
| 1830 | action_available = window_action_available; |
| 1831 | } |
| 1832 | |
| 1833 | action_available |
| 1834 | || self |
| 1835 | .global_action_listeners |
| 1836 | .contains_key(&action.as_any().type_id()) |
| 1837 | } |
| 1838 | |
| 1839 | /// Sets the menu bar for this application. This will replace any existing menu bar. |
| 1840 | pub fn set_menus(&self, menus: Vec<Menu>) { |
| 1841 | self.platform.set_menus(menus, &self.keymap.borrow()); |
| 1842 | } |
| 1843 | |
| 1844 | /// Gets the menu bar for this application. |
| 1845 | pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> { |
| 1846 | self.platform.get_menus() |
| 1847 | } |
| 1848 | |
| 1849 | /// Sets the right click menu for the app icon in the dock |
| 1850 | pub fn set_dock_menu(&self, menus: Vec<MenuItem>) { |
| 1851 | self.platform.set_dock_menu(menus, &self.keymap.borrow()) |
| 1852 | } |
| 1853 | |
| 1854 | /// Performs the action associated with the given dock menu item, only used on Windows for now. |
| 1855 | pub fn perform_dock_menu_action(&self, action: usize) { |
| 1856 | self.platform.perform_dock_menu_action(action); |
| 1857 | } |
| 1858 | |
| 1859 | /// Adds given path to the bottom of the list of recent paths for the application. |
| 1860 | /// The list is usually shown on the application icon's context menu in the dock, |
| 1861 | /// and allows to open the recent files via that context menu. |
| 1862 | /// If the path is already in the list, it will be moved to the bottom of the list. |
| 1863 | pub fn add_recent_document(&self, path: &Path) { |
| 1864 | self.platform.add_recent_document(path); |
| 1865 | } |
| 1866 | |
| 1867 | /// Updates the jump list with the updated list of recent paths for the application, only used on Windows for now. |
| 1868 | /// Note that this also sets the dock menu on Windows. |
| 1869 | pub fn update_jump_list( |
| 1870 | &self, |
| 1871 | menus: Vec<MenuItem>, |
| 1872 | entries: Vec<SmallVec<[PathBuf; 2]>>, |
| 1873 | ) -> Vec<SmallVec<[PathBuf; 2]>> { |
| 1874 | self.platform.update_jump_list(menus, entries) |
| 1875 | } |
| 1876 | |
| 1877 | /// Dispatch an action to the currently active window or global action handler |
| 1878 | /// See [`crate::Action`] for more information on how actions work |
| 1879 | pub fn dispatch_action(&mut self, action: &dyn Action) { |
| 1880 | if let Some(active_window) = self.active_window() { |
| 1881 | active_window |
| 1882 | .update(self, |_, window, cx| { |
| 1883 | window.dispatch_action(action.boxed_clone(), cx) |
| 1884 | }) |
| 1885 | .log_err(); |
| 1886 | } else { |
| 1887 | self.dispatch_global_action(action); |
| 1888 | } |
| 1889 | } |
| 1890 | |
| 1891 | fn dispatch_global_action(&mut self, action: &dyn Action) { |
| 1892 | self.propagate_event = true; |
| 1893 | |
| 1894 | if let Some(mut global_listeners) = self |
| 1895 | .global_action_listeners |
| 1896 | .remove(&action.as_any().type_id()) |
| 1897 | { |
| 1898 | for listener in &global_listeners { |
| 1899 | listener(action.as_any(), DispatchPhase::Capture, self); |
| 1900 | if !self.propagate_event { |
| 1901 | break; |
| 1902 | } |
| 1903 | } |
| 1904 | |
| 1905 | global_listeners.extend( |
| 1906 | self.global_action_listeners |
| 1907 | .remove(&action.as_any().type_id()) |
| 1908 | .unwrap_or_default(), |
| 1909 | ); |
| 1910 | |
| 1911 | self.global_action_listeners |
| 1912 | .insert(action.as_any().type_id(), global_listeners); |
| 1913 | } |
| 1914 | |
| 1915 | if self.propagate_event |
| 1916 | && let Some(mut global_listeners) = self |
| 1917 | .global_action_listeners |
| 1918 | .remove(&action.as_any().type_id()) |
| 1919 | { |
| 1920 | for listener in global_listeners.iter().rev() { |
| 1921 | listener(action.as_any(), DispatchPhase::Bubble, self); |
| 1922 | if !self.propagate_event { |
| 1923 | break; |
| 1924 | } |
| 1925 | } |
| 1926 | |
| 1927 | global_listeners.extend( |
| 1928 | self.global_action_listeners |
| 1929 | .remove(&action.as_any().type_id()) |
| 1930 | .unwrap_or_default(), |
| 1931 | ); |
| 1932 | |
| 1933 | self.global_action_listeners |
| 1934 | .insert(action.as_any().type_id(), global_listeners); |
| 1935 | } |
| 1936 | } |
| 1937 | |
| 1938 | /// Is there currently something being dragged? |
| 1939 | pub fn has_active_drag(&self) -> bool { |
| 1940 | self.active_drag.is_some() |
| 1941 | } |
| 1942 | |
| 1943 | /// Gets the cursor style of the currently active drag operation. |
| 1944 | pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> { |
| 1945 | self.active_drag.as_ref().and_then(|drag| drag.cursor_style) |
| 1946 | } |
| 1947 | |
| 1948 | /// Stops active drag and clears any related effects. |
| 1949 | pub fn stop_active_drag(&mut self, window: &mut Window) -> bool { |
| 1950 | if self.active_drag.is_some() { |
| 1951 | self.active_drag = None; |
| 1952 | window.refresh(); |
| 1953 | true |
| 1954 | } else { |
| 1955 | false |
| 1956 | } |
| 1957 | } |
| 1958 | |
| 1959 | /// Sets the cursor style for the currently active drag operation. |
| 1960 | pub fn set_active_drag_cursor_style( |
| 1961 | &mut self, |
| 1962 | cursor_style: CursorStyle, |
| 1963 | window: &mut Window, |
| 1964 | ) -> bool { |
| 1965 | if let Some(ref mut drag) = self.active_drag { |
| 1966 | drag.cursor_style = Some(cursor_style); |
| 1967 | window.refresh(); |
| 1968 | true |
| 1969 | } else { |
| 1970 | false |
| 1971 | } |
| 1972 | } |
| 1973 | |
| 1974 | /// Set the prompt renderer for GPUI. This will replace the default or platform specific |
| 1975 | /// prompts with this custom implementation. |
| 1976 | pub fn set_prompt_builder( |
| 1977 | &mut self, |
| 1978 | renderer: impl Fn( |
| 1979 | PromptLevel, |
| 1980 | &str, |
| 1981 | Option<&str>, |
| 1982 | &[PromptButton], |
| 1983 | PromptHandle, |
| 1984 | &mut Window, |
| 1985 | &mut App, |
| 1986 | ) -> RenderablePromptHandle |
| 1987 | + 'static, |
| 1988 | ) { |
| 1989 | self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer))); |
| 1990 | } |
| 1991 | |
| 1992 | /// Reset the prompt builder to the default implementation. |
| 1993 | pub fn reset_prompt_builder(&mut self) { |
| 1994 | self.prompt_builder = Some(PromptBuilder::Default); |
| 1995 | } |
| 1996 | |
| 1997 | /// Remove an asset from GPUI's cache |
| 1998 | pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) { |
| 1999 | let asset_id = (TypeId::of::<A>(), hash(source)); |
| 2000 | self.loading_assets.remove(&asset_id); |
| 2001 | } |
| 2002 | |
| 2003 | /// Asynchronously load an asset, if the asset hasn't finished loading this will return None. |
| 2004 | /// |
| 2005 | /// Note that the multiple calls to this method will only result in one `Asset::load` call at a |
| 2006 | /// time, and the results of this call will be cached |
| 2007 | pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> (Shared<Task<A::Output>>, bool) { |
| 2008 | let asset_id = (TypeId::of::<A>(), hash(source)); |
| 2009 | let mut is_first = false; |
| 2010 | let task = self |
| 2011 | .loading_assets |
| 2012 | .remove(&asset_id) |
| 2013 | .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap()) |
| 2014 | .unwrap_or_else(|| { |
| 2015 | is_first = true; |
| 2016 | let future = A::load(source.clone(), self); |
| 2017 | |
| 2018 | self.background_executor().spawn(future).shared() |
| 2019 | }); |
| 2020 | |
| 2021 | self.loading_assets.insert(asset_id, Box::new(task.clone())); |
| 2022 | |
| 2023 | (task, is_first) |
| 2024 | } |
| 2025 | |
| 2026 | /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus |
| 2027 | /// for elements rendered within this window. |
| 2028 | #[track_caller] |
| 2029 | pub fn focus_handle(&self) -> FocusHandle { |
| 2030 | FocusHandle::new(&self.focus_handles) |
| 2031 | } |
| 2032 | |
| 2033 | /// Tell GPUI that an entity has changed and observers of it should be notified. |
| 2034 | pub fn notify(&mut self, entity_id: EntityId) { |
| 2035 | let window_invalidators = mem::take( |
| 2036 | self.window_invalidators_by_entity |
| 2037 | .entry(entity_id) |
| 2038 | .or_default(), |
| 2039 | ); |
| 2040 | |
| 2041 | if window_invalidators.is_empty() { |
| 2042 | if self.pending_notifications.insert(entity_id) { |
| 2043 | self.pending_effects |
| 2044 | .push_back(Effect::Notify { emitter: entity_id }); |
| 2045 | } |
| 2046 | } else { |
| 2047 | for invalidator in window_invalidators.values() { |
| 2048 | invalidator.invalidate_view(entity_id, self); |
| 2049 | } |
| 2050 | } |
| 2051 | |
| 2052 | self.window_invalidators_by_entity |
| 2053 | .insert(entity_id, window_invalidators); |
| 2054 | } |
| 2055 | |
| 2056 | /// Returns the name for this [`App`]. |
| 2057 | #[cfg(any(test, feature = "test-support", debug_assertions))] |
| 2058 | pub fn get_name(&self) -> Option<&'static str> { |
| 2059 | self.name |
| 2060 | } |
| 2061 | |
| 2062 | /// Returns `true` if the platform file picker supports selecting a mix of files and directories. |
| 2063 | pub fn can_select_mixed_files_and_dirs(&self) -> bool { |
| 2064 | self.platform.can_select_mixed_files_and_dirs() |
| 2065 | } |
| 2066 | |
| 2067 | /// Removes an image from the sprite atlas on all windows. |
| 2068 | /// |
| 2069 | /// If the current window is being updated, it will be removed from `App.windows`, you can use `current_window` to specify the current window. |
| 2070 | /// This is a no-op if the image is not in the sprite atlas. |
| 2071 | pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) { |
| 2072 | // remove the texture from all other windows |
| 2073 | for window in self.windows.values_mut().flatten() { |
| 2074 | _ = window.drop_image(image.clone()); |
| 2075 | } |
| 2076 | |
| 2077 | // remove the texture from the current window |
| 2078 | if let Some(window) = current_window { |
| 2079 | _ = window.drop_image(image); |
| 2080 | } |
| 2081 | } |
| 2082 | |
| 2083 | /// Sets the renderer for the inspector. |
| 2084 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 2085 | pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) { |
| 2086 | self.inspector_renderer = Some(f); |
| 2087 | } |
| 2088 | |
| 2089 | /// Registers a renderer specific to an inspector state. |
| 2090 | #[cfg(any(feature = "inspector", debug_assertions))] |
| 2091 | pub fn register_inspector_element<T: 'static, R: crate::IntoElement>( |
| 2092 | &mut self, |
| 2093 | f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R, |
| 2094 | ) { |
| 2095 | self.inspector_element_registry.register(f); |
| 2096 | } |
| 2097 | |
| 2098 | /// Initializes gpui's default colors for the application. |
| 2099 | /// |
| 2100 | /// These colors can be accessed through `cx.default_colors()`. |
| 2101 | pub fn init_colors(&mut self) { |
| 2102 | self.set_global(GlobalColors(Arc::new(Colors::default()))); |
| 2103 | } |
| 2104 | } |
| 2105 | |
| 2106 | impl AppContext for App { |
| 2107 | type Result<T> = T; |
| 2108 | |
| 2109 | /// Builds an entity that is owned by the application. |
| 2110 | /// |
| 2111 | /// The given function will be invoked with a [`Context`] and must return an object representing the entity. An |
| 2112 | /// [`Entity`] handle will be returned, which can be used to access the entity in a context. |
| 2113 | fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> { |
| 2114 | self.update(|cx| { |
| 2115 | let slot = cx.entities.reserve(); |
| 2116 | let handle = slot.clone(); |
| 2117 | let entity = build_entity(&mut Context::new_context(cx, slot.downgrade())); |
| 2118 | |
| 2119 | cx.push_effect(Effect::EntityCreated { |
| 2120 | entity: handle.clone().into_any(), |
| 2121 | tid: TypeId::of::<T>(), |
| 2122 | window: cx.window_update_stack.last().cloned(), |
| 2123 | }); |
| 2124 | |
| 2125 | cx.entities.insert(slot, entity); |
| 2126 | handle |
| 2127 | }) |
| 2128 | } |
| 2129 | |
| 2130 | fn reserve_entity<T: 'static>(&mut self) -> Self::Result<Reservation<T>> { |
| 2131 | Reservation(self.entities.reserve()) |
| 2132 | } |
| 2133 | |
| 2134 | fn insert_entity<T: 'static>( |
| 2135 | &mut self, |
| 2136 | reservation: Reservation<T>, |
| 2137 | build_entity: impl FnOnce(&mut Context<T>) -> T, |
| 2138 | ) -> Self::Result<Entity<T>> { |
| 2139 | self.update(|cx| { |
| 2140 | let slot = reservation.0; |
| 2141 | let entity = build_entity(&mut Context::new_context(cx, slot.downgrade())); |
| 2142 | cx.entities.insert(slot, entity) |
| 2143 | }) |
| 2144 | } |
| 2145 | |
| 2146 | /// Updates the entity referenced by the given handle. The function is passed a mutable reference to the |
| 2147 | /// entity along with a `Context` for the entity. |
| 2148 | fn update_entity<T: 'static, R>( |
| 2149 | &mut self, |
| 2150 | handle: &Entity<T>, |
| 2151 | update: impl FnOnce(&mut T, &mut Context<T>) -> R, |
| 2152 | ) -> R { |
| 2153 | self.update(|cx| { |
| 2154 | let mut entity = cx.entities.lease(handle); |
| 2155 | let result = update( |
| 2156 | &mut entity, |
| 2157 | &mut Context::new_context(cx, handle.downgrade()), |
| 2158 | ); |
| 2159 | cx.entities.end_lease(entity); |
| 2160 | result |
| 2161 | }) |
| 2162 | } |
| 2163 | |
| 2164 | fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T> |
| 2165 | where |
| 2166 | T: 'static, |
| 2167 | { |
| 2168 | GpuiBorrow::new(handle.clone(), self) |
| 2169 | } |
| 2170 | |
| 2171 | fn read_entity<T, R>( |
| 2172 | &self, |
| 2173 | handle: &Entity<T>, |
| 2174 | read: impl FnOnce(&T, &App) -> R, |
| 2175 | ) -> Self::Result<R> |
| 2176 | where |
| 2177 | T: 'static, |
| 2178 | { |
| 2179 | let entity = self.entities.read(handle); |
| 2180 | read(entity, self) |
| 2181 | } |
| 2182 | |
| 2183 | fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T> |
| 2184 | where |
| 2185 | F: FnOnce(AnyView, &mut Window, &mut App) -> T, |
| 2186 | { |
| 2187 | self.update_window_id(handle.id, update) |
| 2188 | } |
| 2189 | |
| 2190 | fn read_window<T, R>( |
| 2191 | &self, |
| 2192 | window: &WindowHandle<T>, |
| 2193 | read: impl FnOnce(Entity<T>, &App) -> R, |
| 2194 | ) -> Result<R> |
| 2195 | where |
| 2196 | T: 'static, |
| 2197 | { |
| 2198 | let window = self |
| 2199 | .windows |
| 2200 | .get(window.id) |
| 2201 | .context("window not found")? |
| 2202 | .as_deref() |
| 2203 | .expect("attempted to read a window that is already on the stack"); |
| 2204 | |
| 2205 | let root_view = window.root.clone().unwrap(); |
| 2206 | let view = root_view |
| 2207 | .downcast::<T>() |
| 2208 | .map_err(|_| anyhow!("root view's type has changed"))?; |
| 2209 | |
| 2210 | Ok(read(view, self)) |
| 2211 | } |
| 2212 | |
| 2213 | fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> |
| 2214 | where |
| 2215 | R: Send + 'static, |
| 2216 | { |
| 2217 | self.background_executor.spawn(future) |
| 2218 | } |
| 2219 | |
| 2220 | fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R> |
| 2221 | where |
| 2222 | G: Global, |
| 2223 | { |
| 2224 | let mut g = self.global::<G>(); |
| 2225 | callback(g, self) |
| 2226 | } |
| 2227 | } |
| 2228 | |
| 2229 | /// These effects are processed at the end of each application update cycle. |
| 2230 | pub(crate) enum Effect { |
| 2231 | Notify { |
| 2232 | emitter: EntityId, |
| 2233 | }, |
| 2234 | Emit { |
| 2235 | emitter: EntityId, |
| 2236 | event_type: TypeId, |
| 2237 | event: Box<dyn Any>, |
| 2238 | }, |
| 2239 | RefreshWindows, |
| 2240 | NotifyGlobalObservers { |
| 2241 | global_type: TypeId, |
| 2242 | }, |
| 2243 | Defer { |
| 2244 | callback: Box<dyn FnOnce(&mut App) + 'static>, |
| 2245 | }, |
| 2246 | EntityCreated { |
| 2247 | entity: AnyEntity, |
| 2248 | tid: TypeId, |
| 2249 | window: Option<WindowId>, |
| 2250 | }, |
| 2251 | } |
| 2252 | |
| 2253 | impl std::fmt::Debug for Effect { |
| 2254 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 2255 | match self { |
| 2256 | Effect::Notify { emitter } => write!(f, "Notify({})", emitter), |
| 2257 | Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter), |
| 2258 | Effect::RefreshWindows => write!(f, "RefreshWindows"), |
| 2259 | Effect::NotifyGlobalObservers { global_type } => { |
| 2260 | write!(f, "NotifyGlobalObservers({:?})", global_type) |
| 2261 | } |
| 2262 | Effect::Defer { .. } => write!(f, "Defer(..)"), |
| 2263 | Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity), |
| 2264 | } |
| 2265 | } |
| 2266 | } |
| 2267 | |
| 2268 | /// Wraps a global variable value during `update_global` while the value has been moved to the stack. |
| 2269 | pub(crate) struct GlobalLease<G: Global> { |
| 2270 | global: Box<dyn Any>, |
| 2271 | global_type: PhantomData<G>, |
| 2272 | } |
| 2273 | |
| 2274 | impl<G: Global> GlobalLease<G> { |
| 2275 | fn new(global: Box<dyn Any>) -> Self { |
| 2276 | GlobalLease { |
| 2277 | global, |
| 2278 | global_type: PhantomData, |
| 2279 | } |
| 2280 | } |
| 2281 | } |
| 2282 | |
| 2283 | impl<G: Global> Deref for GlobalLease<G> { |
| 2284 | type Target = G; |
| 2285 | |
| 2286 | fn deref(&self) -> &Self::Target { |
| 2287 | self.global.downcast_ref().unwrap() |
| 2288 | } |
| 2289 | } |
| 2290 | |
| 2291 | impl<G: Global> DerefMut for GlobalLease<G> { |
| 2292 | fn deref_mut(&mut self) -> &mut Self::Target { |
| 2293 | self.global.downcast_mut().unwrap() |
| 2294 | } |
| 2295 | } |
| 2296 | |
| 2297 | /// Contains state associated with an active drag operation, started by dragging an element |
| 2298 | /// within the window or by dragging into the app from the underlying platform. |
| 2299 | pub struct AnyDrag { |
| 2300 | /// The view used to render this drag |
| 2301 | pub view: AnyView, |
| 2302 | |
| 2303 | /// The value of the dragged item, to be dropped |
| 2304 | pub value: Arc<dyn Any>, |
| 2305 | |
| 2306 | /// This is used to render the dragged item in the same place |
| 2307 | /// on the original element that the drag was initiated |
| 2308 | pub cursor_offset: Point<Pixels>, |
| 2309 | |
| 2310 | /// The cursor style to use while dragging |
| 2311 | pub cursor_style: Option<CursorStyle>, |
| 2312 | } |
| 2313 | |
| 2314 | /// Contains state associated with a tooltip. You'll only need this struct if you're implementing |
| 2315 | /// tooltip behavior on a custom element. Otherwise, use [Div::tooltip](crate::Interactivity::tooltip). |
| 2316 | #[derive(Clone)] |
| 2317 | pub struct AnyTooltip { |
| 2318 | /// The view used to display the tooltip |
| 2319 | pub view: AnyView, |
| 2320 | |
| 2321 | /// The absolute position of the mouse when the tooltip was deployed. |
| 2322 | pub mouse_position: Point<Pixels>, |
| 2323 | |
| 2324 | /// Given the bounds of the tooltip, checks whether the tooltip should still be visible and |
| 2325 | /// updates its state accordingly. This is needed atop the hovered element's mouse move handler |
| 2326 | /// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`). |
| 2327 | pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>, |
| 2328 | } |
| 2329 | |
| 2330 | /// A keystroke event, and potentially the associated action |
| 2331 | #[derive(Debug)] |
| 2332 | pub struct KeystrokeEvent { |
| 2333 | /// The keystroke that occurred |
| 2334 | pub keystroke: Keystroke, |
| 2335 | |
| 2336 | /// The action that was resolved for the keystroke, if any |
| 2337 | pub action: Option<Box<dyn Action>>, |
| 2338 | |
| 2339 | /// The context stack at the time |
| 2340 | pub context_stack: Vec<KeyContext>, |
| 2341 | } |
| 2342 | |
| 2343 | struct NullHttpClient; |
| 2344 | |
| 2345 | impl HttpClient for NullHttpClient { |
| 2346 | fn send( |
| 2347 | &self, |
| 2348 | _req: http_client::Request<http_client::AsyncBody>, |
| 2349 | ) -> futures::future::BoxFuture< |
| 2350 | 'static, |
| 2351 | anyhow::Result<http_client::Response<http_client::AsyncBody>>, |
| 2352 | > { |
| 2353 | async move { |
| 2354 | anyhow::bail!("No HttpClient available"); |
| 2355 | } |
| 2356 | .boxed() |
| 2357 | } |
| 2358 | |
| 2359 | fn user_agent(&self) -> Option<&http_client::http::HeaderValue> { |
| 2360 | None |
| 2361 | } |
| 2362 | |
| 2363 | fn proxy(&self) -> Option<&Url> { |
| 2364 | None |
| 2365 | } |
| 2366 | |
| 2367 | fn type_name(&self) -> &'static str { |
| 2368 | type_name::<Self>() |
| 2369 | } |
| 2370 | } |
| 2371 | |
| 2372 | /// A mutable reference to an entity owned by GPUI |
| 2373 | pub struct GpuiBorrow<'a, T> { |
| 2374 | inner: Option<Lease<T>>, |
| 2375 | app: &'a mut App, |
| 2376 | } |
| 2377 | |
| 2378 | impl<'a, T: 'static> GpuiBorrow<'a, T> { |
| 2379 | fn new(inner: Entity<T>, app: &'a mut App) -> Self { |
| 2380 | app.start_update(); |
| 2381 | let lease = app.entities.lease(&inner); |
| 2382 | Self { |
| 2383 | inner: Some(lease), |
| 2384 | app, |
| 2385 | } |
| 2386 | } |
| 2387 | } |
| 2388 | |
| 2389 | impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> { |
| 2390 | fn borrow(&self) -> &T { |
| 2391 | self.inner.as_ref().unwrap().borrow() |
| 2392 | } |
| 2393 | } |
| 2394 | |
| 2395 | impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> { |
| 2396 | fn borrow_mut(&mut self) -> &mut T { |
| 2397 | self.inner.as_mut().unwrap().borrow_mut() |
| 2398 | } |
| 2399 | } |
| 2400 | |
| 2401 | impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> { |
| 2402 | type Target = T; |
| 2403 | |
| 2404 | fn deref(&self) -> &Self::Target { |
| 2405 | self.inner.as_ref().unwrap() |
| 2406 | } |
| 2407 | } |
| 2408 | |
| 2409 | impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> { |
| 2410 | fn deref_mut(&mut self) -> &mut T { |
| 2411 | self.inner.as_mut().unwrap() |
| 2412 | } |
| 2413 | } |
| 2414 | |
| 2415 | impl<'a, T> Drop for GpuiBorrow<'a, T> { |
| 2416 | fn drop(&mut self) { |
| 2417 | let lease = self.inner.take().unwrap(); |
| 2418 | self.app.notify(lease.id); |
| 2419 | self.app.entities.end_lease(lease); |
| 2420 | self.app.finish_update(); |
| 2421 | } |
| 2422 | } |
| 2423 | |
| 2424 | #[cfg(test)] |
| 2425 | mod test { |
| 2426 | use std::{cell::RefCell, rc::Rc}; |
| 2427 | |
| 2428 | use crate::{AppContext, TestAppContext}; |
| 2429 | |
| 2430 | #[test] |
| 2431 | fn test_gpui_borrow() { |
| 2432 | let cx = TestAppContext::single(); |
| 2433 | let observation_count = Rc::new(RefCell::new(0)); |
| 2434 | |
| 2435 | let state = cx.update(|cx| { |
| 2436 | let state = cx.new(|_| false); |
| 2437 | cx.observe(&state, { |
| 2438 | let observation_count = observation_count.clone(); |
| 2439 | move |_, _| { |
| 2440 | let mut count = observation_count.borrow_mut(); |
| 2441 | *count += 1; |
| 2442 | } |
| 2443 | }) |
| 2444 | .detach(); |
| 2445 | |
| 2446 | state |
| 2447 | }); |
| 2448 | |
| 2449 | cx.update(|cx| { |
| 2450 | // Calling this like this so that we don't clobber the borrow_mut above |
| 2451 | *std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true; |
| 2452 | }); |
| 2453 | |
| 2454 | cx.update(|cx| { |
| 2455 | state.write(cx, false); |
| 2456 | }); |
| 2457 | |
| 2458 | assert_eq!(*observation_count.borrow(), 2); |
| 2459 | } |
| 2460 | } |