Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,12 @@ jobs:
if: runner.os == 'Windows'
run: |
cargo test -p rake-app-cli --bin rake project_build:: --locked
- name: Build global shortcut probe (X11)
if: runner.os == 'Linux'
run: cargo build -p rake-shortcuts --example shortcut-probe --locked
- name: Global shortcut lifecycle (X11)
if: runner.os == 'Linux'
run: xvfb-run -a env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 cargo run -p rake-shortcuts --example shortcut-probe --locked
run: xvfb-run -a -s '-screen 0 1280x800x24 -noreset' env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 target/debug/examples/shortcut-probe
- name: Default desktop lints
run: >-
cargo clippy -p rake-app -p rake-desktop-example -p rake-notes
Expand Down
35 changes: 34 additions & 1 deletion crates/rake-shortcuts/src/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ async fn x11_worker(
};

let setup = || {
let (connection, screen) = x11rb::connect(None).map_err(|_| Error::Unsupported)?;
let (connection, screen) = x11rb::connect(None).map_err(x11_connect_error)?;
let root = connection.setup().roots[screen].root;
let key = accelerator
.key
Expand Down Expand Up @@ -335,3 +335,36 @@ async fn x11_worker(
fn x11_error(error: impl std::fmt::Display) -> Error {
Error::Native(error.to_string())
}

fn x11_connect_error(error: x11rb::errors::ConnectError) -> Error {
match error {
x11rb::errors::ConnectError::DisplayParsingError(
x11rb::errors::DisplayParsingError::DisplayNotSet,
) => Error::Unsupported,
error => Error::Native(format!("could not connect to X11 display: {error}")),
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn only_an_unconfigured_display_is_unsupported() {
use x11rb::errors::{ConnectError, DisplayParsingError};

assert!(matches!(
x11_connect_error(ConnectError::DisplayParsingError(
DisplayParsingError::DisplayNotSet
)),
Error::Unsupported
));
let error = ConnectError::InvalidScreen;
let diagnostic = error.to_string();

assert!(matches!(
x11_connect_error(error),
Error::Native(message) if message.contains(&diagnostic)
));
}
}
34 changes: 19 additions & 15 deletions crates/rake/src/platform/preferences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,25 +91,29 @@ impl Preferences {

#[cfg(not(target_family = "wasm"))]
{
let root = self.root.clone();
let path = root.join(key);
let preferences = self.clone();
let key = key.to_owned();
let value = value.to_owned();

blocking::unblock(move || {
use std::io::Write;
std::fs::create_dir_all(&root)?;
let mut temporary = tempfile::NamedTempFile::new_in(&root)?;
blocking::unblock(move || preferences.set_blocking(&key, &value)).await
}
}

temporary.write_all(value.as_bytes())?;
temporary.as_file().sync_all()?;
temporary
.persist(path)
.map_err(|error| Error::Io(error.error))?;
#[cfg(not(target_family = "wasm"))]
pub(crate) fn set_blocking(&self, key: &str, value: &str) -> Result<(), Error> {
use std::io::Write;

Ok(())
})
.await
}
name(key)?;
std::fs::create_dir_all(&self.root)?;
let mut temporary = tempfile::NamedTempFile::new_in(&self.root)?;

temporary.write_all(value.as_bytes())?;
temporary.as_file().sync_all()?;
temporary
.persist(self.root.join(key))
.map_err(|error| Error::Io(error.error))?;

Ok(())
}

/// Removes one preference; removing a missing value succeeds.
Expand Down
28 changes: 20 additions & 8 deletions crates/rake/src/window_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ struct Inner {
preferences: Preferences,
records: RefCell<BTreeMap<String, SavedWindow>>,
loaded: std::cell::Cell<bool>,
writes: futures::lock::Mutex<()>,
writes: std::sync::Arc<futures::lock::Mutex<()>>,
}

impl std::fmt::Debug for WindowState {
Expand All @@ -73,7 +73,7 @@ impl WindowState {
preferences,
records: RefCell::new(BTreeMap::new()),
loaded: std::cell::Cell::new(false),
writes: futures::lock::Mutex::new(()),
writes: std::sync::Arc::new(futures::lock::Mutex::new(())),
}),
keys: Rc::new(|id| (id == WindowId(1)).then(|| "main".into())),
}
Expand Down Expand Up @@ -112,12 +112,12 @@ impl WindowState {

#[cfg(not(target_family = "wasm"))]
{
let _write = self.inner.writes.lock().await;
let write = self.inner.writes.clone().lock_owned().await;

self.load_locked().await?;
self.inner.records.borrow_mut().remove(key);

self.save_locked().await
self.save_locked(write).await
}
}

Expand All @@ -135,10 +135,22 @@ impl WindowState {
}

#[cfg(not(target_family = "wasm"))]
async fn save_locked(&self) -> Result<(), crate::platform::Error> {
async fn save_locked(
&self,
write: futures::lock::OwnedMutexGuard<()>,
) -> Result<(), crate::platform::Error> {
let value = placement::encode(&self.inner.records.borrow());

self.inner.preferences.set(PREFERENCE_KEY, &value).await
let preferences = self.inner.preferences.clone();

// Release serialization on the blocking thread, even when the UI stops
// polling the writer during shutdown.
blocking::unblock(move || {
let _write = write;

preferences.set_blocking(PREFERENCE_KEY, &value)
})
.await
}

#[cfg(all(feature = "gpui", not(target_family = "wasm")))]
Expand All @@ -159,9 +171,9 @@ impl WindowState {

#[cfg(all(feature = "gpui", not(target_family = "wasm")))]
async fn save(&self) {
let _write = self.inner.writes.lock().await;
let write = self.inner.writes.clone().lock_owned().await;

if let Err(error) = self.save_locked().await {
if let Err(error) = self.save_locked(write).await {
crate::warn!(
error_type = std::any::type_name_of_val(&error),
"window placement could not be saved"
Expand Down
22 changes: 18 additions & 4 deletions crates/rake/src/window_state/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ use crate::router::WindowId;

/// Coalesce events without postponing persistence indefinitely during a drag.
const SAVE_INTERVAL: Duration = Duration::from_millis(250);
// Allow slow synced writes beyond GPUI's 200 ms grace period without hanging exit.
const QUIT_SAVE_TIMEOUT: Duration = Duration::from_secs(3);
// Native transitions normally complete sooner; a rejected request must not freeze tracking.
const RESTORE_TIMEOUT: Duration = Duration::from_secs(2);

Expand All @@ -28,7 +30,7 @@ struct Driver {
policy: WindowState,
signals: Rc<Signals>,
windows: HashMap<gpui::WindowId, (String, Entity<Observer>, gpui::AnyWindowHandle)>,
_worker: gpui::Task<()>,
_worker: Option<gpui::Task<()>>,
_closed: Subscription,
_quit: Subscription,
}
Expand Down Expand Up @@ -228,21 +230,33 @@ pub(crate) fn install(policy: WindowState, cx: &mut gpui::App) {
});
}

let driver = cx.global::<Driver>();
let driver = cx.global_mut::<Driver>();

driver.signals.stopping.set(true);
driver.signals.changed.notify(usize::MAX);
driver.signals.final_save.notify(usize::MAX);
let policy = driver.policy.clone();

async move { policy.save().await }
driver._worker.take();

// GPUI cancels returned quit futures after 200 ms; give disk writes a
// separate bounded grace period before handing control back to shutdown.
if cx
.foreground_executor()
.block_with_timeout(QUIT_SAVE_TIMEOUT, policy.save())
.is_err()
{
crate::warn!("timed out saving window placement during quit");
}

async {}
});

cx.set_global(Driver {
policy,
signals,
windows: HashMap::new(),
_worker: worker,
_worker: Some(worker),
_closed: closed,
_quit: quit,
});
Expand Down
41 changes: 39 additions & 2 deletions crates/rake/src/window_state/native/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,22 @@ fn fullscreen_keeps_normal_bounds_and_quit_flushes_before_debounce() {
.expect("fullscreen test window")
});
app.simulate_window_resize(window, gpui::size(gpui::px(1920.), gpui::px(1080.)));
// Preferences use a real blocking pool; retain the wall-clock quit deadline
// without the test scheduler's randomized early poll cutoff.
// Hold the write serialization gate longer than GPUI's quit deadline, as a
// slow in-flight fsync can. Quit must drain it and still save the final bounds.
let write = app
.foreground_executor()
.block_test(policy.inner.writes.clone().lock_owned());
let slow_write = std::thread::spawn(move || {
let _write = write;

std::thread::sleep(gpui::SHUTDOWN_TIMEOUT * 2);
});
// Keep the real deadline without the test scheduler's randomized poll cutoff.
app.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
app.quit();
slow_write
.join()
.expect("slow write completed before quit returned");
let data = std::fs::read_to_string(directory.path().join(super::super::PREFERENCE_KEY))
.expect("quit awaits final preference write");

Expand All @@ -180,6 +192,31 @@ fn fullscreen_keeps_normal_bounds_and_quit_flushes_before_debounce() {
assert_eq!(records["main"].bounds.width, 750.);
}

#[test]
fn quit_returns_when_a_write_remains_locked_past_the_grace_period() {
let app = gpui::TestAppContext::single();
let (directory, policy) = policy();

app.executor().allow_parking();
app.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
app.update(|cx| install(policy.clone(), cx));
open(&app, WindowId(1));
let write = app
.foreground_executor()
.block_test(policy.inner.writes.clone().lock_owned());
let started = std::time::Instant::now();

app.quit();

assert!(started.elapsed() >= QUIT_SAVE_TIMEOUT);
assert!(!directory.path().join(super::super::PREFERENCE_KEY).exists());
assert!(
policy.inner.writes.try_lock().is_none(),
"quit returned while the write stayed locked"
);
drop(write);
}

#[test]
fn reset_serializes_with_queued_saves_and_preserves_other_windows() {
let app = gpui::TestAppContext::single();
Expand Down
1 change: 1 addition & 0 deletions docs/platform-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ silently registered. Repeated presses may be coalesced while the UI is busy.
the portal owns conflict resolution and user-approved bindings. Closing the
private D-Bus connection ends the session on unregister/drop, including pending
authorization. A missing portal returns Unsupported. Rake never bypasses it.
- On X11, an unset display returns Unsupported; connection failures retain the native diagnostic.
- Web, headless builds and hosts without the feature return explicit Unsupported.
`capabilities().global_shortcuts` reports support. On Linux it starts false;
await `global_shortcuts().available()` to refresh that shared capability snapshot
Expand Down
Loading