fix(shell): coordinate startup cover and tab stills
This commit is contained in:
parent
fd99901bb2
commit
2008967c04
13 changed files with 442 additions and 52 deletions
|
|
@ -290,7 +290,7 @@ statement checks its caller.
|
||||||
routes helper-window closes (Windows), follows window resizes natively and adds the shell
|
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).
|
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`,
|
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
|
`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
|
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
|
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:
|
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`,
|
`profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`,
|
||||||
`open_external`.
|
`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`.
|
- `commands`: the host's command list and `manifest(&[..])` for the app's `build.rs`.
|
||||||
- `testkit`: see the capabilities section.
|
- `testkit`: see the capabilities section.
|
||||||
- `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never
|
- `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,8 @@ pub struct AppConfig {
|
||||||
pub min_window_size: (f64, f64),
|
pub min_window_size: (f64, f64),
|
||||||
/// The window's color before the shell paints (no white flash).
|
/// The window's color before the shell paints (no white flash).
|
||||||
pub background: (u8, u8, u8),
|
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
|
/// 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.
|
/// traffic lights over the shell). Off: the OS frame, for a shell without one.
|
||||||
pub custom_titlebar: bool,
|
pub custom_titlebar: bool,
|
||||||
|
|
@ -74,6 +76,7 @@ impl AppConfig {
|
||||||
window_size: (1360.0, 900.0),
|
window_size: (1360.0, 900.0),
|
||||||
min_window_size: (900.0, 560.0),
|
min_window_size: (900.0, 560.0),
|
||||||
background: (7, 8, 12),
|
background: (7, 8, 12),
|
||||||
|
defer_window_show: false,
|
||||||
custom_titlebar: true,
|
custom_titlebar: true,
|
||||||
deep_link: false,
|
deep_link: false,
|
||||||
updater: false,
|
updater: false,
|
||||||
|
|
@ -319,8 +322,8 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
|
||||||
// and the app's per-tab state goes with the old one.
|
// and the app's per-tab state goes with the old one.
|
||||||
let existing = match existing {
|
let existing = match existing {
|
||||||
Some(tab) if current_profile.as_deref() != Some(item.profile.as_str()) => {
|
Some(tab) if current_profile.as_deref() != Some(item.profile.as_str()) => {
|
||||||
|
host::forget_tab(&app, &label);
|
||||||
let _ = tab.close();
|
let _ = tab.close();
|
||||||
host::forget_tab(&label);
|
|
||||||
profiles(&app)?.tab_profiles.remove(&label);
|
profiles(&app)?.tab_profiles.remove(&label);
|
||||||
hooks.tab_closed(&app, &label, TabClosed::Replaced);
|
hooks.tab_closed(&app, &label, TabClosed::Replaced);
|
||||||
None
|
None
|
||||||
|
|
@ -383,8 +386,8 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
|
||||||
if let Some(id) = policy::tab_id(existing.label()) {
|
if let Some(id) = policy::tab_id(existing.label()) {
|
||||||
if !keep.contains(id) {
|
if !keep.contains(id) {
|
||||||
let label = existing.label().to_owned();
|
let label = existing.label().to_owned();
|
||||||
|
host::forget_tab(&app, &label);
|
||||||
let _ = existing.close();
|
let _ = existing.close();
|
||||||
host::forget_tab(&label);
|
|
||||||
if let Ok(mut data) = profiles(&app) {
|
if let Ok(mut data) = profiles(&app) {
|
||||||
data.tab_profiles.remove(&label);
|
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}"))
|
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,
|
/// 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
|
/// 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.
|
/// 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<Wry>) -> bool + Send + Sync + 's
|
||||||
tab_action,
|
tab_action,
|
||||||
open_external_url,
|
open_external_url,
|
||||||
shell_focus,
|
shell_focus,
|
||||||
|
shell_ready,
|
||||||
|
tab_still_ready,
|
||||||
shell_raise,
|
shell_raise,
|
||||||
window_system_menu,
|
window_system_menu,
|
||||||
profiles_get,
|
profiles_get,
|
||||||
|
|
@ -864,6 +888,18 @@ fn open_window(app: &mut tauri::App<Wry>, config: &AppConfig) -> Result<(), Box<
|
||||||
let shell = shell.transparent(true);
|
let shell = shell.transparent(true);
|
||||||
let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?;
|
let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?;
|
||||||
host::attach_shell(&shell);
|
host::attach_shell(&shell);
|
||||||
|
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()?;
|
window.show()?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ pub const SHELL: &[&str] = &[
|
||||||
"tab_action",
|
"tab_action",
|
||||||
"open_external_url",
|
"open_external_url",
|
||||||
"shell_focus",
|
"shell_focus",
|
||||||
|
"shell_ready",
|
||||||
|
"tab_still_ready",
|
||||||
"shell_raise",
|
"shell_raise",
|
||||||
"window_system_menu",
|
"window_system_menu",
|
||||||
"profiles_get",
|
"profiles_get",
|
||||||
|
|
|
||||||
|
|
@ -461,6 +461,12 @@ mod linux {
|
||||||
|
|
||||||
/// The event carrying a tab's last frame to the shell ([`capture_still`]).
|
/// The event carrying a tab's last frame to the shell ([`capture_still`]).
|
||||||
pub const EVENT_TAB_STILL: &str = "tab-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)]
|
#[cfg(windows)]
|
||||||
#[derive(Clone, Serialize)]
|
#[derive(Clone, Serialize)]
|
||||||
|
|
@ -468,18 +474,114 @@ struct TabStill {
|
||||||
id: String,
|
id: String,
|
||||||
/// `data:image/jpeg;base64,…`
|
/// `data:image/jpeg;base64,…`
|
||||||
image: String,
|
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<std::collections::HashMap<String, StillEntry>> {
|
||||||
|
use std::sync::{Mutex, OnceLock};
|
||||||
|
static PENDING: OnceLock<Mutex<std::collections::HashMap<String, StillEntry>>> = OnceLock::new();
|
||||||
|
PENDING.get_or_init(Default::default)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn cancel_pending_still(label: &str) -> Option<u64> {
|
||||||
|
pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(label).map(|entry| entry.token)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn hide_after_still<R: Runtime>(app: &AppHandle<R>, 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<R: Runtime>(app: &AppHandle<R>, 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<R: Runtime>(_app: &AppHandle<R>, _id: &str, _token: u64) {}
|
||||||
|
|
||||||
/// Windows: a tab webview about to be hidden hands the shell its last frame (WebView2
|
/// 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
|
/// `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
|
/// 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.
|
/// thread, so the frame is still there. Kept in the shell's memory only. No-op elsewhere.
|
||||||
fn capture_still<R: Runtime>(webview: &Webview<R>) {
|
fn capture_still<R: Runtime>(webview: &Webview<R>, token: u64) {
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
{
|
{
|
||||||
let Some(id) = policy::tab_id(webview.label()).map(str::to_owned) else { return };
|
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 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 base64::Engine;
|
||||||
use webview2_com::CapturePreviewCompletedHandler;
|
use webview2_com::CapturePreviewCompletedHandler;
|
||||||
use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG;
|
use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG;
|
||||||
|
|
@ -491,41 +593,82 @@ fn capture_still<R: Runtime>(webview: &Webview<R>) {
|
||||||
let controller = platform.controller();
|
let controller = platform.controller();
|
||||||
let mut shown = windows::core::BOOL::default();
|
let mut shown = windows::core::BOOL::default();
|
||||||
if controller.IsVisible(&mut shown).is_err() || !shown.as_bool() {
|
if controller.IsVisible(&mut shown).is_err() || !shown.as_bool() {
|
||||||
|
hide_after_still(&app, &label, token);
|
||||||
return;
|
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 target = stream.clone();
|
||||||
|
let callback_app = app.clone();
|
||||||
|
let callback_label = label.clone();
|
||||||
let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| {
|
let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| {
|
||||||
result?;
|
let image = (|| {
|
||||||
|
result.ok()?;
|
||||||
let mut size = 0u64;
|
let mut size = 0u64;
|
||||||
target.Seek(0, STREAM_SEEK_END, Some(&mut size))?;
|
target.Seek(0, STREAM_SEEK_END, Some(&mut size)).ok()?;
|
||||||
if size == 0 || size > 16 << 20 {
|
if size == 0 || size > 16 << 20 { return None; }
|
||||||
return Ok(());
|
target.Seek(0, STREAM_SEEK_SET, None).ok()?;
|
||||||
}
|
|
||||||
target.Seek(0, STREAM_SEEK_SET, None)?;
|
|
||||||
let mut bytes = vec![0u8; size as usize];
|
let mut bytes = vec![0u8; size as usize];
|
||||||
let mut read = 0u32;
|
let mut read = 0u32;
|
||||||
target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok()?;
|
target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok().ok()?;
|
||||||
bytes.truncate(read as usize);
|
bytes.truncate(read as usize);
|
||||||
let image = format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
|
Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)))
|
||||||
emit_shell(&app, EVENT_TAB_STILL, TabStill { id, image });
|
})();
|
||||||
|
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);
|
||||||
|
}
|
||||||
Ok(())
|
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))]
|
#[cfg(not(windows))]
|
||||||
let _ = webview;
|
let _ = (webview, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shows or hides a tab webview and sets its WebView2 memory target to match
|
/// 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`
|
/// ([`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
|
/// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only
|
||||||
/// show/hide.
|
/// show/hide.
|
||||||
pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool) {
|
pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool, was_visible: bool) {
|
||||||
if !visible {
|
#[cfg(windows)]
|
||||||
capture_still(webview);
|
{
|
||||||
|
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() };
|
let _ = if visible { webview.show() } else { webview.hide() };
|
||||||
set_memory_target(webview, visible, parked);
|
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
|
/// 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.
|
/// touches one webview, and one that changes nothing costs nothing.
|
||||||
pub fn place_tab<R: Runtime>(webview: &Webview<R>, rect: crate::layout::Rect, visible: bool, parked: bool) {
|
pub fn place_tab<R: Runtime>(webview: &Webview<R>, 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 {
|
if changed.bounds {
|
||||||
let (x, y, width, height) = rect;
|
let (x, y, width, height) = rect;
|
||||||
place_child(webview, x, y, width, height);
|
place_child(webview, x, y, width, height);
|
||||||
}
|
}
|
||||||
if changed.visible {
|
if changed.visible {
|
||||||
set_tab_visible(webview, visible, parked);
|
set_tab_visible(webview, visible, parked, was_visible);
|
||||||
} else {
|
} else {
|
||||||
set_memory_target(webview, visible, parked);
|
set_memory_target(webview, visible, parked);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A tab webview was closed: a new one with the same label is placed from scratch.
|
/// 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<R: Runtime>(app: &AppHandle<R>, 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);
|
placements().forget(label);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,10 @@ pub struct Placements {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl 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
|
/// Records `label` at `rect`/`visible` and says what differs from its last placement (a child
|
||||||
/// never placed before differs in both).
|
/// never placed before differs in both).
|
||||||
pub fn place(&mut self, label: &str, rect: Rect, visible: bool) -> Changed {
|
pub fn place(&mut self, label: &str, rect: Rect, visible: bool) -> Changed {
|
||||||
|
|
@ -144,10 +148,14 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn a_recreated_webview_is_placed_again() {
|
fn a_recreated_webview_is_placed_again() {
|
||||||
let mut p = Placements::default();
|
let mut p = Placements::default();
|
||||||
|
assert!(!p.was_visible("tab-a"));
|
||||||
p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false);
|
p.place("tab-a", (5.0, 92.0, 680.0, 803.0), false);
|
||||||
|
assert!(!p.was_visible("tab-a"));
|
||||||
p.forget("tab-a");
|
p.forget("tab-a");
|
||||||
// A fresh webview starts visible: hiding it must not be skipped as "unchanged".
|
// 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 });
|
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]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -74,6 +74,9 @@ pub struct TabState {
|
||||||
/// The language the site's own UI is in (its `<html lang>`), a validated tag; site tabs only.
|
/// The language the site's own UI is in (its `<html lang>`), a validated tag; site tabs only.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub lang: Option<String>,
|
pub lang: Option<String>,
|
||||||
|
/// Site content reached its first meaningful paint (sent only by participating apps).
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_ready: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TabState {
|
impl TabState {
|
||||||
|
|
@ -93,6 +96,7 @@ impl TabState {
|
||||||
loading: None,
|
loading: None,
|
||||||
unread: None,
|
unread: None,
|
||||||
lang: None,
|
lang: None,
|
||||||
|
content_ready: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ import { useDecks, useProfiles, useT } from './hooks.ts';
|
||||||
import { Icon, type IconName } from './icons.tsx';
|
import { Icon, type IconName } from './icons.tsx';
|
||||||
import { site } from './site.ts';
|
import { site } from './site.ts';
|
||||||
import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts';
|
import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts';
|
||||||
|
import { useTabStill } from './tabStill.ts';
|
||||||
import './deck.css';
|
import './deck.css';
|
||||||
|
|
||||||
const emitDecks = () => window.dispatchEvent(new CustomEvent('bt-decks'));
|
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 tr = useT();
|
||||||
const profiles = useProfiles();
|
const profiles = useProfiles();
|
||||||
const body = useRef<HTMLDivElement>(null);
|
const body = useRef<HTMLDivElement>(null);
|
||||||
|
const still = useTabStill(column.tabId);
|
||||||
const [menu, setMenu] = useState<null | { kind: 'filters' | 'menu'; anchor: DOMRect }>(null);
|
const [menu, setMenu] = useState<null | { kind: 'filters' | 'menu'; anchor: DOMRect }>(null);
|
||||||
const [leaving, setLeaving] = useState(false);
|
const [leaving, setLeaving] = useState(false);
|
||||||
const spec = deckSite();
|
const spec = deckSite();
|
||||||
|
|
@ -236,7 +238,9 @@ function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; c
|
||||||
{runtime?.loading && <span className="bt-col-progress" aria-label={tr('wb.common.loading')}/>}
|
{runtime?.loading && <span className="bt-col-progress" aria-label={tr('wb.common.loading')}/>}
|
||||||
</header>
|
</header>
|
||||||
<div className="bt-col-body" ref={body}>
|
<div className="bt-col-body" ref={body}>
|
||||||
<div className="bt-col-hint"><span className="bt-spinner" aria-hidden="true"/><span>{title}</span></div>
|
{still
|
||||||
|
? <div className="bt-still" aria-hidden="true" style={{ backgroundImage: `url("${still}")` }}/>
|
||||||
|
: <div className="bt-col-hint"><span className="bt-spinner" aria-hidden="true"/><span>{title}</span></div>}
|
||||||
</div>
|
</div>
|
||||||
{menu?.kind === 'filters' && <FilterPopover deckId={deck.id} column={column} anchor={menu.anchor} onClose={() => setMenu(null)}/>}
|
{menu?.kind === 'filters' && <FilterPopover deckId={deck.id} column={column} anchor={menu.anchor} onClose={() => setMenu(null)}/>}
|
||||||
{menu?.kind === 'menu' && <ColumnMenu deck={deck} column={column} anchor={menu.anchor} onClose={() => setMenu(null)} onRemove={remove}/>}
|
{menu?.kind === 'menu' && <ColumnMenu deck={deck} column={column} anchor={menu.anchor} onClose={() => setMenu(null)} onRemove={remove}/>}
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import {
|
||||||
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
|
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
|
||||||
} from 'dockview';
|
} from 'dockview';
|
||||||
import 'dockview/dist/styles/dockview.css';
|
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 { createPortal } from 'react-dom';
|
||||||
import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts';
|
import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts';
|
||||||
import { besideGroup } from '../paneModel.ts';
|
import { besideGroup } from '../paneModel.ts';
|
||||||
|
|
@ -19,7 +19,7 @@ import { accountLabel } from './AccountSwitcher.tsx';
|
||||||
import { invoke, listen } from './bridge.ts';
|
import { invoke, listen } from './bridge.ts';
|
||||||
import { CommandPalette } from './CommandPalette.tsx';
|
import { CommandPalette } from './CommandPalette.tsx';
|
||||||
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.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 { installDevHost } from './devHost.ts';
|
||||||
import { useProfiles, useT } from './hooks.ts';
|
import { useProfiles, useT } from './hooks.ts';
|
||||||
import { t } from './i18n.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 { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts';
|
||||||
import { hasFeature, site } from './site.ts';
|
import { hasFeature, site } from './site.ts';
|
||||||
import {
|
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,
|
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
|
||||||
} from './state.ts';
|
} from './state.ts';
|
||||||
import { installSyncHost } from './syncHost.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. */
|
/** 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 {
|
function deckFor(id?: string): string | null {
|
||||||
const found = id ? findColumnTab(id) : null;
|
if (id !== undefined) {
|
||||||
|
const found = findColumnTab(id);
|
||||||
if (found) return found.deck.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;
|
const params = shell.api?.activePanel?.params as TabParams | undefined;
|
||||||
return params?.kind === 'deck' ? params.deckId : null;
|
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.
|
// 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);
|
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) {
|
switch (shortcut) {
|
||||||
case 'new-tab': addStart(); break;
|
case 'new-tab': addStart(); break;
|
||||||
case 'close-tab': if (panel) closeTab(panel); 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 'forward': if (panel && isWeb(panel)) tabAction(panel.id, 'forward'); break;
|
||||||
case 'split-right': if (panel) splitTab(panel, 'right'); break;
|
case 'split-right': if (panel) splitTab(panel, 'right'); break;
|
||||||
case 'split-down': if (panel) splitTab(panel, 'below'); 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;
|
case 'media-panel': toggleMedia(); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -456,7 +460,7 @@ function Tab(props: IDockviewPanelHeaderProps<TabParams>) {
|
||||||
// Titles saved by older sessions (or before the page reports one) said "New tab" in English.
|
// 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;
|
const shown = params.kind === 'start' || !title || title === 'New tab' ? t('wb.shell.tab.new') : title;
|
||||||
return <div className={`bt-tab${params.pinned ? ' pinned bt-tab--pinned' : ''}${loading ? ' bt-tab--loading' : ''}`}
|
return <div className={`bt-tab${params.pinned ? ' pinned bt-tab--pinned' : ''}${loading ? ' bt-tab--loading' : ''}`}
|
||||||
title={account ? `${shown} · ${accountName}` : shown} onContextMenu={onContextMenu}
|
data-panel-id={props.api.id} title={account ? `${shown} · ${accountName}` : shown} onContextMenu={onContextMenu}
|
||||||
onAuxClick={event => { if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}>
|
onAuxClick={event => { if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}>
|
||||||
<span className="bt-tab-icon">
|
<span className="bt-tab-icon">
|
||||||
<Favicon params={params}/>
|
<Favicon params={params}/>
|
||||||
|
|
@ -522,6 +526,7 @@ function markTitlebarGroups() {
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Shell() {
|
export default function Shell() {
|
||||||
|
const contentReadyTabs = useRef(new Set<string>());
|
||||||
const [menu, setMenu] = useState<Menu | null>(null);
|
const [menu, setMenu] = useState<Menu | null>(null);
|
||||||
const [maximized, setMaximized] = useState(false);
|
const [maximized, setMaximized] = useState(false);
|
||||||
const [palette, setPalette] = useState<PaletteContext | null>(null);
|
const [palette, setPalette] = useState<PaletteContext | null>(null);
|
||||||
|
|
@ -565,29 +570,34 @@ export default function Shell() {
|
||||||
const unlisten = [
|
const unlisten = [
|
||||||
// A tab saw its account sign in or out (native code already saved it): refresh the switcher.
|
// A tab saw its account sign in or out (native code already saved it): refresh the switcher.
|
||||||
listen<unknown>('profiles-changed', ({ payload }) => setProfiles(payload)),
|
listen<unknown>('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 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) {
|
if (!panel) {
|
||||||
// A deck column (or a deck's compose dock) reports about its own webview.
|
// A deck column (or a deck's compose dock) reports about its own webview.
|
||||||
const found = findColumnTab(payload.id);
|
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 });
|
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 (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) {
|
if (payload.focused && found.column && decks.focus.get(found.deck.id) !== found.column.id) {
|
||||||
decks.focus.set(found.deck.id, found.column.id);
|
decks.focus.set(found.deck.id, found.column.id);
|
||||||
window.dispatchEvent(new CustomEvent('bt-decks'));
|
window.dispatchEvent(new CustomEvent('bt-decks'));
|
||||||
}
|
}
|
||||||
|
notifyStartup();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Another site must not keep the previous one's icon until (or unless) it reports its own.
|
// 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((panel.params as WebParams).url) ? '' : undefined);
|
||||||
const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf(previous) ? '' : undefined);
|
|
||||||
patchParams(panel, { url: payload.url, loading: payload.loading, favicon, title: payload.title });
|
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);
|
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
|
// 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.
|
// 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();
|
if (payload.focused && !panel.api.isActive && panel.api.isVisible) panel.api.setActive();
|
||||||
saveLayoutSoon();
|
saveLayoutSoon();
|
||||||
|
notifyStartup();
|
||||||
}),
|
}),
|
||||||
listen<{ url: string; from?: string; background: boolean; beside?: boolean }>('tab-open', ({ payload }) => {
|
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.
|
// 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 onReady = async (event: DockviewReadyEvent) => {
|
||||||
const api: DockviewApi = event.api;
|
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<typeof setTimeout> | 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;
|
shell.api = api;
|
||||||
// Chrome colors and fonts follow the theme; panes with their own theme follow theirs.
|
// Chrome colors and fonts follow the theme; panes with their own theme follow theirs.
|
||||||
site().themes?.attachDock(api);
|
site().themes?.attachDock(api);
|
||||||
|
|
@ -782,6 +810,93 @@ export default function Shell() {
|
||||||
});
|
});
|
||||||
markTitlebarGroups();
|
markTitlebarGroups();
|
||||||
scheduleSync();
|
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<string>();
|
||||||
|
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<void>(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<void>(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';
|
const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native';
|
||||||
|
|
|
||||||
|
|
@ -3,13 +3,14 @@ import { Fragment, useEffect, useRef, useState, type KeyboardEvent as ReactKeybo
|
||||||
import { tabProfile } from '../profileModel.ts';
|
import { tabProfile } from '../profileModel.ts';
|
||||||
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
|
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
|
||||||
import { WB_MARK } from './brand.ts';
|
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 { useProfiles, useSiteText, useT } from './hooks.ts';
|
||||||
import { Icon } from './icons.tsx';
|
import { Icon } from './icons.tsx';
|
||||||
import { openPaneTheme } from './PaneTheme.tsx';
|
import { openPaneTheme } from './PaneTheme.tsx';
|
||||||
import { toUrl } from './searchInput.ts';
|
import { toUrl } from './searchInput.ts';
|
||||||
import { site } from './site.ts';
|
import { site } from './site.ts';
|
||||||
import { scheduleSync, setOverlay, shell, tabAction, type WebParams } from './state.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. */
|
/** One browser tab: toolbar with the smart address bar over a placeholder the native webview covers. */
|
||||||
export function WebPanel(props: IDockviewPanelProps<WebParams>) {
|
export function WebPanel(props: IDockviewPanelProps<WebParams>) {
|
||||||
|
|
@ -22,7 +23,7 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
|
||||||
const [caret, setCaret] = useState(0);
|
const [caret, setCaret] = useState(0);
|
||||||
const [splitMenu, setSplitMenu] = useState(false);
|
const [splitMenu, setSplitMenu] = useState(false);
|
||||||
// Windows: the page's last frame, shown while its webview is hidden (host `tab-still`).
|
// Windows: the page's last frame, shown while its webview is hidden (host `tab-still`).
|
||||||
const [still, setStill] = useState<string | null>(null);
|
const still = useTabStill(api.id);
|
||||||
useSiteText();
|
useSiteText();
|
||||||
const profiles = useProfiles();
|
const profiles = useProfiles();
|
||||||
const { logo, product, addressCompleter, themes } = site();
|
const { logo, product, addressCompleter, themes } = site();
|
||||||
|
|
@ -46,14 +47,6 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
|
||||||
};
|
};
|
||||||
}, [api]);
|
}, [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.
|
// An overlay (the shell rises above the tab webviews, or hides them) while the menu is open; Esc closes it.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!splitMenu) return;
|
if (!splitMenu) return;
|
||||||
|
|
|
||||||
|
|
@ -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-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 .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; }
|
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: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); }
|
html.bt-raised .bt-deck :is(.bt-col-head, .bt-compose-head) { background-color: var(--bt-chrome); }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -99,6 +99,8 @@ export type ShellSite = {
|
||||||
name: string;
|
name: string;
|
||||||
/** The app's name ("wayBetter for X"): the update chip, the brand button, the palette's group. */
|
/** The app's name ("wayBetter for X"): the update chip, the brand button, the palette's group. */
|
||||||
product: string;
|
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. */
|
/** The app's logo (an image URL): titlebar, the panel tab, the new-tab page, the site chip. */
|
||||||
logo: string;
|
logo: string;
|
||||||
/** The site's home feed: the first tab, and what an account opens beside. */
|
/** The site's home feed: the first tab, and what an account opens beside. */
|
||||||
|
|
|
||||||
|
|
@ -184,7 +184,10 @@ function columnBoxes() {
|
||||||
export function setOverlay(delta: number) {
|
export function setOverlay(delta: number) {
|
||||||
const before = shell.overlay;
|
const before = shell.overlay;
|
||||||
shell.overlay = Math.max(0, before + delta);
|
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();
|
scheduleSync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -194,6 +197,7 @@ export function setOverlay(delta: number) {
|
||||||
* `html.bt-raised` makes the page see-through where panes are (shell.css).
|
* `html.bt-raised` makes the page see-through where panes are (shell.css).
|
||||||
*/
|
*/
|
||||||
const layer = { supported: false, raised: false, queue: Promise.resolve(), probed: false };
|
const layer = { supported: false, raised: false, queue: Promise.resolve(), probed: false };
|
||||||
|
let layerProbe: Promise<void> = Promise.resolve();
|
||||||
const frames = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
const frames = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||||
|
|
||||||
/** The startup probe (createShell): whether this platform can raise the shell above its tabs. */
|
/** 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
|
// `localStorage['bt.dev.noRaise'] = '1'` (then reload): overlays hide the tabs as where raising
|
||||||
// is not supported, for before/after comparisons.
|
// is not supported, for before/after comparisons.
|
||||||
const off = (() => { try { return localStorage.getItem('bt.dev.noRaise') === '1'; } catch { return false; } })();
|
const off = (() => { try { return localStorage.getItem('bt.dev.noRaise') === '1'; } catch { return false; } })();
|
||||||
invoke<boolean>('shell_raise', { on: false }).then(ok => { layer.supported = raiseSupported(ok, off); syncLayer(); scheduleSync(); }, () => {});
|
layerProbe = invoke<boolean>('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<void> {
|
||||||
|
await layerProbe;
|
||||||
|
await layer.queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
53
packages/shell/src/frame/tabStill.ts
Normal file
53
packages/shell/src/frame/tabStill.ts
Normal file
|
|
@ -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<string | null>(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 = <T,>(event: string, handler: (payload: T) => void) => {
|
||||||
|
listen<T>(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<string>('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;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue