1use std::cell::RefCell;
11
12use gpui::{
13 div, prelude::*, px, rgba, size, App, Context, TitlebarOptions, WeakEntity, Window,
14 WindowBounds, WindowControlArea, WindowOptions,
15};
16use gpui_platform::application;
17use sk_runtime::runtime::{PUMP_MICROTASKS, PUMP_RAF, PUMP_TIMERS};
18use sk_runtime::{host_fn, with_published, with_published_app, JsRuntime, Phase};
19
20mod background;
21#[cfg(feature = "prod")]
22mod bytecode;
23#[cfg(not(feature = "prod"))]
24mod dev;
25mod idle;
26#[cfg(sk_devtools)]
28mod devtools;
29#[cfg(sk_devtools)]
31pub mod heapcount;
32#[cfg(sk_devtools)]
34pub use heapcount::Counting as HostAllocator;
35#[cfg(not(sk_devtools))]
36pub use std::alloc::System as HostAllocator;
37mod http_client;
38#[cfg(all(sk_devtools, test))]
40#[global_allocator]
41static GLOBAL: heapcount::Counting = heapcount::Counting;
42#[cfg(not(target_os = "windows"))]
43mod chrome_posix;
44#[cfg(target_os = "windows")]
45#[doc(hidden)]
46pub mod consent_window;
47#[cfg(target_os = "windows")]
48mod content_dialog;
49#[doc(hidden)]
50pub mod crash_window;
51mod dialogs;
52pub mod embed;
53#[cfg(feature = "hotkeys")]
54pub mod hotkeys;
55#[cfg(sk_devtools)]
56mod inspector;
57pub mod js;
58mod json;
59mod mapped_file;
60#[cfg(feature = "audio")]
61mod microphone;
62#[cfg(feature = "native-aot")]
63mod native_aot;
64mod occlusion;
65mod owner;
66mod payload;
67mod perf;
68mod placement;
69mod popout;
70mod popout_win;
71#[cfg(feature = "prod")]
72mod prod;
73mod quiet;
74mod reclaim;
75mod reload;
76#[cfg(all(feature = "webgpu", target_os = "windows"))]
77mod shared_gpu;
78mod shutdown;
79mod slot;
80#[cfg(feature = "spatial-audio")]
81mod spatial_audio;
82mod transparency;
83pub mod tray;
84mod window;
85
86#[cfg(not(feature = "prod"))]
87use dev as boot_mode;
88#[cfg(feature = "prod")]
89use prod as boot_mode;
90
91const PRELUDE_JS: &str = include_str!("prelude.js");
95
96const WINDOW_PRELUDE_JS: &str = include_str!("window.prelude.js");
98
99thread_local! {
100 static FRAME_NO: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
101 static FIRST_WAVE_RELEASED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
102}
103
104fn first_wave_waits(window: &mut Window) -> bool {
107 if FIRST_WAVE_RELEASED.with(|c| c.get()) {
108 return false;
109 }
110 FIRST_WAVE_RELEASED.with(|c| c.set(true));
111 window.refresh();
112 true
113}
114
115struct StderrLogger {
119 directives: Vec<(String, log::LevelFilter)>,
121 default: log::LevelFilter,
122}
123
124fn target_matches(target: &str, prefix: &str) -> bool {
126 target.len() >= prefix.len()
127 && target.starts_with(prefix)
128 && (target.len() == prefix.len() || target[prefix.len()..].starts_with("::"))
129}
130
131impl StderrLogger {
132 fn level_for(&self, target: &str) -> log::LevelFilter {
133 for (prefix, l) in &self.directives {
134 if target_matches(target, prefix) {
135 return *l;
136 }
137 }
138 self.default
139 }
140}
141
142impl log::Log for StderrLogger {
143 fn enabled(&self, metadata: &log::Metadata) -> bool {
144 metadata.level() <= self.level_for(metadata.target())
145 }
146 fn log(&self, record: &log::Record) {
147 if !self.enabled(record.metadata()) {
148 return;
149 }
150 let line = format!("[{} {}] {}", record.level(), record.target(), record.args());
151 eprintln!("{line}");
153 tee(record.level(), line);
154 }
155 fn flush(&self) {}
156}
157
158static MAIN_THREAD: std::sync::OnceLock<std::thread::ThreadId> = std::sync::OnceLock::new();
159static OFF_THREAD: std::sync::Mutex<Vec<(&'static str, String)>> =
160 std::sync::Mutex::new(Vec::new());
161const OFF_THREAD_CAP: usize = 512;
163
164fn kind_of(level: log::Level) -> &'static str {
165 match level {
166 log::Level::Error => "error",
167 log::Level::Warn => "warn",
168 _ => "log",
169 }
170}
171
172fn tee(level: log::Level, line: String) {
173 if !sk_tree::log::is_enabled() {
174 return;
175 }
176 let kind = kind_of(level);
177 if MAIN_THREAD.get() == Some(&std::thread::current().id()) {
178 sk_tree::log::record(kind, line);
179 return;
180 }
181 if let Ok(mut queue) = OFF_THREAD.lock() {
182 if queue.len() >= OFF_THREAD_CAP {
183 queue.remove(0); }
185 queue.push((kind, line));
186 }
187}
188
189fn drain_log_tee() {
191 if !sk_tree::log::is_enabled() {
192 return;
193 }
194 let Ok(mut queue) = OFF_THREAD.try_lock() else {
195 return;
196 };
197 for (kind, line) in queue.drain(..) {
198 sk_tree::log::record(kind, line);
199 }
200}
201
202fn parse_level(word: &str) -> Option<log::LevelFilter> {
203 match word.trim().to_ascii_lowercase().as_str() {
204 "" | "info" | "1" | "true" => Some(log::LevelFilter::Info),
205 "off" | "0" | "false" => Some(log::LevelFilter::Off),
206 "error" => Some(log::LevelFilter::Error),
207 "warn" => Some(log::LevelFilter::Warn),
208 "debug" => Some(log::LevelFilter::Debug),
209 "trace" => Some(log::LevelFilter::Trace),
210 _ => None,
211 }
212}
213
214fn install_logger() {
215 let _ = MAIN_THREAD.set(std::thread::current().id());
216 let spec = std::env::var("SK_LOG").unwrap_or_default();
217 let mut default = log::LevelFilter::Off;
218 let mut directives: Vec<(String, log::LevelFilter)> = Vec::new();
219 let mut saw_bare = false;
220 for part in spec.split(',') {
221 let part = part.trim();
222 if part.is_empty() {
223 continue;
224 }
225 match part.split_once('=') {
226 Some((target, level)) => match parse_level(level) {
227 Some(l) => directives.push((target.trim().to_string(), l)),
228 None => eprintln!("[sk] SK_LOG: {level:?} is not a level — ignoring {part:?}"),
229 },
230 None => match parse_level(part) {
231 Some(l) => {
232 default = l;
233 saw_bare = true;
234 }
235 None => eprintln!("[sk] SK_LOG={part:?} is not a level — using info"),
236 },
237 }
238 }
239 if !saw_bare && directives.is_empty() && !spec.is_empty() {
241 default = log::LevelFilter::Info;
242 }
243 directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
244 let max = directives
245 .iter()
246 .map(|(_, l)| *l)
247 .chain([default])
248 .max()
249 .unwrap_or(default);
250 let logger: &'static StderrLogger = Box::leak(Box::new(StderrLogger {
251 directives,
252 default,
253 }));
254 if log::set_logger(logger).is_ok() {
255 log::set_max_level(max);
257 }
258}
259
260#[cfg(test)]
261#[test]
262fn devtools_are_in_every_build_that_did_not_opt_out() {
263 assert_eq!(cfg!(sk_devtools), !cfg!(feature = "no-devtools"));
264}
265
266#[cfg(test)]
267mod logger_tests {
268 use super::*;
269 use log::LevelFilter as L;
270
271 fn logger(spec: &[(&str, L)], default: L) -> StderrLogger {
272 let mut directives: Vec<(String, L)> =
273 spec.iter().map(|(t, l)| ((*t).to_string(), *l)).collect();
274 directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
275 StderrLogger {
276 directives,
277 default,
278 }
279 }
280
281 #[test]
282 fn the_longest_matching_directive_wins() {
283 let l = logger(&[("gpui", L::Warn), ("gpui::window", L::Debug)], L::Off);
284 assert_eq!(l.level_for("gpui::window"), L::Debug);
285 assert_eq!(l.level_for("gpui::platform"), L::Warn);
286 assert_eq!(l.level_for("sk_tree"), L::Off);
287 }
288
289 #[test]
290 fn target_boundaries_are_module_separators() {
291 assert!(target_matches("gpui::window", "gpui"));
292 assert!(target_matches("gpui", "gpui"));
293 assert!(!target_matches("gpui_windows::events", "gpui"));
294 }
295}
296
297struct Shell;
298
299thread_local! {
300 static SHELL: RefCell<Option<WeakEntity<Shell>>> = const { RefCell::new(None) };
301 static MAIN_WINDOW: std::cell::Cell<Option<gpui::AnyWindowHandle>> =
304 const { std::cell::Cell::new(None) };
305}
306
307fn sync_layout() {
316 let Some(handle) = MAIN_WINDOW.with(|w| w.get()) else {
317 return;
318 };
319 let draw = |window: &mut gpui::Window, cx: &mut gpui::App| {
320 sk_runtime::bridge::with_draw(|| window.draw(cx).clear(cx))
321 };
322 let drew = sk_runtime::bridge::with_app(|cx| {
323 handle.update(cx, |_, window, cx| draw(window, cx)).is_ok()
324 });
325 if drew != Some(false) || sk_tree::in_input_dispatch() {
326 return;
327 }
328 sk_runtime::with_commit(|window, cx| {
329 if window.window_handle() == handle {
330 draw(window, cx);
331 }
332 });
333}
334
335fn commit_boot_tree(runtime: &JsRuntime) {
336 runtime.ctx().drain_microtasks();
338 sk_tree::flush_changes();
339}
340
341#[cfg(test)]
342mod startup_tests {
343 #[test]
344 fn boot_microtask_styles_are_computed_before_any_frame_pump() {
345 sk_runtime::testing::on_js_thread(|| {
346 sk_runtime::JsRuntime::with(|runtime| {
347 sk_tree::install(runtime);
348 runtime.eval(
349 "globalThis.__startupRoot = __sk_create_root(); \
350 globalThis.__startupNode = __sk_create_element(__sk_intern('button')); \
351 __sk_insert(__startupNode, __startupRoot, 0); \
352 __sk_set_style(__startupNode, __sk_intern('opacity'), '0.25'); \
353 queueMicrotask(() => __sk_set_style(__startupNode, __sk_intern('opacity'), '0.75'));",
354 "sk://startup-regression.js",
355 ).expect("queue the mount/load microtask through the native DOM bridge");
356 super::commit_boot_tree(runtime);
357 let node = runtime
358 .ctx()
359 .global_get("__startupNode")
360 .unwrap()
361 .as_number()
362 .unwrap() as u32;
363 let styles = sk_tree::devtools::computed_styles(node)
365 .expect("boot writes must already be cascaded");
366 let base = &styles.iter().find(|(name, _)| *name == "base").unwrap().1;
367 assert!(
368 base.contains("0.75"),
369 "the first draw must not await pump_frame to cascade boot opacity: {base}"
370 );
371 })
372 });
373 }
374}
375
376const HIDDEN_START_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
377
378fn reveal_if_unreachable(cx: &mut App) {
381 cx.spawn(async move |cx| {
382 cx.background_executor().timer(HIDDEN_START_GRACE).await;
383 let _ = cx.update(|_| {
384 if shutdown::is_closing() || window::revealed() || sk_desktop::tray::Tray::app_shown() {
385 return;
386 }
387 let line = format!(
388 "[sk] started hidden, and no tray icon is up after {} s: showing the window so the app can be reached",
389 HIDDEN_START_GRACE.as_secs()
390 );
391 eprintln!("{line}");
392 sk_tree::log::record("warn", line);
393 window::request_activate();
394 });
395 })
396 .detach();
397}
398
399#[cfg(target_os = "windows")]
400fn reveal_startup_window(cx: &mut App, activate: bool) {
401 let Some(handle) = MAIN_WINDOW.with(|window| window.get()) else {
402 window::cancel_startup_reveal();
403 return;
404 };
405 cx.spawn(async move |cx| {
406 if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
407 window::cancel_startup_reveal();
408 return;
409 }
410 let hwnd = cx.update(|cx| handle.update(cx, |_, window, _| window::capture_hwnd(window)));
411 let Ok(Some(hwnd)) = hwnd else {
412 window::cancel_startup_reveal();
413 return;
414 };
415 popout_win::paint_now(hwnd);
417 if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
418 window::cancel_startup_reveal();
419 return;
420 }
421 let shown = cx.update(|cx| {
422 handle.update(cx, |_, window, _| {
423 window.show_window(
424 activate,
425 || !shutdown::is_closing() && !sk_runtime::bridge::poisoned(),
426 move |shown| {
427 window::cancel_startup_reveal();
428 if shown {
429 quiet::send_hwnd_to_back(hwnd);
430 }
431 if !shown && !shutdown::is_closing() {
432 eprintln!("[window] the prepared startup window could not be shown");
433 }
434 },
435 )
436 })
437 });
438 if !matches!(shown, Ok(true)) {
439 window::cancel_startup_reveal();
440 eprintln!("[window] failed to reveal the prepared startup window");
441 }
442 })
443 .detach();
444}
445
446pub(crate) fn main_window_display(cx: &mut App) -> Option<gpui::DisplayId> {
448 let handle = MAIN_WINDOW.with(|w| w.get())?;
449 handle
450 .update(cx, |_, window, cx| window.display(cx).map(|d| d.id()))
451 .ok()
452 .flatten()
453}
454
455#[cfg(sk_devtools)]
457pub(crate) fn main_window_id() -> Option<u64> {
458 MAIN_WINDOW
459 .with(|w| w.get())
460 .map(|h| h.window_id().as_u64())
461}
462
463pub(crate) fn refresh_main(cx: &mut App) {
466 notify_shell(cx);
467}
468
469pub(crate) fn notify_shell(cx: &mut App) {
470 SHELL.with(|s| {
471 if let Some(shell) = s.borrow().as_ref().and_then(|w| w.upgrade()) {
472 shell.update(cx, |_, cx| cx.notify());
473 }
474 });
475}
476
477host_fn!(fn sk_set_status(g, args) {
478 let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
479 .unwrap_or_default();
480 sk_tree::log::set_status(text);
482 sk_runtime::redjs::api::Value::undefined().0
483});
484
485host_fn!(fn sk_perf_mark(g, args) {
486 let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
487 .unwrap_or_default();
488 perf::mark(&text);
489 sk_runtime::redjs::api::Value::undefined().0
490});
491
492host_fn!(fn sk_log(g, args) {
493 let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
494 .unwrap_or_default();
495 sk_tree::log::record("log", text);
496 sk_runtime::redjs::api::Value::undefined().0
497});
498
499fn pump_frame(window: &mut Window, cx: &mut App) {
501 #[cfg(sk_devtools)]
502 let _allocation_scope = crate::heapcount::recording::scope("runtime", "frame/pump");
503 if background::pumped_once() && (window::cloaked() || window::occluded()) {
506 idle::rearm_paced(window, pump_frame, Some(idle::CLOAKED_INTERVAL));
507 return;
508 }
509 perf::frame();
510 background::note_frame();
511 drain_log_tee();
513 if sk_runtime::bridge::poisoned() {
514 crash_window::on_poisoned(cx);
516 return;
517 }
518 if first_wave_waits(window) {
519 idle::rearm_unpaced(window, pump_frame);
520 return;
521 }
522 sk_tree::flush_pending_mouse_move(window, cx);
524 #[cfg(sk_devtools)]
525 inspector::poll_frame(cx);
526 js_wave(window, cx, Wave::Frame);
527 window::note_painted_frame();
528 after_wave(window, cx);
529 #[cfg(sk_devtools)]
530 if devtools::busy() {
531 idle::note_moved();
532 }
533 idle::rearm(
534 window,
535 pump_frame,
536 window::app_focused(cx) || quiet::never_focus(),
537 );
538 perf::pump_done();
539 sk_tree::settle_container_queries(window, cx);
543 sk_tree::update_layout_observers(window, cx);
544 background::note_frame();
546}
547
548#[derive(Clone, Copy, PartialEq, Eq)]
549pub(crate) enum Wave {
550 Frame,
551 Background,
553}
554
555pub(crate) fn js_wave(window: &mut Window, cx: &mut App, wave: Wave) {
557 let focused = window::app_focused(cx) || quiet::never_focus();
558 with_published(window, cx, Phase::Commit, || {
559 if wave == Wave::Frame {
561 let n = FRAME_NO.with(|f| {
562 let n = f.get().wrapping_add(1);
563 f.set(n);
564 n
565 });
566 boot_mode::poll_frame(n);
567 }
568 reload::pump();
569 sk_runtime::with_commit(|window, cx| window::pump(window, cx));
571 sk_runtime::runtime::set_frame_budget_ms(window::frame_budget_ms());
572 let flags = match wave {
573 Wave::Frame => PUMP_TIMERS | PUMP_RAF | PUMP_MICROTASKS,
574 Wave::Background => PUMP_TIMERS | PUMP_MICROTASKS,
575 };
576 JsRuntime::with(|rt| {
577 let pumped = std::time::Instant::now();
578 let stats = rt.pump(flags);
579 let elapsed = pumped.elapsed();
580 if wave == Wave::Frame {
581 let next_work = sk_runtime::redjs::web::next_work_ms(rt.raw());
582 #[cfg_attr(not(feature = "audio"), allow(unused_mut))]
583 let mut report = idle::Wave::from_stats(&stats, next_work, elapsed);
584 #[cfg(feature = "audio")]
585 {
586 report.audio = sk_runtime::redjs::webapi::audio::busy(rt.raw());
587 }
588 idle::note_wave(report);
589 }
590 #[cfg(sk_devtools)]
591 devtools::trace::note_js(elapsed.as_secs_f32() * 1000.0);
592 for err in rt.drain_errors() {
593 eprintln!("[js uncaught] {}\n{}", err.header, err.stack);
594 sk_tree::log::record(
595 "error",
596 format!("[js uncaught] {}\n{}", err.header, err.stack),
597 );
598 }
599 reclaim::after_wave(
600 rt,
601 focused,
602 wave == Wave::Background || window::page_hidden(),
603 );
604 });
605 #[cfg(sk_devtools)]
607 {
608 devtools::pump();
609 }
610 js::frame();
611 sk_permissions::pump();
612 sk_desktop::pump();
613 embed::pump();
614 #[cfg(feature = "storages")]
616 sk_storage::pump();
617 });
618 if wave == Wave::Frame {
620 let later = JsRuntime::try_with(|rt| {
621 let at = sk_runtime::redjs::web::next_work_ms(rt.raw())?;
622 let ms = at - sk_runtime::redjs::web::now_ms();
623 Some(std::time::Duration::from_secs_f64(ms.max(0.0) / 1000.0))
624 });
625 idle::note_later_work(later.flatten());
626 }
627}
628
629pub(crate) fn after_wave(window: &mut Window, cx: &mut App) {
631 publish_video_device();
634 let media_moved = sk_tree::frame_tick(window, cx);
635 if sk_tree::media_polls() {
636 sk_runtime::frames::wake_at(std::time::Instant::now() + idle::MEDIA_POLL);
637 }
638 let flush = sk_tree::flush_changes_kind();
639 let tree_moved = flush != sk_tree::Flush::Unchanged;
640 let animating = sk_tree::animating() && !window::page_hidden();
642 let moving = animating || media_moved;
643 if flush == sk_tree::Flush::DrawnBySync {
644 sk_tree::perf::note_sync_tail(!moving);
646 }
647 if flush == sk_tree::Flush::Changed || moving {
648 notify_shell(cx);
649 }
650 if tree_moved || moving {
651 if tree_moved || media_moved {
653 idle::note_moved();
654 } else {
655 idle::note_animating();
656 }
657 popout::notify_all(cx);
659 }
660 #[cfg(sk_devtools)]
662 devtools::ws::broadcast_frame();
663}
664
665impl Render for Shell {
666 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
667 #[cfg(sk_devtools)]
668 let _allocation_scope = crate::heapcount::recording::scope("render", "frame/build");
669 perf::render_begin();
670 let el = self.render_body(window, cx);
671 perf::render_done();
672 #[cfg(sk_devtools)]
674 devtools::ws::broadcast_frame();
675 el
676 }
677}
678
679impl Shell {
680 fn render_body(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {
681 let shell = div()
682 .relative()
683 .flex()
684 .flex_col()
685 .size_full()
686 .text_color(gpui::white())
687 .font_family(".SystemUIFont");
688 #[cfg(not(target_os = "windows"))]
689 let shell = chrome_posix::wrap(shell, window, true);
690 let shell = match window::opaque_fill(window::backdrop(), window::effective_dark(window)) {
691 Some(fill) => shell.bg(fill),
692 None => shell,
693 };
694 if !window::fallback_titlebar() {
695 return shell
696 .child(sk_tree::build_root(window, cx))
697 .children(sk_tree::build_view_transition())
698 .children(window_controls_overlay(window))
699 .children(inspector_overlay());
700 }
701 shell
702 .child(
703 div()
704 .id("titlebar")
705 .window_control_area(WindowControlArea::Drag)
706 .h(px(window::title_bar_height()))
707 .overflow_hidden()
708 .px(px(14.))
709 .flex()
710 .items_center()
711 .text_size(px(13.))
712 .child(window::title()),
713 )
714 .child(
717 div()
718 .flex_1()
719 .min_h(px(0.))
720 .child(sk_tree::build_root(window, cx)),
721 )
722 .children(sk_tree::build_view_transition())
723 .children(window_controls_overlay(window))
724 .children(inspector_overlay())
725 }
726}
727
728fn inspector_overlay() -> Option<gpui::Div> {
730 #[cfg(sk_devtools)]
731 {
732 devtools::highlight_overlay()
733 }
734 #[cfg(not(sk_devtools))]
735 {
736 None
737 }
738}
739
740fn window_controls_overlay(window: &Window) -> Option<gpui::Div> {
745 let (height, overlay) = window::overlay()?;
746 let dark = window::effective_dark(window);
747 const MIN: &str = "\u{e921}";
749 const MAX: &str = "\u{e922}";
750 const CLOSE: &str = "\u{e8bb}";
751 let glyph_font = gpui::Font {
752 family: "Segoe Fluent Icons".into(),
753 fallbacks: Some(gpui::FontFallbacks::from_fonts(vec![
754 "Segoe MDL2 Assets".to_string(),
755 "Segoe UI Symbol".to_string(),
756 ])),
757 features: Default::default(),
758 weight: Default::default(),
759 style: Default::default(),
760 };
761 let symbol = overlay
762 .symbol_color
763 .map(rgba)
764 .unwrap_or_else(|| rgba(if dark { 0xffffffe0 } else { 0x000000e0 }));
765 let hover = if dark { 0xffffff1a } else { 0x0000000f };
766 let button = |id: &'static str, glyph: &'static str, area: WindowControlArea, hover: u32| {
767 div()
768 .id(id)
769 .w(px(window::OVERLAY_BUTTON_WIDTH))
770 .h(px(height))
771 .flex()
772 .items_center()
773 .justify_center()
774 .text_size(px(10.))
775 .text_color(symbol)
776 .font(glyph_font.clone())
777 .window_control_area(area)
778 .hover(|s| s.bg(rgba(hover)))
779 .child(glyph)
780 };
781 let mut strip = div()
782 .absolute()
783 .top_0()
784 .right_0()
785 .h(px(height))
786 .flex()
787 .flex_row();
788 if let Some(bg) = overlay.color {
789 strip = strip.bg(rgba(bg));
790 }
791 Some(
792 strip
793 .child(button("wco-min", MIN, WindowControlArea::Min, hover))
794 .child(button("wco-max", MAX, WindowControlArea::Max, hover))
795 .child(button(
796 "wco-close",
797 CLOSE,
798 WindowControlArea::Close,
799 0xc42b1cff,
800 )),
801 )
802}
803
804fn publish_app_root() {
807 #[cfg(feature = "prod")]
808 if prod::publish_asset_store() {
809 return;
810 }
811 if let Some(dir) = std::env::var_os("SK_APP_ROOT") {
812 if !dir.is_empty() {
813 sk_tree::set_asset_base(std::path::PathBuf::from(dir));
814 }
815 }
816}
817
818#[cfg(feature = "webview")]
819fn install_iframe_backend() {
820 #[cfg(feature = "storages")]
821 let data = embed::data_dir()
822 .map(std::path::Path::to_path_buf)
823 .or_else(|| {
824 sk_storage::default_folder(boot_mode::app_name().as_deref())
825 .parent()
826 .map(std::path::Path::to_path_buf)
827 });
828 #[cfg(not(feature = "storages"))]
829 let data: Option<std::path::PathBuf> = None;
830 let user_data = data
831 .unwrap_or_else(|| std::env::temp_dir().join("skathi"))
832 .join("webview");
833 let config = sk_webview::Config {
834 assets: std::rc::Rc::new(|path| sk_tree::read_app_asset(path)),
835 user_data,
836 page_origin: "app://redjs".into(),
837 devtools: !cfg!(feature = "prod"),
838 };
839 if let Some(backend) = sk_webview::backend(config) {
840 sk_tree::iframe::set_backend(backend, std::rc::Rc::new(sk_runtime::frames::wake));
841 }
842}
843
844#[cfg(not(feature = "webview"))]
845fn install_iframe_backend() {
846 sk_tree::iframe::set_unavailable(
847 "this app's host was built without Skathi's `webview` feature. Enable it in the `skathi` \
848 dependency's features to use <iframe>.",
849 );
850}
851
852fn close_iframes_on_quit(cx: &mut App) {
854 std::mem::forget(cx.on_app_quit(|_| {
855 sk_tree::iframe::shutdown();
856 std::future::ready(())
857 }));
858}
859
860#[cfg(target_os = "windows")]
864fn publish_video_device() {
865 use std::cell::Cell;
866 #[cfg(feature = "native-dx12")]
867 {
868 static INSTALL: std::sync::Once = std::sync::Once::new();
869 INSTALL.call_once(|| {
870 fn provide() -> Result<Option<sk_tree::SharedVideoDevice>, String> {
871 gpui_windows::ensure_renderer_d3d11_device()
872 .map(|lease| {
873 lease.map(|lease| sk_tree::SharedVideoDevice {
874 device: lease.device,
875 generation: lease.generation,
876 keep_alive: lease.keep_alive,
877 })
878 })
879 .map_err(|error| {
880 format!("Could not initialize renderer video bridge: {error:#}")
881 })
882 }
883 if let Err(error) = unsafe { sk_tree::install_video_device_provider(provide) } {
885 log::error!("Could not install lazy video device provider: {error}");
886 }
887 sk_tree::surface::install_d3d12_provider(|| {
888 gpui_windows::renderer_d3d12_device().map(|handle| sk_tree::surface::D3D12Lease {
889 device: handle.device,
890 queue: handle.queue,
891 generation: handle.generation,
892 keep_alive: handle.keep_alive,
893 })
894 });
895 });
896 }
897 thread_local! {
898 static PUBLISHED: Cell<u64> = const { Cell::new(0) };
900 }
901 let (ptr, generation) = gpui_windows::renderer_d3d11_device();
902 let previous = PUBLISHED.with(Cell::get);
903 if generation == 0 || previous == generation || (ptr.is_null() && previous == 0) {
904 return;
905 }
906 let first = previous == 0;
908 PUBLISHED.with(|p| p.set(generation));
909 unsafe { sk_tree::set_video_device(ptr, generation) };
911 if first {
912 return;
913 }
914 sk_tree::surface_device_changed();
915 let rebuilt = sk_tree::video_device_changed();
916 let msg = format!(
917 "[video] the renderer recreated its D3D11 device (generation {generation}) — rebuilt \
918 {rebuilt} <video> element(s) on it, resuming where they were"
919 );
920 eprintln!("{msg}");
921 sk_tree::log::record("window", msg);
922}
923
924#[cfg(not(target_os = "windows"))]
925fn publish_video_device() {}
926
927fn install_http_client(app: gpui::Application) -> gpui::Application {
930 app.with_http_client(std::sync::Arc::new(http_client::RedjsHttpClient::new()))
931}
932
933pub fn run_exe() {
935 owner::watch();
937 let args = sk_desktop::args::process();
939 if args.host.host_info && !payload::embedded_present() {
941 println!("{}", payload::host_info_json());
942 return;
943 }
944 if std::env::args_os()
946 .nth(1)
947 .is_some_and(|a| a == embed::HOST_TYPES_FLAG)
948 && !payload::embedded_present()
949 {
950 return;
951 }
952 if let Some(dist) = args.host.sk_dist.as_deref().filter(|d| !d.is_empty()) {
954 std::env::set_var("SK_DIST", dist);
955 }
956 {
959 let launch_cfg = if args.host.devtools {
960 None
961 } else {
962 boot_mode::launch_config()
963 };
964 #[cfg(not(feature = "prod"))]
966 let dev_slot = Some(slot::dir());
967 #[cfg(feature = "prod")]
968 let dev_slot = None;
969 let build_name = if args.host.devtools {
970 None
971 } else {
972 boot_mode::app_name()
973 };
974 if let sk_desktop::launch::Outcome::Exit(code) =
975 sk_desktop::launch::start(args, launch_cfg.as_deref(), build_name, dev_slot)
976 {
977 std::process::exit(code);
978 }
979 if !args.host.devtools {
980 sk_desktop::launch::register_declared();
981 }
982 }
983 #[cfg(sk_devtools)]
985 inspector::init();
986 #[cfg(feature = "prod")]
987 {
988 #[cfg(sk_devtools)]
989 let inspecting = inspector::is_devtools_host();
990 #[cfg(not(sk_devtools))]
991 let inspecting = false;
992 if !inspecting {
993 prod::require_payload();
994 }
995 }
996 run_app();
997 shutdown::finish();
999}
1000
1001pub(crate) fn run_embedded() {
1004 let args = sk_desktop::args::process();
1005 if !embed::desktop_launch_prepared() {
1006 let _ = sk_desktop::launch::start(args, None, boot_mode::app_name(), None);
1007 }
1008 run_app();
1009 shutdown::finish();
1010}
1011
1012fn run_app() {
1013 install_logger();
1015 #[cfg(all(feature = "webgpu", target_os = "windows"))]
1016 shared_gpu::install().expect("installing shared graphics device provider");
1017 perf::boot();
1018 #[cfg(sk_devtools)]
1019 if heapcount::on() {
1020 sk_tree::perf::set_live_bytes_probe(|| heapcount::snapshot().map(|s| s.0));
1021 sk_tree::devtools::set_image_tracking(true);
1022 }
1023 let app = install_http_client(application()).with_quit_mode(gpui::QuitMode::LastWindowClosed);
1025 #[cfg(target_os = "macos")]
1027 app.on_reopen(|_| embed::reopen());
1028 #[cfg(feature = "prod")]
1029 let app = if payload::get().is_some() {
1030 payload::install_effects();
1031 app.with_assets(payload::GpuiAssets)
1032 } else {
1033 app
1034 };
1035 app.run(|cx: &mut App| {
1036 #[cfg(sk_devtools)]
1038 let devtools_mode = inspector::is_devtools_host();
1039 #[cfg(not(sk_devtools))]
1040 let devtools_mode = false;
1041 sk_elements::init(cx);
1042 publish_app_root();
1043 std::mem::forget(cx.on_app_quit(|_| {
1046 sk_tree::surface_app_closed();
1047 window::cancel_startup_reveal();
1048 shutdown::begin("quit");
1049 window::page_hide();
1050 std::future::ready(())
1051 }));
1052 std::mem::forget(cx.on_app_quit(|_| {
1053 JsRuntime::try_with(|runtime| js::shutdown(runtime.ctx()));
1054 std::future::ready(())
1055 }));
1056 close_iframes_on_quit(cx);
1057 std::mem::forget(cx.intercept_keystrokes(sk_tree::pointer_lock_intercept_escape));
1059 #[cfg(sk_devtools)]
1060 {
1061 inspector::install_hotkey(cx);
1062 std::mem::forget(cx.on_app_quit(|_| {
1064 shutdown::step("inspector", inspector::close_children);
1065 std::future::ready(())
1066 }));
1067 }
1068 #[cfg(feature = "storages")]
1070 std::mem::forget(cx.on_app_quit(|_| {
1071 shutdown::step("storage", || {
1072 if let Err(e) = sk_storage::flush() {
1073 eprintln!("[storage] localStorage: the last change was not written: {e}");
1074 }
1075 if let Err(e) = sk_storage::cookies::flush() {
1076 eprintln!("[storage] cookies: the last change was not written: {e}");
1077 }
1078 });
1079 shutdown::step("http-cache", sk_runtime::redjs::webapi::http::cache::uninstall);
1080 std::future::ready(())
1081 }));
1082 #[cfg(feature = "indexeddb")]
1084 std::mem::forget(cx.on_app_quit(|_| {
1085 let t = std::time::Instant::now();
1086 let done = shutdown::step("indexeddb", || sk_runtime::redjs::ffi::redjs_idb_shutdown(2_000));
1087 if done == 0 {
1088 eprintln!(
1089 "[sk] IndexedDB did not finish closing within {} ms; the next start recovers from its WAL",
1090 t.elapsed().as_millis()
1091 );
1092 }
1093 std::future::ready(())
1094 }));
1095 shutdown::install_test_delay(cx);
1096 #[cfg(sk_devtools)]
1098 devtools::arm();
1099
1100 #[cfg(sk_devtools)]
1103 let window_json =
1104 if devtools_mode { inspector::window_config() } else { boot_mode::window_config() };
1105 #[cfg(not(sk_devtools))]
1106 let window_json = boot_mode::window_config();
1107 #[cfg(feature = "storages")]
1109 let http_cache_mb = http_client::cache_mb(window_json.as_deref());
1110 let cfg = window::load_config(window_json);
1111
1112 #[cfg(sk_devtools)]
1114 devtools::boot(window::devtools_config_enabled());
1115
1116 sk_desktop::network::install();
1118
1119 #[cfg(all(sk_devtools, not(feature = "native-aot")))]
1120 if let Some(summary) = devtools_mode.then(|| inspector::engine_without_native(
1121 std::env::var_os("SK_DEVTOOLS_ENGINE").as_deref(),
1122 std::env::var_os("SK_DEVTOOLS_NATIVE_IMAGE").is_some(),
1123 ).err()).flatten() {
1124 eprintln!("[native-aot] {summary}");
1125 embed::finished(false, summary);
1126 cx.quit();
1127 return;
1128 }
1129 #[cfg(feature = "native-aot")]
1130 if let Err(error) = native_aot::prepare(devtools_mode) {
1131 let summary = if devtools_mode {
1132 format!("native inspector preparation failed: {error}")
1133 } else {
1134 format!(
1135 "this app's native image cannot run on this host ({error}). \
1136 Rebuild the app with `sk build --aot` from the sk that matches this host."
1137 )
1138 };
1139 eprintln!("[native-aot] {summary}");
1140 let embedded =
1141 payload::get().is_some_and(|l| matches!(l.source, payload::Source::Embedder(_)));
1142 if !devtools_mode && !embedded {
1143 payload::message_box(&summary);
1144 std::process::exit(3);
1145 }
1146 embed::finished(false, summary);
1147 cx.quit();
1148 return;
1149 }
1150 JsRuntime::init();
1151 #[cfg(target_os = "windows")]
1152 consent_window::install(cx);
1153 let setup_result = JsRuntime::with(|rt| -> Result<(), String> {
1154 rt.register("__sk_set_status", 1, sk_set_status as *const _);
1155 rt.register("__sk_log", 1, sk_log as *const _);
1156 rt.register("__sk_perf_mark", 1, sk_perf_mark as *const _);
1157 reload::install(rt);
1158 sk_tree::install(rt);
1159 window::install(rt);
1160 popout::install(rt);
1161 #[cfg(feature = "audio")]
1162 microphone::install();
1163 #[cfg(feature = "spatial-audio")]
1164 spatial_audio::install(rt);
1165 #[cfg(feature = "clipboard")]
1167 sk_clipboard::install();
1168 sk_permissions::install(rt);
1169 sk_locale::install(rt);
1170 if !devtools_mode {
1172 install_iframe_backend();
1173 }
1174 sk_desktop::set_log_sink(|kind, text| sk_tree::log::record(kind, text));
1175 sk_desktop::install(rt);
1176 sk_desktop::dialog::set_owner_resolver(dialogs::owner);
1178 sk_permissions::set_asker(dialogs::ask_permission);
1179 sk_permissions::set_app_name(&cfg.title);
1180 crash_window::set_app_name(&cfg.title);
1181 #[cfg(feature = "storages")]
1183 if !devtools_mode {
1184 let encrypted = embed::storage_encrypted();
1185 if embed::data_dir().is_some() || encrypted.is_some() {
1186 let directory = embed::data_dir().map(std::path::Path::to_path_buf)
1187 .unwrap_or_else(|| sk_storage::default_folder(boot_mode::app_name().as_deref()));
1188 sk_storage::set_storage_folder(&directory, encrypted)?;
1189 if encrypted == Some(true) {
1190 sk_storage::encrypt_local_storage_at(&directory)?;
1191 }
1192 }
1193 }
1194 #[cfg(feature = "storages")]
1195 sk_storage::install(
1196 rt,
1197 if devtools_mode { Some("sk-devtools".to_string()) } else { boot_mode::app_name() },
1198 );
1199 #[cfg(feature = "storages")]
1201 if !devtools_mode {
1202 if let Some(directory) = embed::data_dir() {
1203 sk_storage::http_cache::install_at(http_cache_mb, directory.join("cache").join("http"));
1204 } else {
1205 sk_storage::http_cache::install(http_cache_mb);
1206 }
1207 }
1208 #[cfg(feature = "storages")]
1210 sk_permissions::set_decisions_file(sk_storage::cookies::folder().map(|f| f.join("permissions.json")));
1211 if !devtools_mode {
1213 tray::install(rt)?;
1214 #[cfg(feature = "hotkeys")]
1215 hotkeys::install(rt)?;
1216 embed::setup(rt)?;
1217 }
1218 #[cfg(sk_devtools)]
1219 devtools::install(rt);
1220 embed::install(rt);
1221 unsafe { sk_runtime::standins::install_missing(rt.raw()) };
1222 Ok(())
1223 });
1224 if let Err(error) = setup_result {
1225 let summary = format!("host setup failed: {error}");
1226 eprintln!("[embed] {summary}");
1227 embed::finished(false, summary);
1228 cx.quit();
1229 return;
1230 }
1231
1232 let (bounds, display_id) = placement::initial_bounds(&cfg, cx);
1233 let startup_visible = embed::visible();
1234 let startup_focus = !devtools_mode && !quiet::never_focus() && embed::activates();
1235 let defer_reveal = cfg!(target_os = "windows") && startup_visible;
1236 if defer_reveal {
1237 window::begin_startup_reveal();
1238 }
1239 cx.open_window(
1240 WindowOptions {
1241 window_bounds: Some(WindowBounds::Windowed(bounds)),
1242 display_id,
1243 window_background: cfg.backdrop.to_gpui(),
1244 titlebar: Some(TitlebarOptions {
1245 title: Some(cfg.title.clone().into()),
1246 appears_transparent: cfg.title_bar_style == window::TitleBarStyle::Hidden,
1248 traffic_light_position: window::traffic_light_position(
1249 cfg.title_bar_style == window::TitleBarStyle::Hidden,
1250 cfg.title_bar_height,
1251 ),
1252 ..Default::default()
1253 }),
1254 is_resizable: cfg.resizable,
1255 is_minimizable: cfg.minimizable,
1256 app_owns_titlebar_drag: cfg.title_bar_style == window::TitleBarStyle::Hidden,
1258 window_min_size: match (cfg.min_width, cfg.min_height) {
1259 (None, None) => None,
1260 (w, h) => Some(size(px(w.unwrap_or(0.0)), px(h.unwrap_or(0.0)))),
1261 },
1262 inactive_frame_interval: None,
1264 show: startup_visible && !defer_reveal,
1266 focus: startup_focus,
1267 #[cfg(target_os = "linux")]
1268 window_decorations: Some(gpui::WindowDecorations::Client),
1269 #[cfg(target_os = "linux")]
1270 app_id: embed::desktop_id().or_else(|| sk_desktop::launch::identity().map(|i| i.id.clone())),
1271 ..Default::default()
1272 },
1273 |window, cx| {
1274 if std::env::var_os("SK_RETAINED_LAYOUT").as_deref() != Some(std::ffi::OsStr::new("0")) {
1275 window.vn_enable_retained_layout();
1276 }
1277 quiet::send_to_back(window);
1279 publish_video_device();
1280 let shell = cx.new(|_| Shell);
1281 SHELL.with(|s| *s.borrow_mut() = Some(shell.downgrade()));
1282 window::init(&cfg, window, cx);
1283 if let Some(hwnd) = window::capture_hwnd(window) {
1285 sk_desktop::launch::set_window(hwnd);
1286 }
1287 window.on_window_should_close(cx, |window, cx| {
1289 let closing = window::should_close();
1290 if closing {
1291 window::cancel_startup_reveal();
1292 shutdown::begin("a close request (WM_CLOSE)");
1293 }
1294 if closing && popout::count() > 0 {
1296 sk_tree::log::record(
1297 "window",
1298 format!(
1299 "[window] the primary window is closing — taking {} pop-out(s) \
1300 with it",
1301 popout::count()
1302 ),
1303 );
1304 popout::close_all(cx);
1305 }
1306 closing && dialogs::may_close_now(window.window_handle(), cx)
1308 });
1309 window.on_next_frame(pump_frame);
1310 shell
1311 },
1312 )
1313 .map(|handle| MAIN_WINDOW.with(|w| w.set(Some(handle.into()))))
1314 .unwrap();
1315 background::start(cx);
1316 #[cfg(target_os = "windows")]
1317 sk_runtime::frames::set_waker(|| {
1318 gpui_windows::wake_frames();
1319 background::poke();
1320 });
1321
1322 sk_tree::set_sync_layout(sync_layout);
1324 let text_system = cx.text_system().clone();
1325 sk_css::set_font_source(move || text_system.all_font_names());
1326 let metric_system = cx.text_system().clone();
1327 let metric_text = RefCell::new((0usize, gpui::WindowTextSystem::new(metric_system.clone())));
1328 sk_css::set_font_metric_source(move |font, size| {
1329 let mut cache = metric_text.borrow_mut();
1330 let (queries, text) = &mut *cache;
1331 if *queries >= 128 {
1333 *text = gpui::WindowTextSystem::new(metric_system.clone());
1334 *queries = 0;
1335 }
1336 *queries += 1;
1337 let run = gpui::TextRun { len: 1, font: font.clone(), color: gpui::black(), ..Default::default() };
1338 let lines = text.shape_text("0".into(), gpui::px(size), &[run], None, None).ok()?;
1339 let line = lines.first()?;
1340 let font_id = line.runs().first()?.font_id;
1341 Some(sk_css::FontRelativeMetrics {
1342 zero_advance: f32::from(line.size(gpui::px(size)).width),
1343 x_height: f32::from(text.x_height(font_id, gpui::px(size))),
1344 })
1345 });
1346
1347 #[cfg(sk_devtools)]
1349 let mut startup_error: Option<String> = None;
1350 with_published_app(cx, || {
1351 JsRuntime::with(|rt| {
1352 if let Err(e) = perf::boot_eval("preludes", || rt.eval(PRELUDE_JS, "sk://prelude.js")) {
1353 eprintln!("[js boot] {}\n{}", e.header, e.stack);
1354 #[cfg(all(sk_devtools, feature = "native-aot"))]
1355 if devtools_mode && sk_runtime::redjs::aot::is_active() {
1356 startup_error = Some(format!("native inspector prelude failed: {}", e.header));
1357 return;
1358 }
1359 }
1360 if let Err(e) = perf::boot_eval("preludes", || rt.eval(WINDOW_PRELUDE_JS, "sk://window.js")) {
1361 eprintln!("[js boot] {}\n{}", e.header, e.stack);
1362 #[cfg(all(sk_devtools, feature = "native-aot"))]
1363 if devtools_mode && sk_runtime::redjs::aot::is_active() {
1364 startup_error = Some(format!("native inspector prelude failed: {}", e.header));
1365 return;
1366 }
1367 }
1368 let scenario = std::env::var("SK_SCENARIO").unwrap_or_default();
1370 if !scenario.is_empty() {
1371 let safe: String = scenario
1372 .chars()
1373 .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
1374 .collect();
1375 let js = format!("globalThis.__SK_SCENARIO__ = \"{safe}\";");
1376 if let Err(e) = rt.eval(&js, "sk://scenario.js") {
1377 eprintln!("[js boot] {}\n{}", e.header, e.stack);
1378 }
1379 }
1380 #[cfg(sk_devtools)]
1381 if devtools_mode {
1382 if let Err(error) = inspector::boot(rt) {
1383 startup_error = Some(error);
1384 return;
1385 }
1386 } else {
1387 boot_mode::boot(rt);
1388 }
1389 #[cfg(not(sk_devtools))]
1390 boot_mode::boot(rt);
1391 window::content_loaded();
1392 commit_boot_tree(rt);
1393 });
1394 });
1395 #[cfg(sk_devtools)]
1396 if let Some(error) = startup_error {
1397 let summary = format!("inspector startup failed: {error}");
1398 eprintln!("[native-aot] {summary}");
1399 embed::finished(false, summary);
1400 window::cancel_startup_reveal();
1401 cx.quit();
1402 return;
1403 }
1404 refresh_main(cx);
1405 #[cfg(target_os = "windows")]
1406 if defer_reveal {
1407 reveal_startup_window(cx, startup_focus);
1408 }
1409 if !embed::visible() {
1411 background::note_frame();
1412 reveal_if_unreachable(cx);
1413 }
1414 if !devtools_mode && !quiet::never_focus() && embed::activates() {
1415 cx.activate(true);
1416 }
1417 #[cfg(sk_devtools)]
1418 if devtools_mode {
1419 inspector::watch_parent();
1420 }
1421 });
1422}