Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions packages/tauri-app/src-tauri/src/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ mod navigation;
mod partitions;
mod process;
mod window;
mod window_flush;
#[cfg(test)]
mod window_flush_tests;

#[doc(hidden)]
pub use commands::{
Expand Down Expand Up @@ -35,7 +38,6 @@ use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicU64;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter, Manager};
Expand Down Expand Up @@ -72,7 +74,7 @@ pub struct ClientState {
state: Mutex<PersistedClientState>,
zoom_levels: Mutex<HashMap<String, f64>>,
write_lock: Mutex<()>,
save_generation: AtomicU64,
window_flush: window_flush::WindowFlushScheduler,
renderer_access: access::RendererAccess,
ephemeral_windows: Mutex<HashSet<String>>,
renderer_flush: RendererFlush,
Expand Down Expand Up @@ -205,7 +207,7 @@ impl ClientState {
state: Mutex::new(state),
zoom_levels: Mutex::new(zoom_levels),
write_lock: Mutex::new(()),
save_generation: AtomicU64::new(0),
window_flush: window_flush::WindowFlushScheduler::default(),
renderer_access: access::RendererAccess::default(),
ephemeral_windows: Mutex::new(HashSet::new()),
renderer_flush: RendererFlush::default(),
Expand Down Expand Up @@ -704,6 +706,12 @@ impl ClientState {
Ok(())
}

fn schedule_window_flush(&self, app: &AppHandle) {
if let Err(error) = self.window_flush.schedule(app) {
eprintln!("[client-state] failed to schedule window-state flush: {error}");
}
}

fn normal_writes_suppressed(&self, window_id: &str) -> Result<bool, String> {
let state = self.state.lock().map_err(|err| err.to_string())?;
Ok(state.unsupported_future_envelope || !state.record(window_id)?.writes_enabled)
Expand Down Expand Up @@ -822,6 +830,7 @@ impl ClientState {
}

fn release_locks(&self) {
self.window_flush.stop();
// Lock order fences takeover until root publication and partition GC leave write_lock.
let _write = self
.write_lock
Expand Down
18 changes: 1 addition & 17 deletions packages/tauri-app/src-tauri/src/client_state/window.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
use super::ClientState;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WindowEvent};

const MIN_WINDOW_WIDTH: i32 = 800;
const MIN_WINDOW_HEIGHT: i32 = 600;
const MIN_ZOOM_LEVEL: f64 = 0.25;
pub(super) const MAX_ZOOM_LEVEL: f64 = 5.0;
const SAVE_DEBOUNCE: Duration = Duration::from_millis(250);

pub const DEFAULT_ZOOM_LEVEL: f64 = 1.0;

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
Expand Down Expand Up @@ -254,19 +250,7 @@ fn schedule_flush(app: &AppHandle) {
let Some(client_state) = app.try_state::<ClientState>() else {
return;
};
let generation = client_state.save_generation.fetch_add(1, Ordering::SeqCst) + 1;
let app = app.clone();
std::thread::spawn(move || {
std::thread::sleep(SAVE_DEBOUNCE);
let Some(client_state) = app.try_state::<ClientState>() else {
return;
};
if client_state.save_generation.load(Ordering::SeqCst) == generation {
if let Err(err) = client_state.flush() {
eprintln!("[client-state] failed to save window state: {err}");
}
}
});
client_state.schedule_window_flush(app);
}

#[cfg(windows)]
Expand Down
96 changes: 96 additions & 0 deletions packages/tauri-app/src-tauri/src/client_state/window_flush.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use super::ClientState;
use std::sync::{
mpsc::{sync_channel, Receiver, RecvTimeoutError, SyncSender, TrySendError},
Mutex,
};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use tauri::{AppHandle, Manager};

const SAVE_DEBOUNCE: Duration = Duration::from_millis(250);

#[derive(Default)]
struct SchedulerState {
sender: Option<SyncSender<AppHandle>>,
worker: Option<JoinHandle<()>>,
stopped: bool,
}

#[derive(Default)]
pub(super) struct WindowFlushScheduler {
state: Mutex<SchedulerState>,
}

impl WindowFlushScheduler {
pub(super) fn schedule(&self, app: &AppHandle) -> Result<(), String> {
let mut state = self.state.lock().map_err(|error| error.to_string())?;
if state.stopped {
return Ok(());
}
if state.sender.is_none() {
// Keep at most one wakeup queued while the single worker is busy.
let (sender, receiver): (SyncSender<AppHandle>, Receiver<AppHandle>) = sync_channel(1);
let worker = thread::Builder::new()
.name("client-state-window-flush".to_string())
.spawn(move || {
run_debounced(receiver, SAVE_DEBOUNCE, |worker_app| {
let Some(client_state) = worker_app.try_state::<ClientState>() else {
return;
};
if let Err(error) = client_state.flush() {
eprintln!("[client-state] failed to save window state: {error}");
}
});
})
.map_err(|error| format!("failed to start window-state flush worker: {error}"))?;
state.sender = Some(sender);
state.worker = Some(worker);
}

match state
.sender
.as_ref()
.expect("initialized sender")
.try_send(app.clone())
{
Ok(()) | Err(TrySendError::Full(_)) => Ok(()),
Err(TrySendError::Disconnected(_)) => {
Err("window-state flush worker disconnected".to_string())
}
}
}

pub(super) fn stop(&self) {
let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
state.stopped = true;
// Disconnect wakes the worker and makes it drain a pending flush before ownership release.
drop(state.sender.take());
if let Some(worker) = state.worker.take() {
if worker.join().is_err() {
eprintln!("[client-state] window-state flush worker panicked");
}
}
}
}

pub(super) fn run_debounced<T>(
receiver: Receiver<T>,
debounce: Duration,
mut flush: impl FnMut(T),
) {
while let Ok(mut request) = receiver.recv() {
loop {
match receiver.recv_timeout(debounce) {
Ok(next) => request = next,
Err(RecvTimeoutError::Timeout) => {
flush(request);
break;
}
Err(RecvTimeoutError::Disconnected) => {
flush(request);
return;
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use super::window_flush::run_debounced;
use std::sync::mpsc::{self, sync_channel, RecvTimeoutError};
use std::thread;
use std::time::Duration;

#[test]
fn burst_requests_coalesce_to_one_flush() {
let (sender, receiver) = sync_channel(1);
let (flushed_sender, flushed_receiver) = mpsc::channel();
let worker = thread::spawn(move || {
run_debounced(receiver, Duration::from_millis(30), |()| {
flushed_sender.send(()).unwrap();
});
});

sender.try_send(()).unwrap();
for _ in 0..256 {
let _ = sender.try_send(());
}
flushed_receiver
.recv_timeout(Duration::from_secs(1))
.unwrap();
assert_eq!(
flushed_receiver.recv_timeout(Duration::from_millis(80)),
Err(RecvTimeoutError::Timeout)
);

drop(sender);
worker.join().unwrap();
}

#[test]
fn request_during_flush_produces_one_trailing_flush() {
let (sender, receiver) = sync_channel(1);
let (entered_sender, entered_receiver) = mpsc::channel();
let (release_sender, release_receiver) = mpsc::channel();
let worker = thread::spawn(move || {
let mut calls = 0;
run_debounced(receiver, Duration::from_millis(20), |()| {
calls += 1;
entered_sender.send(calls).unwrap();
if calls == 1 {
release_receiver
.recv_timeout(Duration::from_secs(1))
.unwrap();
}
});
});

sender.try_send(()).unwrap();
assert_eq!(
entered_receiver
.recv_timeout(Duration::from_secs(1))
.unwrap(),
1
);
for _ in 0..256 {
let _ = sender.try_send(());
}
release_sender.send(()).unwrap();
assert_eq!(
entered_receiver
.recv_timeout(Duration::from_secs(1))
.unwrap(),
2
);
assert_eq!(
entered_receiver.recv_timeout(Duration::from_millis(60)),
Err(RecvTimeoutError::Timeout)
);

drop(sender);
worker.join().unwrap();
}

#[test]
fn disconnect_drains_a_pending_request_without_waiting_for_debounce() {
let (sender, receiver) = sync_channel(1);
let (flushed_sender, flushed_receiver) = mpsc::channel();
let worker = thread::spawn(move || {
run_debounced(receiver, Duration::from_secs(10), |()| {
flushed_sender.send(()).unwrap();
});
});

sender.try_send(()).unwrap();
drop(sender);
flushed_receiver
.recv_timeout(Duration::from_secs(1))
.unwrap();
worker.join().unwrap();
}
Loading