diff --git a/README.md b/README.md index 8980781..034df1d 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,7 @@ statement checks its caller. routes helper-window closes (Windows), follows window resizes natively and adds the shell webview (transparent: it can rise above the tabs; macOS needs the `macos-private-api` feature). It serves `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `open_external_url`, - `shell_focus`, `shell_raise`, `window_system_menu`, `profiles_get`/`profiles_set`, + `shell_focus`, `shell_ready`, `tab_still_ready`, `shell_raise`, `window_system_menu`, `profiles_get`/`profiles_set`, `i18n_get`/`i18n_set`) and `commands::TAB` (`tab_shortcut`, `tab_link_drag`), each checking its caller first, and dispatches every other command to the app's handler. Tab webviews get their profile's data folder, the app's document-start scripts, navigation/pop-up/load/title/download @@ -298,6 +298,10 @@ statement checks its caller. scripts, legacy domains, link routing, per-tab state, what a finished site page gets). Helpers: `profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`, `open_external`. + To show the first window only after restored panes are placed, opt in on both sides: + `AppConfig::defer_window_show = true` and `ShellSite.deferWindowShow = true`, and grant the + shell `allow-shell-ready`. The default still shows the window immediately. An opted-in app + shows it after initial `tabs_sync`, with a three-second fallback if shell startup fails. - `commands`: the host's command list and `manifest(&[..])` for the app's `build.rs`. - `testkit`: see the capabilities section. - `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs index b0b5a2b..eb151e3 100644 --- a/crates/waybetter-host/src/app.rs +++ b/crates/waybetter-host/src/app.rs @@ -52,6 +52,8 @@ pub struct AppConfig { pub min_window_size: (f64, f64), /// The window's color before the shell paints (no white flash). pub background: (u8, u8, u8), + /// Wait for the shell's `shell_ready` command before showing the first window. + pub defer_window_show: bool, /// The shell draws the titlebar (Windows/Linux: frameless; macOS: an overlay titlebar with the /// traffic lights over the shell). Off: the OS frame, for a shell without one. pub custom_titlebar: bool, @@ -74,6 +76,7 @@ impl AppConfig { window_size: (1360.0, 900.0), min_window_size: (900.0, 560.0), background: (7, 8, 12), + defer_window_show: false, custom_titlebar: true, deep_link: false, updater: false, @@ -319,8 +322,8 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec, view // and the app's per-tab state goes with the old one. let existing = match existing { Some(tab) if current_profile.as_deref() != Some(item.profile.as_str()) => { + host::forget_tab(&app, &label); let _ = tab.close(); - host::forget_tab(&label); profiles(&app)?.tab_profiles.remove(&label); hooks.tab_closed(&app, &label, TabClosed::Replaced); None @@ -383,8 +386,8 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec, view if let Some(id) = policy::tab_id(existing.label()) { if !keep.contains(id) { let label = existing.label().to_owned(); + host::forget_tab(&app, &label); let _ = existing.close(); - host::forget_tab(&label); if let Ok(mut data) = profiles(&app) { data.tab_profiles.remove(&label); } @@ -423,6 +426,25 @@ async fn shell_focus(webview: Webview) -> Result<(), String> { webview.set_focus().map_err(|error| format!("FOCUS: {error}")) } +/// The shell calls this after its first DOM commit, so startup never exposes an empty webview. +#[tauri::command] +async fn shell_ready(webview: Webview, app: AppHandle) -> Result<(), String> { + shell_only(&webview)?; + app.get_window(policy::MAIN_LABEL) + .ok_or("WINDOW: main window missing")? + .show() + .map_err(|error| format!("WINDOW: {error}")) +} + +/// The shell has committed a captured tab frame; its native webview can now be hidden. +#[tauri::command] +async fn tab_still_ready(webview: Webview, app: AppHandle, id: String, token: u64) -> Result<(), String> { + shell_only(&webview)?; + if !policy::valid_tab_id(&id) { return Err("VALIDATION: invalid tab id".into()); } + host::acknowledge_still(&app, &id, token); + Ok(()) +} + /// Raises the shell above the tab webviews while one of its overlays (menu, dialog, palette, /// drag) is open, so the panes stay on screen under it, or lowers it again. Returns whether this /// platform can; when not, the shell hides the tabs for the overlay instead. @@ -701,6 +723,8 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's tab_action, open_external_url, shell_focus, + shell_ready, + tab_still_ready, shell_raise, window_system_menu, profiles_get, @@ -864,6 +888,18 @@ fn open_window(app: &mut tauri::App, config: &AppConfig) -> Result<(), Box< let shell = shell.transparent(true); let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?; host::attach_shell(&shell); - window.show()?; + if config.defer_window_show { + // A shell that opts in shows the window after initial layout and sync. If JS fails to + // start, make the failure visible rather than leaving a hidden process. + let fallback = window.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(3)); + if fallback.is_visible().is_ok_and(|visible| !visible) { + let _ = fallback.show(); + } + }); + } else { + window.show()?; + } Ok(()) } diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs index c2d5cc8..263f656 100644 --- a/crates/waybetter-host/src/commands.rs +++ b/crates/waybetter-host/src/commands.rs @@ -12,6 +12,8 @@ pub const SHELL: &[&str] = &[ "tab_action", "open_external_url", "shell_focus", + "shell_ready", + "tab_still_ready", "shell_raise", "window_system_menu", "profiles_get", diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs index fb85dd3..a070b88 100644 --- a/crates/waybetter-host/src/host.rs +++ b/crates/waybetter-host/src/host.rs @@ -461,6 +461,12 @@ mod linux { /// The event carrying a tab's last frame to the shell ([`capture_still`]). pub const EVENT_TAB_STILL: &str = "tab-still"; +#[cfg(windows)] +const EVENT_TAB_STILL_START: &str = "tab-still-start"; +#[cfg(windows)] +const EVENT_TAB_STILL_CANCEL: &str = "tab-still-cancel"; +#[cfg(windows)] +const EVENT_TAB_STILL_RESET: &str = "tab-still-reset"; #[cfg(windows)] #[derive(Clone, Serialize)] @@ -468,18 +474,114 @@ struct TabStill { id: String, /// `data:image/jpeg;base64,…` image: String, + token: u64, } +#[cfg(windows)] +#[derive(Clone, Serialize)] +struct TabStillToken { id: String, token: u64 } + +#[cfg(windows)] +#[derive(Clone, Copy, PartialEq, Eq)] +enum StillPhase { Pending, Hidden } + +#[cfg(windows)] +#[derive(Clone, Copy)] +struct StillEntry { token: u64, phase: StillPhase } + +#[cfg(windows)] +impl StillEntry { + fn accepts(self, token: u64) -> bool { self.token == token } + fn hide(&mut self, token: u64) -> bool { + if !self.accepts(token) || self.phase != StillPhase::Pending { return false; } + self.phase = StillPhase::Hidden; + true + } +} + +#[cfg(all(test, windows))] +mod still_tests { + use super::{cancel_pending_still, pending_stills, StillEntry, StillPhase}; + + #[test] + fn timeout_keeps_late_frame_valid_but_stale_tokens_cannot_hide() { + let mut entry = StillEntry { token: 7, phase: StillPhase::Pending }; + assert!(!entry.hide(6)); + assert!(entry.hide(7)); + assert!(entry.accepts(7)); // CapturePreview may finish after the bounded hide. + assert!(!entry.hide(7)); // A late acknowledgement must not hide a shown tab again. + entry = StillEntry { token: 8, phase: StillPhase::Pending }; + assert!(!entry.accepts(7)); + assert!(!entry.hide(7)); + } + + #[test] + fn teardown_invalidates_old_capture_before_same_label_is_reused() { + let label = "tab-still-test-recreated"; + pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 31, phase: StillPhase::Hidden }); + assert_eq!(cancel_pending_still(label), Some(31)); + pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 32, phase: StillPhase::Pending }); + let current = pending_stills().lock().unwrap().get(label).copied().unwrap(); + assert!(!current.accepts(31)); + assert!(current.accepts(32)); + cancel_pending_still(label); + } +} + +#[cfg(windows)] +fn pending_stills() -> &'static std::sync::Mutex> { + use std::sync::{Mutex, OnceLock}; + static PENDING: OnceLock>> = OnceLock::new(); + PENDING.get_or_init(Default::default) +} + +#[cfg(windows)] +fn cancel_pending_still(label: &str) -> Option { + pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(label).map(|entry| entry.token) +} + +#[cfg(windows)] +fn hide_after_still(app: &AppHandle, label: &str, token: u64) { + let app = app.clone(); + let label = label.to_owned(); + let dispatcher = app.clone(); + // Webview::show/hide both execute on Tauri's main thread. Check the token there, directly + // before hiding, so a queued hide cannot run after a newer show canceled this capture. + let _ = dispatcher.run_on_main_thread(move || { + let current = { + let mut pending = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + pending.get_mut(&label).is_some_and(|entry| entry.hide(token)) + }; + if current { + if let Some(tab) = app.get_webview(&label) { let _ = tab.hide(); } + } + }); +} + +/// The shell has painted a captured frame; complete the bounded overlay handoff. +#[cfg(windows)] +pub fn acknowledge_still(app: &AppHandle, id: &str, token: u64) { + if policy::valid_tab_id(id) { + hide_after_still(app, &policy::tab_label(id), token); + } +} + +#[cfg(not(windows))] +pub fn acknowledge_still(_app: &AppHandle, _id: &str, _token: u64) {} + /// Windows: a tab webview about to be hidden hands the shell its last frame (WebView2 /// `CapturePreview`, JPEG) as [`EVENT_TAB_STILL`], which its pane shows while no webview is on /// screen there. Only a webview that is on screen now; requested before the hide, on the same /// thread, so the frame is still there. Kept in the shell's memory only. No-op elsewhere. -fn capture_still(webview: &Webview) { +fn capture_still(webview: &Webview, token: u64) { #[cfg(windows)] { let Some(id) = policy::tab_id(webview.label()).map(str::to_owned) else { return }; + let label = webview.label().to_owned(); let app = webview.app_handle().clone(); - let _ = webview.with_webview(move |platform| { + let fallback = app.clone(); + let fallback_label = label.clone(); + let result = webview.with_webview(move |platform| { use base64::Engine; use webview2_com::CapturePreviewCompletedHandler; use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG; @@ -491,41 +593,82 @@ fn capture_still(webview: &Webview) { let controller = platform.controller(); let mut shown = windows::core::BOOL::default(); if controller.IsVisible(&mut shown).is_err() || !shown.as_bool() { + hide_after_still(&app, &label, token); return; } - let (Ok(core), Some(stream)) = (controller.CoreWebView2(), SHCreateMemStream(None)) else { return }; + let (Ok(core), Some(stream)) = (controller.CoreWebView2(), SHCreateMemStream(None)) else { + hide_after_still(&app, &label, token); + return; + }; let target = stream.clone(); + let callback_app = app.clone(); + let callback_label = label.clone(); let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| { - result?; - let mut size = 0u64; - target.Seek(0, STREAM_SEEK_END, Some(&mut size))?; - if size == 0 || size > 16 << 20 { - return Ok(()); + let image = (|| { + result.ok()?; + let mut size = 0u64; + target.Seek(0, STREAM_SEEK_END, Some(&mut size)).ok()?; + if size == 0 || size > 16 << 20 { return None; } + target.Seek(0, STREAM_SEEK_SET, None).ok()?; + let mut bytes = vec![0u8; size as usize]; + let mut read = 0u32; + target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok().ok()?; + bytes.truncate(read as usize); + Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))) + })(); + if let Some(image) = image { + let current = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(&callback_label).is_some_and(|entry| entry.accepts(token)); + if current { + emit_shell(&callback_app, EVENT_TAB_STILL, TabStill { id, image, token }); + } + } else { + hide_after_still(&callback_app, &callback_label, token); } - target.Seek(0, STREAM_SEEK_SET, None)?; - let mut bytes = vec![0u8; size as usize]; - let mut read = 0u32; - target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok()?; - bytes.truncate(read as usize); - let image = format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)); - emit_shell(&app, EVENT_TAB_STILL, TabStill { id, image }); Ok(()) })); - let _ = core.CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG, &stream, &handler); + if core.CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG, &stream, &handler).is_err() { + hide_after_still(&app, &label, token); + } } }); + if result.is_err() { + hide_after_still(&fallback, &fallback_label, token); + } } #[cfg(not(windows))] - let _ = webview; + let _ = (webview, token); } /// Shows or hides a tab webview and sets its WebView2 memory target to match /// ([`tabs::memory_target`]): hidden tabs run at `COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW` /// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only /// show/hide. -pub fn set_tab_visible(webview: &Webview, visible: bool, parked: bool) { - if !visible { - capture_still(webview); +pub fn set_tab_visible(webview: &Webview, visible: bool, parked: bool, was_visible: bool) { + #[cfg(windows)] + { + let app = webview.app_handle(); + let id = policy::tab_id(webview.label()).unwrap_or_default().to_owned(); + if let Some(token) = cancel_pending_still(webview.label()) { + emit_shell(app, EVENT_TAB_STILL_CANCEL, TabStillToken { id: id.clone(), token }); + } + if !visible && !parked && was_visible && webview.window().is_visible().unwrap_or(false) { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + let token = NEXT.fetch_add(1, Ordering::Relaxed); + let label = webview.label().to_owned(); + pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(label.clone(), StillEntry { token, phase: StillPhase::Pending }); + emit_shell(app, EVENT_TAB_STILL_START, TabStillToken { id, token }); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(160)).await; + hide_after_still(&app, &label, token); + }); + capture_still(webview, token); + set_memory_target(webview, visible, parked); + return; + } } let _ = if visible { webview.show() } else { webview.hide() }; set_memory_target(webview, visible, parked); @@ -577,20 +720,33 @@ fn placements() -> std::sync::MutexGuard<'static, crate::layout::Placements> { /// native calls for whatever did not change since its last placement: a sync that moves one pane /// touches one webview, and one that changes nothing costs nothing. pub fn place_tab(webview: &Webview, rect: crate::layout::Rect, visible: bool, parked: bool) { - let changed = placements().place(webview.label(), rect, visible); + let (changed, was_visible) = { + let mut placed = placements(); + let was_visible = placed.was_visible(webview.label()); + (placed.place(webview.label(), rect, visible), was_visible) + }; if changed.bounds { let (x, y, width, height) = rect; place_child(webview, x, y, width, height); } if changed.visible { - set_tab_visible(webview, visible, parked); + set_tab_visible(webview, visible, parked, was_visible); } else { set_memory_target(webview, visible, parked); } } /// A tab webview was closed: a new one with the same label is placed from scratch. -pub fn forget_tab(label: &str) { +pub fn forget_tab(app: &AppHandle, label: &str) { + #[cfg(windows)] + { + cancel_pending_still(label); + if let Some(id) = policy::tab_id(label) { + emit_shell(app, EVENT_TAB_STILL_RESET, id.to_owned()); + } + } + #[cfg(not(windows))] + let _ = app; placements().forget(label); } diff --git a/crates/waybetter-host/src/layout.rs b/crates/waybetter-host/src/layout.rs index 98c61a0..7e1ef7f 100644 --- a/crates/waybetter-host/src/layout.rs +++ b/crates/waybetter-host/src/layout.rs @@ -80,6 +80,10 @@ pub struct Placements { } impl Placements { + pub fn was_visible(&self, label: &str) -> bool { + self.tabs.get(label).is_some_and(|placed| placed.visible) + } + /// Records `label` at `rect`/`visible` and says what differs from its last placement (a child /// never placed before differs in both). pub fn place(&mut self, label: &str, rect: Rect, visible: bool) -> Changed { @@ -144,10 +148,14 @@ mod tests { #[test] fn a_recreated_webview_is_placed_again() { let mut p = Placements::default(); + assert!(!p.was_visible("tab-a")); p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false); + assert!(!p.was_visible("tab-a")); p.forget("tab-a"); // A fresh webview starts visible: hiding it must not be skipped as "unchanged". assert_eq!(p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false), Changed { bounds: true, visible: true }); + p.place("tab-a", (5.0, 92.0, 680.0, 803.0), true); + assert!(p.was_visible("tab-a")); } #[test] diff --git a/crates/waybetter-host/src/tabs.rs b/crates/waybetter-host/src/tabs.rs index 6e02995..6a430e1 100644 --- a/crates/waybetter-host/src/tabs.rs +++ b/crates/waybetter-host/src/tabs.rs @@ -74,6 +74,9 @@ pub struct TabState { /// The language the site's own UI is in (its ``), a validated tag; site tabs only. #[serde(skip_serializing_if = "Option::is_none")] pub lang: Option, + /// Site content reached its first meaningful paint (sent only by participating apps). + #[serde(skip_serializing_if = "Option::is_none")] + pub content_ready: Option, } impl TabState { @@ -93,6 +96,7 @@ impl TabState { loading: None, unread: None, lang: None, + content_ready: None, } } } diff --git a/packages/shell/src/frame/DeckView.tsx b/packages/shell/src/frame/DeckView.tsx index aa57d44..1e5b5a3 100644 --- a/packages/shell/src/frame/DeckView.tsx +++ b/packages/shell/src/frame/DeckView.tsx @@ -21,6 +21,7 @@ import { useDecks, useProfiles, useT } from './hooks.ts'; import { Icon, type IconName } from './icons.tsx'; import { site } from './site.ts'; import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts'; +import { useTabStill } from './tabStill.ts'; import './deck.css'; const emitDecks = () => window.dispatchEvent(new CustomEvent('bt-decks')); @@ -177,6 +178,7 @@ function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; c const tr = useT(); const profiles = useProfiles(); const body = useRef(null); + const still = useTabStill(column.tabId); const [menu, setMenu] = useState(null); const [leaving, setLeaving] = useState(false); const spec = deckSite(); @@ -236,7 +238,9 @@ function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; c {runtime?.loading && }
-
+ {still + ? {menu?.kind === 'filters' && setMenu(null)}/>} {menu?.kind === 'menu' && setMenu(null)} onRemove={remove}/>} diff --git a/packages/shell/src/frame/Shell.tsx b/packages/shell/src/frame/Shell.tsx index 73b3596..fcc6c2a 100644 --- a/packages/shell/src/frame/Shell.tsx +++ b/packages/shell/src/frame/Shell.tsx @@ -9,7 +9,7 @@ import { type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview, } from 'dockview'; import 'dockview/dist/styles/dockview.css'; -import { useEffect, useState, type MouseEvent as ReactMouseEvent } from 'react'; +import { useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react'; import { createPortal } from 'react-dom'; import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts'; import { besideGroup } from '../paneModel.ts'; @@ -19,7 +19,7 @@ import { accountLabel } from './AccountSwitcher.tsx'; import { invoke, listen } from './bridge.ts'; import { CommandPalette } from './CommandPalette.tsx'; import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx'; -import { createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts'; +import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts'; import { installDevHost } from './devHost.ts'; import { useProfiles, useT } from './hooks.ts'; import { t } from './i18n.ts'; @@ -31,7 +31,7 @@ import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx'; import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts'; import { hasFeature, site } from './site.ts'; import { - isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction, + flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction, type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams, } from './state.ts'; import { installSyncHost } from './syncHost.ts'; @@ -170,8 +170,12 @@ function toggleDeck() { /** The deck a shortcut is about: the column's deck (keys pressed in a column), else the active deck tab. */ function deckFor(id?: string): string | null { - const found = id ? findColumnTab(id) : null; - if (found) return found.deck.id; + if (id !== undefined) { + const found = findColumnTab(id); + if (found) return found.deck.id; + const params = shell.api?.getPanel(id)?.params as TabParams | undefined; + return params?.kind === 'deck' ? params.deckId : null; + } const params = shell.api?.activePanel?.params as TabParams | undefined; return params?.kind === 'deck' ? params.deckId : null; } @@ -273,7 +277,7 @@ function runShortcut(shortcut: string, id?: string) { } // A browser shortcut pressed inside a deck column acts on its deck tab. if (id && !api.getPanel(id) && findColumnTab(id)) id = deckPanelId(findColumnTab(id)!.deck.id); - const panel = (id && api.getPanel(id)) || api.activePanel; + const panel = id === undefined ? api.activePanel : api.getPanel(id); switch (shortcut) { case 'new-tab': addStart(); break; case 'close-tab': if (panel) closeTab(panel); break; @@ -286,7 +290,7 @@ function runShortcut(shortcut: string, id?: string) { case 'forward': if (panel && isWeb(panel)) tabAction(panel.id, 'forward'); break; case 'split-right': if (panel) splitTab(panel, 'right'); break; case 'split-down': if (panel) splitTab(panel, 'below'); break; - case 'open-panel': openPanel(undefined, panel?.id); break; + case 'open-panel': if (id === undefined || panel) openPanel(undefined, panel?.id); break; case 'media-panel': toggleMedia(); break; } } @@ -456,7 +460,7 @@ function Tab(props: IDockviewPanelHeaderProps) { // Titles saved by older sessions (or before the page reports one) said "New tab" in English. const shown = params.kind === 'start' || !title || title === 'New tab' ? t('wb.shell.tab.new') : title; return
{ if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}> @@ -522,6 +526,7 @@ function markTitlebarGroups() { } export default function Shell() { + const contentReadyTabs = useRef(new Set()); const [menu, setMenu] = useState(null); const [maximized, setMaximized] = useState(false); const [palette, setPalette] = useState(null); @@ -565,29 +570,34 @@ export default function Shell() { const unlisten = [ // A tab saw its account sign in or out (native code already saved it): refresh the switcher. listen('profiles-changed', ({ payload }) => setProfiles(payload)), - listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number }>('tab-state', ({ payload }) => { + listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number; contentReady?: boolean }>('tab-state', ({ payload }) => { const panel = shell.api?.getPanel(payload.id); + const previousUrl = panel ? (panel.params as WebParams).url : decks.runtime.get(payload.id)?.url; + if (payload.loading || (payload.url && previousUrl && payload.url !== previousUrl)) contentReadyTabs.current.delete(payload.id); + if (payload.contentReady) contentReadyTabs.current.add(payload.id); + const notifyStartup = () => window.dispatchEvent(new Event('bt-tab-startup-state')); if (!panel) { // A deck column (or a deck's compose dock) reports about its own webview. const found = findColumnTab(payload.id); - if (!found) return; + if (!found) { notifyStartup(); return; } setRuntime(payload.id, { url: payload.url, title: payload.title, loading: payload.loading, unread: payload.unread }); if (found.compose) site().deck?.compose?.navigated?.(payload.id, payload.url, payload.loading); if (payload.focused && found.column && decks.focus.get(found.deck.id) !== found.column.id) { decks.focus.set(found.deck.id, found.column.id); window.dispatchEvent(new CustomEvent('bt-decks')); } + notifyStartup(); return; } // Another site must not keep the previous one's icon until (or unless) it reports its own. - const previous = (panel.params as WebParams).url; - const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf(previous) ? '' : undefined); + const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf((panel.params as WebParams).url) ? '' : undefined); patchParams(panel, { url: payload.url, loading: payload.loading, favicon, title: payload.title }); if (payload.title !== undefined) panel.api.setTitle(payload.title || (panel.params as WebParams).url); // A click into a visible pane makes it the active tab. A tab that is no longer shown (a link it // opened just took its place in the group) reports a late focus too: it must not jump back. if (payload.focused && !panel.api.isActive && panel.api.isVisible) panel.api.setActive(); saveLayoutSoon(); + notifyStartup(); }), listen<{ url: string; from?: string; background: boolean; beside?: boolean }>('tab-open', ({ payload }) => { // Links opened from a tab stay in that tab's account; they never jump to another login. @@ -699,6 +709,24 @@ export default function Shell() { const onReady = async (event: DockviewReadyEvent) => { const api: DockviewApi = event.api; + // Establish the cover before any restore-triggered sync creates a visible native tab. + // This also keeps the no-raise path from exposing X while a late still is captured. + let coverActive = isTauri && !!site().deferWindowShow; + let coverWatchdog: ReturnType | undefined; + const releaseStartupCover = () => { + if (!coverActive) return; + coverActive = false; + clearTimeout(coverWatchdog); + setOverlay(-1); + document.documentElement.classList.remove('bt-startup-cover'); + }; + if (coverActive) { + document.documentElement.classList.add('bt-startup-cover'); + setOverlay(1); + // Guard shell initialization if settings or native startup never complete. + // Once shell_ready succeeds, semantic X readiness owns this cover. + coverWatchdog = setTimeout(releaseStartupCover, 10_000); + } shell.api = api; // Chrome colors and fonts follow the theme; panes with their own theme follow theirs. site().themes?.attachDock(api); @@ -782,6 +810,93 @@ export default function Shell() { }); markTitlebarGroups(); scheduleSync(); + if (isTauri && site().deferWindowShow) { + // React commits dock placeholders after Dockview's ready callback. Keep the native + // window hidden until their real bounds have been sent and its restored panes exist. + for (let attempt = 0; attempt < 40; attempt++) { + const visibleWeb = api.panels.filter(panel => isWeb(panel) && panel.api.isVisible); + const webReady = visibleWeb.every(panel => { + const element = shell.placeholders.get(panel.id); + const rect = element?.getBoundingClientRect(); + return !!rect && rect.width > 1 && rect.height > 1; + }); + // On the first run Dockview can report no visible panels for a frame after addPanel. + // An empty `every()` must not reveal the native window before the loading shape mounts. + const visibleDeck = api.panels.some(panel => (panel.params as TabParams | undefined)?.kind === 'deck' && panel.api.isVisible); + const deckReady = api.panels.every(panel => { + const params = panel.params as TabParams | undefined; + if (params?.kind !== 'deck' || !panel.api.isVisible) return true; + const deck = deckById(params.deckId); + if (!deck) return true; + return deck.columns.every(column => decks.ready.has(column.tabId)) && + (deck.columns.length === 0 || deck.columns.some(column => { + const element = shell.placeholders.get(column.tabId); + const rect = element?.isConnected ? element.getBoundingClientRect() : null; + return !!rect && rect.width > 1 && rect.height > 1; + })); + }); + if ((visibleWeb.length > 0 || visibleDeck) && webReady && deckReady) break; + await new Promise(resolve => setTimeout(resolve, 50)); + } + const origin = new URL(site().homeUrl).origin; + const matchesSite = (url: string | null | undefined) => { + try { return !!url && new URL(url).origin === origin; } catch { return false; } + }; + const visibleSiteIds = () => { + const ids = new Set(); + for (const panel of api.panels.filter(panel => panel.api.isVisible)) { + const params = panel.params as TabParams; + if (params.kind === 'web' && matchesSite(params.url)) ids.add(panel.id); + if (params.kind === 'deck') { + for (const column of deckById(params.deckId)?.columns ?? []) { + const rect = shell.placeholders.get(column.tabId)?.getBoundingClientRect(); + const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source); + if (decks.ready.has(column.tabId) && rect && rect.width > 1 && rect.height > 1 && matchesSite(url)) { + ids.add(column.tabId); + } + } + } + } + return ids; + }; + const coverIds = visibleSiteIds(); + if (!coverIds.size) releaseStartupCover(); + await flushLayer(); + try { + await flushSync(); + // Give the shell webview two paint opportunities after its placeholder DOM is committed. + await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + await invoke('shell_ready'); + // The global watchdog protects initialization. Once shown, the visible X tabs + // keep the shell cover until content is ready or the tab is no longer visible. + clearTimeout(coverWatchdog); + if (coverIds.size && coverActive) { + // Keep the shell's loading shape over the native tab until X has a real page. + // The toolbar remains usable to reload a slow or offline page. + await new Promise(resolve => { + const done = () => { + const visible = visibleSiteIds(); + return [...coverIds].every(id => !visible.has(id) || contentReadyTabs.current.has(id)); + }; + if (done()) { resolve(); return; } + const check = () => { if (done()) finish(); }; + const finish = () => { + clearInterval(poll); + window.removeEventListener('bt-tab-startup-state', check); + resolve(); + }; + // Dockview closes and deck layout changes do not always emit tab-state. + const poll = setInterval(check, 200); + window.addEventListener('bt-tab-startup-state', check); + }); + // The X DOM signal can precede its separate native WebView surface by a frame. + // Give that surface one compositor turn before exposing it under the shell. + await new Promise(resolve => setTimeout(resolve, 100)); + } + } finally { + releaseStartupCover(); + } + } }; const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native'; diff --git a/packages/shell/src/frame/WebPanel.tsx b/packages/shell/src/frame/WebPanel.tsx index d70da9a..a1411ae 100644 --- a/packages/shell/src/frame/WebPanel.tsx +++ b/packages/shell/src/frame/WebPanel.tsx @@ -3,13 +3,14 @@ import { Fragment, useEffect, useRef, useState, type KeyboardEvent as ReactKeybo import { tabProfile } from '../profileModel.ts'; import { AccountAvatar, accountName } from './AccountSwitcher.tsx'; import { WB_MARK } from './brand.ts'; -import { invoke, listen } from './bridge.ts'; +import { invoke } from './bridge.ts'; import { useProfiles, useSiteText, useT } from './hooks.ts'; import { Icon } from './icons.tsx'; import { openPaneTheme } from './PaneTheme.tsx'; import { toUrl } from './searchInput.ts'; import { site } from './site.ts'; import { scheduleSync, setOverlay, shell, tabAction, type WebParams } from './state.ts'; +import { useTabStill } from './tabStill.ts'; /** One browser tab: toolbar with the smart address bar over a placeholder the native webview covers. */ export function WebPanel(props: IDockviewPanelProps) { @@ -22,7 +23,7 @@ export function WebPanel(props: IDockviewPanelProps) { const [caret, setCaret] = useState(0); const [splitMenu, setSplitMenu] = useState(false); // Windows: the page's last frame, shown while its webview is hidden (host `tab-still`). - const [still, setStill] = useState(null); + const still = useTabStill(api.id); useSiteText(); const profiles = useProfiles(); const { logo, product, addressCompleter, themes } = site(); @@ -46,14 +47,6 @@ export function WebPanel(props: IDockviewPanelProps) { }; }, [api]); - useEffect(() => { - let off: (() => void) | undefined; - let gone = false; - listen<{ id: string; image: string }>('tab-still', ({ payload }) => { if (payload.id === api.id) setStill(payload.image); }) - .then(dispose => { if (gone) dispose(); else off = dispose; }, () => { /* Browser preview: no native events. */ }); - return () => { gone = true; off?.(); }; - }, [api.id]); - // An overlay (the shell rises above the tab webviews, or hides them) while the menu is open; Esc closes it. useEffect(() => { if (!splitMenu) return; diff --git a/packages/shell/src/frame/shell.css b/packages/shell/src/frame/shell.css index efddf9f..12c4535 100644 --- a/packages/shell/src/frame/shell.css +++ b/packages/shell/src/frame/shell.css @@ -387,6 +387,9 @@ html.bt-raised, html.bt-raised body, html.bt-raised #root, html.bt-raised .bt-sh html.bt-raised .bt-shell .dv-groupview > .dv-content-container, html.bt-raised .bt-web, html.bt-raised .bt-viewport, html.bt-raised .bt-deck:has(.bt-col-body), html.bt-raised .bt-col, html.bt-raised .bt-compose, html.bt-raised .bt-col-body { background: transparent; } html.bt-raised :is(.bt-viewport-hint, .bt-col-hint, .bt-skeleton, .bt-still) { visibility: hidden; } +/* At startup, cover the X webview's empty first paint with the shell's existing loading shape. */ +html.bt-raised.bt-startup-cover .bt-shell :is(.bt-viewport, .bt-col-body) { background: var(--bt-ground); } +html.bt-raised.bt-startup-cover :is(.bt-viewport-hint, .bt-col-hint, .bt-skeleton) { visibility: visible; } html.bt-raised .bt-deck:has(.bt-col-body) > .bt-deck-bar { background: var(--bt-ground); } html.bt-raised .bt-deck :is(.bt-col-head, .bt-compose-head) { background-color: var(--bt-chrome); } diff --git a/packages/shell/src/frame/site.ts b/packages/shell/src/frame/site.ts index 3233793..689c25c 100644 --- a/packages/shell/src/frame/site.ts +++ b/packages/shell/src/frame/site.ts @@ -99,6 +99,8 @@ export type ShellSite = { name: string; /** The app's name ("wayBetter for X"): the update chip, the brand button, the palette's group. */ product: string; + /** Match native `AppConfig::defer_window_show`: reveal after the first layout reaches native. */ + deferWindowShow?: boolean; /** The app's logo (an image URL): titlebar, the panel tab, the new-tab page, the site chip. */ logo: string; /** The site's home feed: the first tab, and what an account opens beside. */ diff --git a/packages/shell/src/frame/state.ts b/packages/shell/src/frame/state.ts index 9c6e8a8..110d4c2 100644 --- a/packages/shell/src/frame/state.ts +++ b/packages/shell/src/frame/state.ts @@ -184,7 +184,10 @@ function columnBoxes() { export function setOverlay(delta: number) { const before = shell.overlay; shell.overlay = Math.max(0, before + delta); - if ((before === 0) !== (shell.overlay === 0)) syncLayer(); + if ((before === 0) !== (shell.overlay === 0)) { + window.dispatchEvent(new Event('bt-overlay-changed')); + syncLayer(); + } scheduleSync(); } @@ -194,6 +197,7 @@ export function setOverlay(delta: number) { * `html.bt-raised` makes the page see-through where panes are (shell.css). */ const layer = { supported: false, raised: false, queue: Promise.resolve(), probed: false }; +let layerProbe: Promise = Promise.resolve(); const frames = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); /** The startup probe (createShell): whether this platform can raise the shell above its tabs. */ @@ -203,7 +207,13 @@ export function probeLayer() { // `localStorage['bt.dev.noRaise'] = '1'` (then reload): overlays hide the tabs as where raising // is not supported, for before/after comparisons. const off = (() => { try { return localStorage.getItem('bt.dev.noRaise') === '1'; } catch { return false; } })(); - invoke('shell_raise', { on: false }).then(ok => { layer.supported = raiseSupported(ok, off); syncLayer(); scheduleSync(); }, () => {}); + layerProbe = invoke('shell_raise', { on: false }).then(ok => { layer.supported = raiseSupported(ok, off); syncLayer(); scheduleSync(); }, () => {}); +} + +/** Wait until the startup cover has either raised the shell or hidden the native tabs. */ +export async function flushLayer(): Promise { + await layerProbe; + await layer.queue; } /** diff --git a/packages/shell/src/frame/tabStill.ts b/packages/shell/src/frame/tabStill.ts new file mode 100644 index 0000000..b228f91 --- /dev/null +++ b/packages/shell/src/frame/tabStill.ts @@ -0,0 +1,53 @@ +import { useLayoutEffect, useState } from 'react'; +import { flushSync } from 'react-dom'; +import { invoke, listen } from './bridge.ts'; +import { shell } from './state.ts'; + +/** Cached native tab frame for the shell's no-raise placeholder. */ +export function useTabStill(id: string): string | null { + const [still, setStill] = useState(null); + useLayoutEffect(() => { + const off: Array<() => void> = []; + let gone = false; + let active: number | null = null; + setStill(null); + const overlayChanged = () => { active = null; setStill(null); }; + window.addEventListener('bt-overlay-changed', overlayChanged); + const watch = (event: string, handler: (payload: T) => void) => { + listen(event, ({ payload }) => { if (!gone) handler(payload); }) + .then(dispose => { if (gone) dispose(); else off.push(dispose); }, () => {}); + }; + watch<{ id: string; token: number }>('tab-still-start', payload => { + if (payload.id !== id) return; + active = payload.token; + setStill(null); + }); + watch<{ id: string; token: number }>('tab-still-cancel', payload => { + if (payload.id !== id || active !== payload.token) return; + active = null; + setStill(null); + }); + watch('tab-still-reset', tabId => { + if (tabId !== id) return; + active = null; + setStill(null); + }); + watch<{ id: string; image: string; token: number }>('tab-still', payload => { + if (payload.id !== id || active !== payload.token || shell.overlay === 0) return; + // Keep the native tab over this pane until its replacement image is decoded and painted. + const picture = new Image(); + picture.src = payload.image; + void picture.decode().catch(() => {}).then(() => { + if (gone || active !== payload.token || shell.overlay === 0) return; + flushSync(() => setStill(payload.image)); + requestAnimationFrame(() => setTimeout(() => { + if (!gone && active === payload.token && shell.overlay > 0) { + void invoke('tab_still_ready', { id, token: payload.token }).catch(() => {}); + } + }, 0)); + }); + }); + return () => { gone = true; window.removeEventListener('bt-overlay-changed', overlayChanged); off.forEach(dispose => dispose()); }; + }, [id]); + return still; +}