A print dialog with a preview, CUPS and the print portal, a Windows backend, and ltk::dirs for the user's folders
Printing. An app that wanted to print had nothing in ltk to ask the user where and how, nor to reach a printer. `ltk::print` (`src/print/`) is a dialog built as `FileChooser` is: the app holds a `PrintDialog`, puts its `view()` in its own and hands its `PrintDialogMsg`s to `update()`, which returns a `PrintEvent`; `wrap` makes the app's message of the dialog's, so the printer list reaches it through the app's `ChannelSender`. It offers the destination, the printers CUPS knows with their state and "Save as PDF", the number of copies, all pages or a range such as `1-3, 5, 8-`, the paper (A4, Letter, Legal, A3, A5), the orientation, the margins, the scale, two-sided printing, colour and background graphics, the copies, sides and colour only for a printer. `PrintOptions` holds what was chosen and survives between dialogs, `parse_pages` and `format_pages` read and write the ranges. On a desktop the dialog is a card with ltk's `dialog()`, the preview on the left and the settings on the right; `compact()` makes it a whole page for a phone. `.printer( name )` and `.save_as_pdf()` choose where it starts. The preview. With `.preview( true )` the dialog asks the app for one with `PrintEvent::Preview( options )` whenever a setting that moves the pages changes, and shows what the app hands back to `PrintDialogMsg::previewed`, a `Preview` of some pages as RGBA with the document's total, one page at a time with buttons to move between them, greyed when colour is off. While one is being rendered a new request waits and is sent only if the layout changed meanwhile, so turning the scale quickly does not stack renders; until the first arrives the sheet's box shows "Preparing the preview…", kept to the sheet's width so it does not push the settings aside. CUPS. `print/cups.rs` loads `libcups.so.2` with `dlopen` at first use, so ltk neither links against it nor needs its headers, and a system without CUPS only loses its printers. It uses the destinations API, which also lists the network's driverless printers that have no queue: `printers()` with the default first, `print( printer, title, options, pdf )` sending the PDF as one job with `copies`, `media` as a PWG name, `sides` and `print-color-mode`, `jobs()`, `cancel()` and `set_default()`, which writes the user's `lpoptions`. `ltk::print::send`, `list_printers`, `jobs`, `cancel_job` and `set_default` run them on a thread and answer through the app's sender; `ltk::print::blocking` exposes them as they are, for code that has its own thread, such as a portal backend. `print/none.rs` stands in on Windows, Android and the browser, where only saving as PDF is offered. The portal. An app in a Flatpak cannot reach the CUPS socket. When `/.flatpak-info` exists, the dialog shows nothing of its own: it calls `org.freedesktop.portal.Print.PreparePrint` with the options as GTK's print settings and page setup, and the portal's own dialog answers; `Destination::Portal` then carries its token, and `send` passes the PDF to `Print` through a memfd. The Response signal is subscribed to on the request's path before the call, so a quick answer is not missed. `print/gtk.rs` translates `PrintOptions` to and from GTK's keys (`n-copies`, `page-ranges` counted from zero, `duplex`, `use-color`, `scale` in percent, the paper by its PWG name and size in millimetres), which a portal backend uses for the other direction. zbus 4, the one accesskit_unix already brings, joins the `wayland` feature for it. The dialog's strings are in ltk's seven locales. `file_chooser::view::icon` is shared with the dialog. Windows. The `windows` feature runs `ltk::run` in a Win32 window on Windows 10 1703 or later, with Windows's own frame, drawn through ANGLE's EGL and OpenGL ES when `libEGL.dll` and `libGLESv2.dll` sit beside the executable and in software through GDI otherwise (`src/platform/windows/`). It sizes the window by `App::window_size_hint` at the display's DPI and follows per-monitor DPI changes at fractional scales and the accessibility text size; it takes the mouse, the wheel, touch through `WM_POINTER`, and keys with Windows's repeat, dead keys and AltGr; it has the system clipboard, the cursor's shape, full screen, and moves and resizes begun from the app's own chrome, and keeps drawing while the window is moved or resized. Themes, fonts, keyboard layouts and MIME globs come from `ltk\` beside the executable, which `ltk::resource_dir` returns there by default; the font fallback chain and the monospace face are Windows's own, the system face stays the embedded Sora, and the file chooser offers each drive's root. A Win32 message loop cannot wait on calloop, so the runtime's timers and channels go through the queue the web backend already used: `build.rs` sets `cfg( queued_sources )` for both, and `AppData::dispatch_sources` moves from the web backend to `event_loop/sources.rs`. `Canvas::present_to` presents a GPU frame stretched over a window that a fractional scale left a pixel off it, and `EglContext::new_windows` and `create_native_surface` give ANGLE's display and an `HWND`'s surface. `App::save_state` is saved into `%LOCALAPPDATA%\<app_id>\` every 30 seconds, on exit and when the user's session ends, and restored as on Wayland: the part of the Wayland session runtime that does not speak the protocol, deciding why the app starts and handing it its bytes, is now `session_state::bootstrap`, which both backends call, with the file modes and the check for a running instance done each platform's way. `RunError::Window` reports a window Windows refused. `make windows-deps` and `make windows-check` typecheck the backend from Debian, compiling std from `rust-src`. `docs/windows.md` describes building, what ships beside the executable and what the backend does. ltk::dirs. `home`, `data_home`, `config_home`, `cache_home` and `state_home`: XDG's on Linux, with their usual fallbacks under the home folder, and on Windows `USERPROFILE`, `APPDATA` for data and settings and `LOCALAPPDATA` for the cache and state, an `XDG_*` variable that is set winning everywhere. An app finds its files there instead of reading `HOME` and the XDG variables itself, which on Windows are unset; ltk's own lookups of themes, keyboard layouts, MIME globs, the file chooser's folders and the session state now go through it, and `state_dir` takes the base it is given, its tests with it. Docs. The links to `WidgetId` in the crate's, `types`' and `App`'s documentation name the struct, since the `const fn` of the same name made them ambiguous to rustdoc. `README.md` names the other backends and `CHANGELOG.md` records the Windows backend and `ltk::dirs`. Not done. The print dialog has no CHANGELOG entry nor a page in `docs/widgets.md`. Under the portal there is no preview, since the portal's dialog gets the document only at the end. The desktop card's settings column does not scroll, so with a list open in a low window it may not fit. Tests cover the page ranges and the translation to GTK's keys, not the dialog, CUPS or the portal. On Windows there are no overlays, secondary surfaces or subsurfaces, no preedit for the input method and no accessibility.
This commit is contained in:
+87
-36
@@ -1,20 +1,28 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-only
|
||||
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
|
||||
|
||||
//! On-disk session state: `$XDG_STATE_HOME/<app_id>/{session.json,state.bin}`.
|
||||
//! On-disk session state: `$XDG_STATE_HOME/<app_id>/{session.json,state.bin}`, on Windows `%LOCALAPPDATA%\<app_id>\` when `XDG_STATE_HOME` is unset.
|
||||
//!
|
||||
//! `session.json` carries the compositor session id, a clean-exit marker
|
||||
//! and the pid of the run that wrote it; `state.bin` holds the bytes the
|
||||
//! application returned from `App::save_state`. Everything is best effort:
|
||||
//! I/O failures are logged and never abort the application.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{ Path, PathBuf };
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{ Deserialize, Serialize };
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
/// How often a running app's state is saved, besides on a clean exit.
|
||||
pub( crate ) const SAVE_INTERVAL: Duration = Duration::from_secs( 30 );
|
||||
|
||||
/// Set to `1` by a shell that relaunches the app as part of a session restore.
|
||||
pub( crate ) const RESTORE_ENV: &str = "LTK_SESSION_RESTORE";
|
||||
|
||||
const SESSION_FILE: &str = "session.json";
|
||||
const STATE_FILE: &str = "state.bin";
|
||||
const FORMAT_VERSION: u32 = 1;
|
||||
@@ -57,33 +65,23 @@ pub( crate ) struct StateStore
|
||||
last_saved: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Resolve the state directory for `app_id`, or `None` when the id is unusable
|
||||
/// as a path component or no base directory can be determined.
|
||||
pub( crate ) fn state_dir(
|
||||
app_id: &str,
|
||||
xdg_state_home: Option<&OsStr>,
|
||||
home: Option<&OsStr>,
|
||||
) -> Option<PathBuf>
|
||||
/// The state directory for `app_id` under `base`, or `None` when the id is unusable as a path component or there is no base.
|
||||
pub( crate ) fn state_dir( app_id: &str, base: Option<PathBuf> ) -> Option<PathBuf>
|
||||
{
|
||||
if app_id.is_empty() || app_id.contains( '/' ) || app_id == "." || app_id == ".."
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let base = match xdg_state_home.filter( |v| !v.is_empty() )
|
||||
{
|
||||
Some( v ) => PathBuf::from( v ),
|
||||
None => PathBuf::from( home.filter( |v| !v.is_empty() )? ).join( ".local" ).join( "state" ),
|
||||
};
|
||||
Some( base.join( app_id ) )
|
||||
#[ cfg( windows ) ]
|
||||
if app_id.contains( [ '\\', ':' ] ) { return None; }
|
||||
Some( base?.join( app_id ) )
|
||||
}
|
||||
|
||||
impl StateStore
|
||||
{
|
||||
pub fn open( app_id: &str ) -> Option<Self>
|
||||
{
|
||||
let xdg = std::env::var_os( "XDG_STATE_HOME" );
|
||||
let home = std::env::var_os( "HOME" );
|
||||
let dir = state_dir( app_id, xdg.as_deref(), home.as_deref() );
|
||||
let dir = state_dir( app_id, crate::dirs::state_home() );
|
||||
if dir.is_none()
|
||||
{
|
||||
eprintln!( "ltk: session state disabled: cannot derive a state directory for app_id {app_id:?}" );
|
||||
@@ -95,6 +93,7 @@ impl StateStore
|
||||
{
|
||||
let mut builder = fs::DirBuilder::new();
|
||||
builder.recursive( true );
|
||||
#[ cfg( unix ) ]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode( 0o700 );
|
||||
@@ -223,28 +222,82 @@ impl StateStore
|
||||
fn write_atomic( path: &Path, bytes: &[u8] ) -> io::Result<()>
|
||||
{
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
|
||||
let mut tmp = path.as_os_str().to_owned();
|
||||
tmp.push( ".tmp" );
|
||||
let tmp = PathBuf::from( tmp );
|
||||
{
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.write( true )
|
||||
.create( true )
|
||||
.truncate( true )
|
||||
.mode( 0o600 )
|
||||
.open( &tmp )?;
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.write( true ).create( true ).truncate( true );
|
||||
#[ cfg( unix ) ]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode( 0o600 );
|
||||
}
|
||||
let mut f = options.open( &tmp )?;
|
||||
f.write_all( bytes )?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
fs::rename( &tmp, path )
|
||||
}
|
||||
|
||||
#[ cfg( unix ) ]
|
||||
fn pid_alive( pid: u32 ) -> bool
|
||||
{
|
||||
Path::new( "/proc" ).join( pid.to_string() ).exists()
|
||||
}
|
||||
|
||||
#[ cfg( windows ) ]
|
||||
fn pid_alive( pid: u32 ) -> bool
|
||||
{
|
||||
use windows_sys::Win32::Foundation::{ CloseHandle, STILL_ACTIVE };
|
||||
use windows_sys::Win32::System::Threading::{ GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION };
|
||||
|
||||
// SAFETY: the handle is checked for null and closed before returning; `code` is a place for the call to write.
|
||||
unsafe
|
||||
{
|
||||
let process = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, 0, pid );
|
||||
if process.is_null() { return false; }
|
||||
let mut code = 0;
|
||||
let alive = GetExitCodeProcess( process, &mut code ) != 0 && code == STILL_ACTIVE as u32;
|
||||
CloseHandle( process );
|
||||
alive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Before any window exists: read the restore hint from the environment, decide why the app is starting, hand it its saved bytes when that calls for them, and mark the run as live. `None` for the store when persistence is off: an unusable `app_id`, no state directory, or another instance running.
|
||||
pub( crate ) fn bootstrap<A: App>( app: &mut A ) -> ( Option<StateStore>, RestoreReason )
|
||||
{
|
||||
let env_restore = std::env::var_os( RESTORE_ENV ).is_some_and( |v| v == "1" );
|
||||
if std::env::var_os( RESTORE_ENV ).is_some()
|
||||
{
|
||||
// SAFETY: removing an env var is sound only when no other thread
|
||||
// is reading the environment concurrently. We are still in the
|
||||
// init phase before `set_channel_sender`, so the app has had
|
||||
// no opportunity to spawn worker threads yet.
|
||||
unsafe { std::env::remove_var( RESTORE_ENV ); }
|
||||
}
|
||||
|
||||
let Some( mut store ) = StateStore::open( app.app_id() ) else { return ( None, RestoreReason::Launch ) };
|
||||
let reason = match store.decide( env_restore )
|
||||
{
|
||||
Startup::Concurrent =>
|
||||
{
|
||||
eprintln!( "ltk: another instance of {} is running; session persistence disabled", app.app_id() );
|
||||
return ( None, RestoreReason::Launch );
|
||||
}
|
||||
Startup::Reason( reason ) => reason,
|
||||
};
|
||||
if reason != RestoreReason::Launch || app.restore_on_launch()
|
||||
{
|
||||
if let Some( bytes ) = store.load_state()
|
||||
{
|
||||
app.restore_state( bytes );
|
||||
}
|
||||
}
|
||||
store.mark_running();
|
||||
( Some( store ), reason )
|
||||
}
|
||||
|
||||
#[ cfg( test ) ]
|
||||
@@ -264,23 +317,20 @@ mod tests
|
||||
}
|
||||
|
||||
#[ test ]
|
||||
fn state_dir_prefers_xdg_then_home()
|
||||
fn state_dir_is_the_id_under_the_base()
|
||||
{
|
||||
let xdg = OsStr::new( "/tmp/xdg" );
|
||||
let home = OsStr::new( "/home/u" );
|
||||
assert_eq!( state_dir( "net.example.App", Some( xdg ), Some( home ) ), Some( PathBuf::from( "/tmp/xdg/net.example.App" ) ) );
|
||||
assert_eq!( state_dir( "net.example.App", None, Some( home ) ), Some( PathBuf::from( "/home/u/.local/state/net.example.App" ) ) );
|
||||
assert_eq!( state_dir( "net.example.App", Some( OsStr::new( "" ) ), Some( home ) ), Some( PathBuf::from( "/home/u/.local/state/net.example.App" ) ) );
|
||||
assert_eq!( state_dir( "net.example.App", None, None ), None );
|
||||
let base = || Some( PathBuf::from( "/home/u/.local/state" ) );
|
||||
assert_eq!( state_dir( "net.example.App", base() ), Some( PathBuf::from( "/home/u/.local/state/net.example.App" ) ) );
|
||||
assert_eq!( state_dir( "net.example.App", None ), None );
|
||||
}
|
||||
|
||||
#[ test ]
|
||||
fn state_dir_rejects_bad_ids()
|
||||
{
|
||||
let home = OsStr::new( "/home/u" );
|
||||
assert_eq!( state_dir( "", None, Some( home ) ), None );
|
||||
assert_eq!( state_dir( "a/b", None, Some( home ) ), None );
|
||||
assert_eq!( state_dir( "..", None, Some( home ) ), None );
|
||||
let base = || Some( PathBuf::from( "/home/u/.local/state" ) );
|
||||
assert_eq!( state_dir( "", base() ), None );
|
||||
assert_eq!( state_dir( "a/b", base() ), None );
|
||||
assert_eq!( state_dir( "..", base() ), None );
|
||||
}
|
||||
|
||||
#[ test ]
|
||||
@@ -331,6 +381,7 @@ mod tests
|
||||
assert!( !store.save_state_if_changed( None ) );
|
||||
}
|
||||
|
||||
#[ cfg( unix ) ]
|
||||
#[ test ]
|
||||
fn file_modes_are_private()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user