use std::cell::RefCell;
use gpui::{
div, prelude::*, px, rgba, size, App, Bounds, Context, TitlebarOptions, WeakEntity, Window,
WindowBounds, WindowControlArea, WindowOptions,
};
use gpui_platform::application;
use sk_runtime::runtime::{PUMP_MICROTASKS, PUMP_RAF, PUMP_TIMERS};
use sk_runtime::{host_fn, with_published, with_published_app, JsRuntime, Phase};
mod background;
#[cfg(feature = "prod")]
mod bytecode;
#[cfg(not(feature = "prod"))]
mod dev;
mod idle;
#[cfg(sk_devtools)]
mod devtools;
#[cfg(sk_devtools)]
pub mod heapcount;
#[cfg(sk_devtools)]
pub use heapcount::Counting as HostAllocator;
#[cfg(not(sk_devtools))]
pub use std::alloc::System as HostAllocator;
mod http_client;
#[cfg(all(sk_devtools, test))]
#[global_allocator]
static GLOBAL: heapcount::Counting = heapcount::Counting;
#[cfg(not(target_os = "windows"))]
mod chrome_posix;
#[cfg(target_os = "windows")]
#[doc(hidden)]
pub mod consent_window;
#[cfg(target_os = "windows")]
mod content_dialog;
#[doc(hidden)]
pub mod crash_window;
mod dialogs;
pub mod embed;
pub mod hotkeys;
#[cfg(sk_devtools)]
mod inspector;
pub mod js;
mod json;
mod mapped_file;
#[cfg(feature = "audio")]
mod microphone;
#[cfg(feature = "native-aot")]
mod native_aot;
mod occlusion;
mod owner;
mod payload;
mod perf;
mod popout;
mod popout_win;
#[cfg(feature = "prod")]
mod prod;
mod quiet;
mod reclaim;
mod reload;
#[cfg(all(feature = "webgpu", target_os = "windows"))]
mod shared_gpu;
mod shutdown;
mod slot;
pub mod tray;
mod window;
#[cfg(not(feature = "prod"))]
use dev as boot_mode;
#[cfg(feature = "prod")]
use prod as boot_mode;
const PRELUDE_JS: &str = include_str!("prelude.js");
const WINDOW_PRELUDE_JS: &str = include_str!("window.prelude.js");
thread_local! {
static FRAME_NO: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static FIRST_WAVE_RELEASED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn first_wave_waits(window: &mut Window) -> bool {
if FIRST_WAVE_RELEASED.with(|c| c.get()) {
return false;
}
FIRST_WAVE_RELEASED.with(|c| c.set(true));
window.refresh();
true
}
struct StderrLogger {
directives: Vec<(String, log::LevelFilter)>,
default: log::LevelFilter,
}
fn target_matches(target: &str, prefix: &str) -> bool {
target.len() >= prefix.len()
&& target.starts_with(prefix)
&& (target.len() == prefix.len() || target[prefix.len()..].starts_with("::"))
}
impl StderrLogger {
fn level_for(&self, target: &str) -> log::LevelFilter {
for (prefix, l) in &self.directives {
if target_matches(target, prefix) {
return *l;
}
}
self.default
}
}
impl log::Log for StderrLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= self.level_for(metadata.target())
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let line = format!("[{} {}] {}", record.level(), record.target(), record.args());
eprintln!("{line}");
tee(record.level(), line);
}
fn flush(&self) {}
}
static MAIN_THREAD: std::sync::OnceLock<std::thread::ThreadId> = std::sync::OnceLock::new();
static OFF_THREAD: std::sync::Mutex<Vec<(&'static str, String)>> =
std::sync::Mutex::new(Vec::new());
const OFF_THREAD_CAP: usize = 512;
fn kind_of(level: log::Level) -> &'static str {
match level {
log::Level::Error => "error",
log::Level::Warn => "warn",
_ => "log",
}
}
fn tee(level: log::Level, line: String) {
if !sk_tree::log::is_enabled() {
return;
}
let kind = kind_of(level);
if MAIN_THREAD.get() == Some(&std::thread::current().id()) {
sk_tree::log::record(kind, line);
return;
}
if let Ok(mut queue) = OFF_THREAD.lock() {
if queue.len() >= OFF_THREAD_CAP {
queue.remove(0); }
queue.push((kind, line));
}
}
fn drain_log_tee() {
if !sk_tree::log::is_enabled() {
return;
}
let Ok(mut queue) = OFF_THREAD.try_lock() else {
return;
};
for (kind, line) in queue.drain(..) {
sk_tree::log::record(kind, line);
}
}
fn parse_level(word: &str) -> Option<log::LevelFilter> {
match word.trim().to_ascii_lowercase().as_str() {
"" | "info" | "1" | "true" => Some(log::LevelFilter::Info),
"off" | "0" | "false" => Some(log::LevelFilter::Off),
"error" => Some(log::LevelFilter::Error),
"warn" => Some(log::LevelFilter::Warn),
"debug" => Some(log::LevelFilter::Debug),
"trace" => Some(log::LevelFilter::Trace),
_ => None,
}
}
fn install_logger() {
let _ = MAIN_THREAD.set(std::thread::current().id());
let spec = std::env::var("SK_LOG").unwrap_or_default();
let mut default = log::LevelFilter::Off;
let mut directives: Vec<(String, log::LevelFilter)> = Vec::new();
let mut saw_bare = false;
for part in spec.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
match part.split_once('=') {
Some((target, level)) => match parse_level(level) {
Some(l) => directives.push((target.trim().to_string(), l)),
None => eprintln!("[sk] SK_LOG: {level:?} is not a level — ignoring {part:?}"),
},
None => match parse_level(part) {
Some(l) => {
default = l;
saw_bare = true;
}
None => eprintln!("[sk] SK_LOG={part:?} is not a level — using info"),
},
}
}
if !saw_bare && directives.is_empty() && !spec.is_empty() {
default = log::LevelFilter::Info;
}
directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
let max = directives
.iter()
.map(|(_, l)| *l)
.chain([default])
.max()
.unwrap_or(default);
let logger: &'static StderrLogger = Box::leak(Box::new(StderrLogger {
directives,
default,
}));
if log::set_logger(logger).is_ok() {
log::set_max_level(max);
}
}
#[cfg(test)]
#[test]
fn devtools_are_in_every_build_that_did_not_opt_out() {
assert_eq!(cfg!(sk_devtools), !cfg!(feature = "no-devtools"));
}
#[cfg(test)]
mod logger_tests {
use super::*;
use log::LevelFilter as L;
fn logger(spec: &[(&str, L)], default: L) -> StderrLogger {
let mut directives: Vec<(String, L)> =
spec.iter().map(|(t, l)| ((*t).to_string(), *l)).collect();
directives.sort_by(|a, b| b.0.len().cmp(&a.0.len()));
StderrLogger {
directives,
default,
}
}
#[test]
fn the_longest_matching_directive_wins() {
let l = logger(&[("gpui", L::Warn), ("gpui::window", L::Debug)], L::Off);
assert_eq!(l.level_for("gpui::window"), L::Debug);
assert_eq!(l.level_for("gpui::platform"), L::Warn);
assert_eq!(l.level_for("sk_tree"), L::Off);
}
#[test]
fn target_boundaries_are_module_separators() {
assert!(target_matches("gpui::window", "gpui"));
assert!(target_matches("gpui", "gpui"));
assert!(!target_matches("gpui_windows::events", "gpui"));
}
}
struct Shell;
thread_local! {
static SHELL: RefCell<Option<WeakEntity<Shell>>> = const { RefCell::new(None) };
static MAIN_WINDOW: std::cell::Cell<Option<gpui::AnyWindowHandle>> =
const { std::cell::Cell::new(None) };
}
fn sync_layout() {
let Some(handle) = MAIN_WINDOW.with(|w| w.get()) else {
return;
};
let draw = |window: &mut gpui::Window, cx: &mut gpui::App| {
sk_runtime::bridge::with_draw(|| window.draw(cx).clear(cx))
};
let drew = sk_runtime::bridge::with_app(|cx| {
handle.update(cx, |_, window, cx| draw(window, cx)).is_ok()
});
if drew != Some(false) || sk_tree::in_input_dispatch() {
return;
}
sk_runtime::with_commit(|window, cx| {
if window.window_handle() == handle {
draw(window, cx);
}
});
}
fn commit_boot_tree(runtime: &JsRuntime) {
runtime.ctx().drain_microtasks();
sk_tree::flush_changes();
}
#[cfg(test)]
mod startup_tests {
#[test]
fn boot_microtask_styles_are_computed_before_any_frame_pump() {
sk_runtime::testing::on_js_thread(|| {
sk_runtime::JsRuntime::with(|runtime| {
sk_tree::install(runtime);
runtime.eval(
"globalThis.__startupRoot = __sk_create_root(); \
globalThis.__startupNode = __sk_create_element(__sk_intern('button')); \
__sk_insert(__startupNode, __startupRoot, 0); \
__sk_set_style(__startupNode, __sk_intern('opacity'), '0.25'); \
queueMicrotask(() => __sk_set_style(__startupNode, __sk_intern('opacity'), '0.75'));",
"sk://startup-regression.js",
).expect("queue the mount/load microtask through the native DOM bridge");
super::commit_boot_tree(runtime);
let node = runtime
.ctx()
.global_get("__startupNode")
.unwrap()
.as_number()
.unwrap() as u32;
let styles = sk_tree::devtools::computed_styles(node)
.expect("boot writes must already be cascaded");
let base = &styles.iter().find(|(name, _)| *name == "base").unwrap().1;
assert!(
base.contains("0.75"),
"the first draw must not await pump_frame to cascade boot opacity: {base}"
);
})
});
}
}
const HIDDEN_START_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
fn reveal_if_unreachable(cx: &mut App) {
cx.spawn(async move |cx| {
cx.background_executor().timer(HIDDEN_START_GRACE).await;
let _ = cx.update(|_| {
if shutdown::is_closing() || window::revealed() || sk_desktop::tray::Tray::app_shown() {
return;
}
let line = format!(
"[sk] started hidden, and no tray icon is up after {} s: showing the window so the app can be reached",
HIDDEN_START_GRACE.as_secs()
);
eprintln!("{line}");
sk_tree::log::record("warn", line);
window::request_activate();
});
})
.detach();
}
#[cfg(target_os = "windows")]
fn reveal_startup_window(cx: &mut App, activate: bool) {
let Some(handle) = MAIN_WINDOW.with(|window| window.get()) else {
window::cancel_startup_reveal();
return;
};
cx.spawn(async move |cx| {
if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
window::cancel_startup_reveal();
return;
}
let hwnd = cx.update(|cx| handle.update(cx, |_, window, _| window::capture_hwnd(window)));
let Ok(Some(hwnd)) = hwnd else {
window::cancel_startup_reveal();
return;
};
popout_win::paint_now(hwnd);
if shutdown::is_closing() || sk_runtime::bridge::poisoned() {
window::cancel_startup_reveal();
return;
}
let shown = cx.update(|cx| {
handle.update(cx, |_, window, _| {
window.show_window(
activate,
|| !shutdown::is_closing() && !sk_runtime::bridge::poisoned(),
move |shown| {
window::cancel_startup_reveal();
if shown {
quiet::send_hwnd_to_back(hwnd);
}
if !shown && !shutdown::is_closing() {
eprintln!("[window] the prepared startup window could not be shown");
}
},
)
})
});
if !matches!(shown, Ok(true)) {
window::cancel_startup_reveal();
eprintln!("[window] failed to reveal the prepared startup window");
}
})
.detach();
}
pub(crate) fn main_window_display(cx: &mut App) -> Option<gpui::DisplayId> {
let handle = MAIN_WINDOW.with(|w| w.get())?;
handle
.update(cx, |_, window, cx| window.display(cx).map(|d| d.id()))
.ok()
.flatten()
}
#[cfg(sk_devtools)]
pub(crate) fn main_window_id() -> Option<u64> {
MAIN_WINDOW
.with(|w| w.get())
.map(|h| h.window_id().as_u64())
}
pub(crate) fn refresh_main(cx: &mut App) {
notify_shell(cx);
}
pub(crate) fn notify_shell(cx: &mut App) {
SHELL.with(|s| {
if let Some(shell) = s.borrow().as_ref().and_then(|w| w.upgrade()) {
shell.update(cx, |_, cx| cx.notify());
}
});
}
host_fn!(fn sk_set_status(g, args) {
let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
.unwrap_or_default();
sk_tree::log::set_status(text);
sk_runtime::redjs::api::Value::undefined().0
});
host_fn!(fn sk_perf_mark(g, args) {
let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
.unwrap_or_default();
perf::mark(&text);
sk_runtime::redjs::api::Value::undefined().0
});
host_fn!(fn sk_log(g, args) {
let text = unsafe { sk_runtime::redjs::webapi::util::read_string(g, args.arg(0).0) }
.unwrap_or_default();
sk_tree::log::record("log", text);
sk_runtime::redjs::api::Value::undefined().0
});
fn pump_frame(window: &mut Window, cx: &mut App) {
#[cfg(sk_devtools)]
let _allocation_scope = crate::heapcount::recording::scope("runtime", "frame/pump");
if background::pumped_once() && (window::cloaked() || window::occluded()) {
idle::rearm_paced(window, pump_frame, idle::CLOAKED_INTERVAL);
return;
}
perf::frame();
background::note_frame();
drain_log_tee();
if sk_runtime::bridge::poisoned() {
crash_window::on_poisoned(cx);
return;
}
if first_wave_waits(window) {
idle::rearm_unpaced(window, pump_frame);
return;
}
sk_tree::flush_pending_mouse_move(window, cx);
#[cfg(sk_devtools)]
inspector::poll_frame(cx);
js_wave(window, cx, Wave::Frame);
window::note_painted_frame();
after_wave(window, cx);
#[cfg(sk_devtools)]
if devtools::busy() {
idle::note_moved();
}
idle::rearm(
window,
pump_frame,
window::app_focused(cx) || quiet::never_focus(),
);
perf::pump_done();
sk_tree::update_layout_observers(window, cx);
background::note_frame();
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Wave {
Frame,
Background,
}
pub(crate) fn js_wave(window: &mut Window, cx: &mut App, wave: Wave) {
let focused = window::app_focused(cx) || quiet::never_focus();
with_published(window, cx, Phase::Commit, || {
if wave == Wave::Frame {
let n = FRAME_NO.with(|f| {
let n = f.get().wrapping_add(1);
f.set(n);
n
});
boot_mode::poll_frame(n);
}
reload::pump();
sk_runtime::with_commit(|window, cx| window::pump(window, cx));
sk_runtime::runtime::set_frame_budget_ms(window::frame_budget_ms());
let flags = match wave {
Wave::Frame => PUMP_TIMERS | PUMP_RAF | PUMP_MICROTASKS,
Wave::Background => PUMP_TIMERS | PUMP_MICROTASKS,
};
JsRuntime::with(|rt| {
let pumped = std::time::Instant::now();
let stats = rt.pump(flags);
let elapsed = pumped.elapsed();
if wave == Wave::Frame {
#[cfg_attr(not(feature = "audio"), allow(unused_mut))]
let mut report = idle::Wave::from_stats(&stats, elapsed);
#[cfg(feature = "audio")]
{
report.audio = sk_runtime::redjs::webapi::audio::busy(rt.raw());
}
idle::note_wave(report);
}
#[cfg(sk_devtools)]
devtools::trace::note_js(elapsed.as_secs_f32() * 1000.0);
for err in rt.drain_errors() {
eprintln!("[js uncaught] {}\n{}", err.header, err.stack);
sk_tree::log::record(
"error",
format!("[js uncaught] {}\n{}", err.header, err.stack),
);
}
reclaim::after_wave(
rt,
focused,
wave == Wave::Background || window::page_hidden(),
);
});
#[cfg(sk_devtools)]
{
devtools::pump();
}
js::frame();
sk_permissions::pump();
sk_desktop::pump();
embed::pump();
#[cfg(feature = "storages")]
sk_storage::pump();
});
}
pub(crate) fn after_wave(window: &mut Window, cx: &mut App) {
publish_video_device();
let media_moved = sk_tree::frame_tick(window, cx);
let flush = sk_tree::flush_changes_kind();
let tree_moved = flush != sk_tree::Flush::Unchanged;
#[cfg(sk_devtools)]
if tree_moved {
devtools::ws::note_tree_changed();
}
let animating = sk_tree::animating() && !window::page_hidden();
let moving = animating || media_moved;
if flush == sk_tree::Flush::DrawnBySync {
sk_tree::perf::note_sync_tail(!moving);
}
if flush == sk_tree::Flush::Changed || moving {
notify_shell(cx);
}
if tree_moved || moving {
if tree_moved || media_moved {
idle::note_moved();
} else {
idle::note_animating();
}
popout::notify_all(cx);
}
#[cfg(sk_devtools)]
devtools::ws::broadcast_frame();
}
impl Render for Shell {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(sk_devtools)]
let _allocation_scope = crate::heapcount::recording::scope("render", "frame/build");
perf::render_begin();
let el = self.render_body(window, cx);
perf::render_done();
el
}
}
impl Shell {
fn render_body(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Div {
let shell = div()
.relative()
.flex()
.flex_col()
.size_full()
.text_color(gpui::white())
.font_family(".SystemUIFont");
#[cfg(not(target_os = "windows"))]
let shell = chrome_posix::wrap(shell, window, true);
let shell = match window::opaque_fill(window::backdrop(), window::effective_dark(window)) {
Some(fill) => shell.bg(fill),
None => shell,
};
if !window::fallback_titlebar() {
return shell
.child(sk_tree::build_root(window, cx))
.children(sk_tree::build_view_transition())
.children(window_controls_overlay(window))
.children(inspector_overlay());
}
shell
.child(
div()
.id("titlebar")
.window_control_area(WindowControlArea::Drag)
.h(px(window::title_bar_height()))
.overflow_hidden()
.px(px(14.))
.flex()
.items_center()
.text_size(px(13.))
.child(window::title()),
)
.child(
div()
.flex_1()
.min_h(px(0.))
.child(sk_tree::build_root(window, cx)),
)
.children(sk_tree::build_view_transition())
.children(window_controls_overlay(window))
.children(inspector_overlay())
}
}
fn inspector_overlay() -> Option<gpui::Div> {
#[cfg(sk_devtools)]
{
devtools::highlight_overlay()
}
#[cfg(not(sk_devtools))]
{
None
}
}
fn window_controls_overlay(window: &Window) -> Option<gpui::Div> {
let (height, overlay) = window::overlay()?;
let dark = window::effective_dark(window);
const MIN: &str = "\u{e921}";
const MAX: &str = "\u{e922}";
const CLOSE: &str = "\u{e8bb}";
let glyph_font = gpui::Font {
family: "Segoe Fluent Icons".into(),
fallbacks: Some(gpui::FontFallbacks::from_fonts(vec![
"Segoe MDL2 Assets".to_string(),
"Segoe UI Symbol".to_string(),
])),
features: Default::default(),
weight: Default::default(),
style: Default::default(),
};
let symbol = overlay
.symbol_color
.map(rgba)
.unwrap_or_else(|| rgba(if dark { 0xffffffe0 } else { 0x000000e0 }));
let hover = if dark { 0xffffff1a } else { 0x0000000f };
let button = |id: &'static str, glyph: &'static str, area: WindowControlArea, hover: u32| {
div()
.id(id)
.w(px(window::OVERLAY_BUTTON_WIDTH))
.h(px(height))
.flex()
.items_center()
.justify_center()
.text_size(px(10.))
.text_color(symbol)
.font(glyph_font.clone())
.window_control_area(area)
.hover(|s| s.bg(rgba(hover)))
.child(glyph)
};
let mut strip = div()
.absolute()
.top_0()
.right_0()
.h(px(height))
.flex()
.flex_row();
if let Some(bg) = overlay.color {
strip = strip.bg(rgba(bg));
}
Some(
strip
.child(button("wco-min", MIN, WindowControlArea::Min, hover))
.child(button("wco-max", MAX, WindowControlArea::Max, hover))
.child(button(
"wco-close",
CLOSE,
WindowControlArea::Close,
0xc42b1cff,
)),
)
}
fn publish_app_root() {
#[cfg(feature = "prod")]
if prod::publish_asset_store() {
return;
}
if let Some(dir) = std::env::var_os("SK_APP_ROOT") {
if !dir.is_empty() {
sk_tree::set_asset_base(std::path::PathBuf::from(dir));
}
}
}
fn install_iframe_backend() {
#[cfg(feature = "storages")]
let data = embed::data_dir()
.map(std::path::Path::to_path_buf)
.or_else(|| {
sk_storage::default_folder(boot_mode::app_name().as_deref())
.parent()
.map(std::path::Path::to_path_buf)
});
#[cfg(not(feature = "storages"))]
let data: Option<std::path::PathBuf> = None;
let user_data = data
.unwrap_or_else(|| std::env::temp_dir().join("skathi"))
.join("webview");
let config = sk_webview::Config {
assets: std::rc::Rc::new(|path| sk_tree::read_app_asset(path)),
user_data,
page_origin: "app://redjs".into(),
devtools: !cfg!(feature = "prod"),
};
if let Some(backend) = sk_webview::backend(config) {
sk_tree::iframe::set_backend(backend, std::rc::Rc::new(sk_runtime::frames::wake));
}
}
fn close_iframes_on_quit(cx: &mut App) {
std::mem::forget(cx.on_app_quit(|_| {
sk_tree::iframe::shutdown();
std::future::ready(())
}));
}
#[cfg(target_os = "windows")]
fn publish_video_device() {
use std::cell::Cell;
#[cfg(feature = "native-dx12")]
{
static INSTALL: std::sync::Once = std::sync::Once::new();
INSTALL.call_once(|| {
fn provide() -> Result<Option<sk_tree::SharedVideoDevice>, String> {
gpui_windows::ensure_renderer_d3d11_device()
.map(|lease| {
lease.map(|lease| sk_tree::SharedVideoDevice {
device: lease.device,
generation: lease.generation,
keep_alive: lease.keep_alive,
})
})
.map_err(|error| {
format!("Could not initialize renderer video bridge: {error:#}")
})
}
if let Err(error) = unsafe { sk_tree::install_video_device_provider(provide) } {
log::error!("Could not install lazy video device provider: {error}");
}
});
}
thread_local! {
static PUBLISHED: Cell<u64> = const { Cell::new(0) };
}
let (ptr, generation) = gpui_windows::renderer_d3d11_device();
let previous = PUBLISHED.with(Cell::get);
if generation == 0 || previous == generation || (ptr.is_null() && previous == 0) {
return;
}
let first = previous == 0;
PUBLISHED.with(|p| p.set(generation));
unsafe { sk_tree::set_video_device(ptr, generation) };
if first {
return;
}
let rebuilt = sk_tree::video_device_changed();
let msg = format!(
"[video] the renderer recreated its D3D11 device (generation {generation}) — rebuilt \
{rebuilt} <video> element(s) on it, resuming where they were"
);
eprintln!("{msg}");
sk_tree::log::record("window", msg);
}
#[cfg(not(target_os = "windows"))]
fn publish_video_device() {}
fn install_http_client(app: gpui::Application) -> gpui::Application {
app.with_http_client(std::sync::Arc::new(http_client::RedjsHttpClient::new()))
}
pub fn run_exe() {
owner::watch();
let args = sk_desktop::args::process();
if args.host.host_info && !payload::embedded_present() {
println!("{}", payload::host_info_json());
return;
}
if let Some(dist) = args.host.sk_dist.as_deref().filter(|d| !d.is_empty()) {
std::env::set_var("SK_DIST", dist);
}
{
let launch_cfg = if args.host.devtools {
None
} else {
boot_mode::launch_config()
};
#[cfg(not(feature = "prod"))]
let dev_slot = Some(slot::dir());
#[cfg(feature = "prod")]
let dev_slot = None;
let build_name = if args.host.devtools {
None
} else {
boot_mode::app_name()
};
if let sk_desktop::launch::Outcome::Exit(code) =
sk_desktop::launch::start(args, launch_cfg.as_deref(), build_name, dev_slot)
{
std::process::exit(code);
}
if !args.host.devtools {
sk_desktop::launch::register_declared();
}
}
#[cfg(sk_devtools)]
inspector::init();
#[cfg(feature = "prod")]
{
#[cfg(sk_devtools)]
let inspecting = inspector::is_devtools_host();
#[cfg(not(sk_devtools))]
let inspecting = false;
if !inspecting {
prod::require_payload();
}
}
run_app();
shutdown::finish();
}
pub(crate) fn run_embedded() {
let args = sk_desktop::args::process();
if !embed::desktop_launch_prepared() {
let _ = sk_desktop::launch::start(args, None, boot_mode::app_name(), None);
}
run_app();
shutdown::finish();
}
fn run_app() {
install_logger();
#[cfg(all(feature = "webgpu", target_os = "windows"))]
shared_gpu::install().expect("installing shared graphics device provider");
perf::boot();
#[cfg(sk_devtools)]
if heapcount::on() {
sk_tree::perf::set_live_bytes_probe(|| heapcount::snapshot().map(|s| s.0));
sk_tree::devtools::set_image_tracking(true);
}
let app = install_http_client(application()).with_quit_mode(gpui::QuitMode::LastWindowClosed);
#[cfg(target_os = "macos")]
app.on_reopen(|_| embed::reopen());
#[cfg(feature = "prod")]
let app = if payload::get().is_some() {
payload::install_effects();
app.with_assets(payload::GpuiAssets)
} else {
app
};
app.run(|cx: &mut App| {
#[cfg(sk_devtools)]
let devtools_mode = inspector::is_devtools_host();
#[cfg(not(sk_devtools))]
let devtools_mode = false;
sk_elements::init(cx);
publish_app_root();
std::mem::forget(cx.on_app_quit(|_| {
window::cancel_startup_reveal();
shutdown::begin("quit");
window::page_hide();
std::future::ready(())
}));
std::mem::forget(cx.on_app_quit(|_| {
JsRuntime::try_with(|runtime| js::shutdown(runtime.ctx()));
std::future::ready(())
}));
close_iframes_on_quit(cx);
std::mem::forget(cx.intercept_keystrokes(sk_tree::pointer_lock_intercept_escape));
#[cfg(sk_devtools)]
{
inspector::install_hotkey(cx);
std::mem::forget(cx.on_app_quit(|_| {
shutdown::step("inspector", inspector::close_children);
std::future::ready(())
}));
}
#[cfg(feature = "storages")]
std::mem::forget(cx.on_app_quit(|_| {
shutdown::step("storage", || {
if let Err(e) = sk_storage::flush() {
eprintln!("[storage] localStorage: the last change was not written: {e}");
}
if let Err(e) = sk_storage::cookies::flush() {
eprintln!("[storage] cookies: the last change was not written: {e}");
}
});
shutdown::step("http-cache", sk_runtime::redjs::webapi::http::cache::uninstall);
std::future::ready(())
}));
#[cfg(feature = "indexeddb")]
std::mem::forget(cx.on_app_quit(|_| {
let t = std::time::Instant::now();
let done = shutdown::step("indexeddb", || sk_runtime::redjs::ffi::redjs_idb_shutdown(2_000));
if done == 0 {
eprintln!(
"[sk] IndexedDB did not finish closing within {} ms; the next start recovers from its WAL",
t.elapsed().as_millis()
);
}
std::future::ready(())
}));
shutdown::install_test_delay(cx);
#[cfg(sk_devtools)]
devtools::arm();
#[cfg(sk_devtools)]
let window_json =
if devtools_mode { inspector::window_config() } else { boot_mode::window_config() };
#[cfg(not(sk_devtools))]
let window_json = boot_mode::window_config();
#[cfg(feature = "storages")]
let http_cache_mb = http_client::cache_mb(window_json.as_deref());
let cfg = window::load_config(window_json);
#[cfg(sk_devtools)]
devtools::boot(window::devtools_config_enabled());
sk_desktop::network::install();
#[cfg(all(sk_devtools, not(feature = "native-aot")))]
if let Some(summary) = devtools_mode.then(|| inspector::engine_without_native(
std::env::var_os("SK_DEVTOOLS_ENGINE").as_deref(),
std::env::var_os("SK_DEVTOOLS_NATIVE_IMAGE").is_some(),
).err()).flatten() {
eprintln!("[native-aot] {summary}");
embed::finished(false, summary);
cx.quit();
return;
}
#[cfg(feature = "native-aot")]
if let Err(error) = native_aot::prepare(devtools_mode) {
let summary = if devtools_mode {
format!("native inspector preparation failed: {error}")
} else {
format!(
"this app's native image cannot run on this host ({error}). \
Rebuild the app with `sk build --aot` from the sk that matches this host."
)
};
eprintln!("[native-aot] {summary}");
let embedded =
payload::get().is_some_and(|l| matches!(l.source, payload::Source::Embedder(_)));
if !devtools_mode && !embedded {
payload::message_box(&summary);
std::process::exit(3);
}
embed::finished(false, summary);
cx.quit();
return;
}
JsRuntime::init();
#[cfg(target_os = "windows")]
consent_window::install(cx);
let setup_result = JsRuntime::with(|rt| -> Result<(), String> {
rt.register("__sk_set_status", 1, sk_set_status as *const _);
rt.register("__sk_log", 1, sk_log as *const _);
rt.register("__sk_perf_mark", 1, sk_perf_mark as *const _);
reload::install(rt);
sk_tree::install(rt);
window::install(rt);
popout::install(rt);
#[cfg(feature = "audio")]
microphone::install();
#[cfg(feature = "clipboard")]
sk_clipboard::install();
sk_permissions::install(rt);
sk_locale::install(rt);
if !devtools_mode {
install_iframe_backend();
}
sk_desktop::set_log_sink(|kind, text| sk_tree::log::record(kind, text));
sk_desktop::install(rt);
sk_desktop::dialog::set_owner_resolver(dialogs::owner);
sk_permissions::set_asker(dialogs::ask_permission);
sk_permissions::set_app_name(&cfg.title);
crash_window::set_app_name(&cfg.title);
#[cfg(feature = "storages")]
if !devtools_mode {
let encrypted = embed::storage_encrypted();
if embed::data_dir().is_some() || encrypted.is_some() {
let directory = embed::data_dir().map(std::path::Path::to_path_buf)
.unwrap_or_else(|| sk_storage::default_folder(boot_mode::app_name().as_deref()));
sk_storage::set_storage_folder(&directory, encrypted)?;
if encrypted == Some(true) {
sk_storage::encrypt_local_storage_at(&directory)?;
}
}
}
#[cfg(feature = "storages")]
sk_storage::install(
rt,
if devtools_mode { Some("sk-devtools".to_string()) } else { boot_mode::app_name() },
);
#[cfg(feature = "storages")]
if !devtools_mode {
if let Some(directory) = embed::data_dir() {
sk_storage::http_cache::install_at(http_cache_mb, directory.join("cache").join("http"));
} else {
sk_storage::http_cache::install(http_cache_mb);
}
}
#[cfg(feature = "storages")]
sk_permissions::set_decisions_file(sk_storage::cookies::folder().map(|f| f.join("permissions.json")));
if !devtools_mode {
tray::install(rt)?;
hotkeys::install(rt)?;
embed::setup(rt)?;
}
#[cfg(sk_devtools)]
devtools::install(rt);
embed::install(rt);
unsafe { sk_runtime::standins::install_missing(rt.raw()) };
Ok(())
});
if let Err(error) = setup_result {
let summary = format!("host setup failed: {error}");
eprintln!("[embed] {summary}");
embed::finished(false, summary);
cx.quit();
return;
}
let bounds = Bounds::centered(None, size(px(cfg.width), px(cfg.height)), cx);
let startup_visible = embed::visible();
let startup_focus = !devtools_mode && !quiet::never_focus() && embed::activates();
let defer_reveal = cfg!(target_os = "windows") && startup_visible;
if defer_reveal {
window::begin_startup_reveal();
}
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_background: cfg.backdrop.to_gpui(),
titlebar: Some(TitlebarOptions {
title: Some(cfg.title.clone().into()),
appears_transparent: cfg.title_bar_style == window::TitleBarStyle::Hidden,
traffic_light_position: window::traffic_light_position(
cfg.title_bar_style == window::TitleBarStyle::Hidden,
cfg.title_bar_height,
),
..Default::default()
}),
is_resizable: cfg.resizable,
is_minimizable: cfg.minimizable,
app_owns_titlebar_drag: cfg.title_bar_style == window::TitleBarStyle::Hidden,
window_min_size: match (cfg.min_width, cfg.min_height) {
(None, None) => None,
(w, h) => Some(size(px(w.unwrap_or(0.0)), px(h.unwrap_or(0.0)))),
},
inactive_frame_interval: None,
show: startup_visible && !defer_reveal,
focus: startup_focus,
#[cfg(target_os = "linux")]
window_decorations: Some(gpui::WindowDecorations::Client),
#[cfg(target_os = "linux")]
app_id: embed::desktop_id().or_else(|| sk_desktop::launch::identity().map(|i| i.id.clone())),
..Default::default()
},
|window, cx| {
if std::env::var_os("SK_RETAINED_LAYOUT").as_deref() != Some(std::ffi::OsStr::new("0")) {
window.vn_enable_retained_layout();
}
quiet::send_to_back(window);
publish_video_device();
let shell = cx.new(|_| Shell);
SHELL.with(|s| *s.borrow_mut() = Some(shell.downgrade()));
window::init(&cfg, window, cx);
if let Some(hwnd) = window::capture_hwnd(window) {
sk_desktop::launch::set_window(hwnd);
}
window.on_window_should_close(cx, |window, cx| {
let closing = window::should_close();
if closing {
window::cancel_startup_reveal();
shutdown::begin("a close request (WM_CLOSE)");
}
if closing && popout::count() > 0 {
sk_tree::log::record(
"window",
format!(
"[window] the primary window is closing — taking {} pop-out(s) \
with it",
popout::count()
),
);
popout::close_all(cx);
}
closing && dialogs::may_close_now(window.window_handle(), cx)
});
window.on_next_frame(pump_frame);
shell
},
)
.map(|handle| MAIN_WINDOW.with(|w| w.set(Some(handle.into()))))
.unwrap();
background::start(cx);
#[cfg(target_os = "windows")]
sk_runtime::frames::set_waker(gpui_windows::wake_frames);
sk_tree::set_sync_layout(sync_layout);
let text_system = cx.text_system().clone();
sk_css::set_font_source(move || text_system.all_font_names());
let metric_system = cx.text_system().clone();
let metric_text = RefCell::new((0usize, gpui::WindowTextSystem::new(metric_system.clone())));
sk_css::set_font_metric_source(move |font, size| {
let mut cache = metric_text.borrow_mut();
let (queries, text) = &mut *cache;
if *queries >= 128 {
*text = gpui::WindowTextSystem::new(metric_system.clone());
*queries = 0;
}
*queries += 1;
let run = gpui::TextRun { len: 1, font: font.clone(), color: gpui::black(), ..Default::default() };
let lines = text.shape_text("0".into(), gpui::px(size), &[run], None, None).ok()?;
let line = lines.first()?;
let font_id = line.runs().first()?.font_id;
Some(sk_css::FontRelativeMetrics {
zero_advance: f32::from(line.size(gpui::px(size)).width),
x_height: f32::from(text.x_height(font_id, gpui::px(size))),
})
});
#[cfg(sk_devtools)]
let mut startup_error: Option<String> = None;
with_published_app(cx, || {
JsRuntime::with(|rt| {
if let Err(e) = perf::boot_eval("preludes", || rt.eval(PRELUDE_JS, "sk://prelude.js")) {
eprintln!("[js boot] {}\n{}", e.header, e.stack);
#[cfg(all(sk_devtools, feature = "native-aot"))]
if devtools_mode && sk_runtime::redjs::aot::is_active() {
startup_error = Some(format!("native inspector prelude failed: {}", e.header));
return;
}
}
if let Err(e) = perf::boot_eval("preludes", || rt.eval(WINDOW_PRELUDE_JS, "sk://window.js")) {
eprintln!("[js boot] {}\n{}", e.header, e.stack);
#[cfg(all(sk_devtools, feature = "native-aot"))]
if devtools_mode && sk_runtime::redjs::aot::is_active() {
startup_error = Some(format!("native inspector prelude failed: {}", e.header));
return;
}
}
let scenario = std::env::var("SK_SCENARIO").unwrap_or_default();
if !scenario.is_empty() {
let safe: String = scenario
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
.collect();
let js = format!("globalThis.__SK_SCENARIO__ = \"{safe}\";");
if let Err(e) = rt.eval(&js, "sk://scenario.js") {
eprintln!("[js boot] {}\n{}", e.header, e.stack);
}
}
#[cfg(sk_devtools)]
if devtools_mode {
if let Err(error) = inspector::boot(rt) {
startup_error = Some(error);
return;
}
} else {
boot_mode::boot(rt);
}
#[cfg(not(sk_devtools))]
boot_mode::boot(rt);
window::content_loaded();
commit_boot_tree(rt);
});
});
#[cfg(sk_devtools)]
if let Some(error) = startup_error {
let summary = format!("inspector startup failed: {error}");
eprintln!("[native-aot] {summary}");
embed::finished(false, summary);
window::cancel_startup_reveal();
cx.quit();
return;
}
refresh_main(cx);
#[cfg(target_os = "windows")]
if defer_reveal {
reveal_startup_window(cx, startup_focus);
}
if !embed::visible() {
background::note_frame();
reveal_if_unreachable(cx);
}
if !devtools_mode && !quiet::never_focus() && embed::activates() {
cx.activate(true);
}
#[cfg(sk_devtools)]
if devtools_mode {
inspector::watch_parent();
}
});
}