Files
ltk/src/file_chooser/mod.rs
T
admin 45b8ddd483
CI / build + test (push) Canceled after 0s
CI / cargo audit (push) Canceled after 0s
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.
2026-11-01 22:49:18 +01:00

429 lines
12 KiB
Rust

// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>
//! A dialog that picks a file to open, or a folder and a name to save one
//! as, over [`crate::files`], alike natively and in a browser. The app
//! holds it, puts its [`FileChooser::view`] in its own view, and hands its
//! messages to [`FileChooser::update`], which says when the user chose.
//!
//! ```rust,no_run
//! # use ltk::{ ChannelSender, Chosen, Element, FileChooser, FileChooserMsg };
//! # #[ derive( Clone ) ] enum Msg { Chooser( FileChooserMsg ) }
//! # struct App { chooser: Option<FileChooser<Msg>>, sender: ChannelSender<Msg> }
//! # impl App {
//! fn open( &mut self )
//! {
//! self.chooser = Some( FileChooser::open( &self.sender, Msg::Chooser ).filter( &[ "text/*" ] ) );
//! }
//!
//! fn update( &mut self, msg: Msg )
//! {
//! let Msg::Chooser( msg ) = msg;
//! let Some( chooser ) = &mut self.chooser else { return };
//! match chooser.update( msg )
//! {
//! Some( Chosen::Path( path ) ) => { self.chooser = None; /* read path */ }
//! Some( Chosen::Cancelled ) => self.chooser = None,
//! None => {}
//! }
//! }
//! # fn view( &self ) -> Element<Msg> { self.chooser.as_ref().unwrap().view() }
//! # }
//! ```
mod places;
mod sort;
pub( crate ) mod view;
#[ cfg( test ) ]
mod tests;
pub use places::{ home, Place, PlaceKind };
pub use sort::{ Directions, Sort, SortKey };
use std::io;
use std::path::{ Path, PathBuf };
use std::sync::Arc;
use std::time::SystemTime;
use crate::app::ChannelSender;
use crate::widget::Element;
use crate::files::{ self, Kind };
use crate::types::WidgetId;
/// The field with the name to save as.
pub const NAME: WidgetId = WidgetId( "ltk.file_chooser.name" );
/// The field with the name of a folder to create.
pub const FOLDER_NAME: WidgetId = WidgetId( "ltk.file_chooser.folder" );
#[ derive( Clone, Copy, Debug, PartialEq, Eq ) ]
pub enum Purpose
{
Open,
Save,
}
/// What the user chose.
#[ derive( Clone, Debug, PartialEq, Eq ) ]
pub enum Chosen
{
/// The file to open, or the one to save as, which the user agreed to replace if it was there.
Path( PathBuf ),
Cancelled,
}
/// What happens in a file chooser, for [`FileChooser::update`].
#[ derive( Clone, Debug ) ]
pub enum FileChooserMsg
{
Listed( PathBuf, Result<Vec<files::Entry>, String> ),
Enter( PathBuf ),
Up,
Pick( PathBuf ),
Name( String ),
Confirm,
Replace,
KeepFile,
NewFolder,
FolderName( String ),
CreateFolder,
CancelFolder,
FolderCreated( PathBuf, Result<(), String> ),
Mount,
/// `None` when the user dismissed the browser's picker.
Mounted( Result<files::Mount, Option<String>> ),
TogglePlaces,
ToggleSort,
SetSort( Sort ),
CloseNotice,
Cancel,
}
/// One entry of the folder shown.
#[ derive( Clone, Debug, PartialEq ) ]
pub( crate ) struct Item
{
pub name: String,
pub path: PathBuf,
pub is_dir: bool,
pub size: u64,
pub mime: Option<&'static str>,
pub modified: Option<SystemTime>,
pub accessed: Option<SystemTime>,
}
pub struct FileChooser<Msg>
{
purpose: Purpose,
dir: PathBuf,
/// Folders first, then the files the filter lets through, in `sort`'s order, the hidden ones left out.
items: Vec<Item>,
sort: Sort,
sort_open: bool,
name: String,
error: Option<String>,
loading: bool,
filters: Vec<String>,
compact: bool,
places_open: bool,
/// The file saving would replace, while the user is asked.
replacing: Option<PathBuf>,
/// The name of the folder being created.
new_folder: Option<String>,
notice: Option<String>,
focus: Option<WidgetId>,
sender: ChannelSender<Msg>,
wrap: Arc<dyn Fn( FileChooserMsg ) -> Msg + Send + Sync>,
}
impl<Msg: Clone + Send + 'static> FileChooser<Msg>
{
/// A chooser of a file to open, starting at the home folder. `wrap` makes the app's message of the chooser's own.
pub fn open( sender: &ChannelSender<Msg>, wrap: impl Fn( FileChooserMsg ) -> Msg + Send + Sync + 'static ) -> Self
{
Self::new( Purpose::Open, String::new(), sender, Arc::new( wrap ) )
}
/// A chooser of where to save a file, offering `name`, which it gives the focus.
pub fn save( sender: &ChannelSender<Msg>, wrap: impl Fn( FileChooserMsg ) -> Msg + Send + Sync + 'static, name: impl Into<String> ) -> Self
{
let mut chooser = Self::new( Purpose::Save, name.into(), sender, Arc::new( wrap ) );
chooser.focus = Some( NAME );
chooser
}
fn new( purpose: Purpose, name: String, sender: &ChannelSender<Msg>, wrap: Arc<dyn Fn( FileChooserMsg ) -> Msg + Send + Sync> ) -> Self
{
let mut chooser = Self
{
purpose,
dir: PathBuf::new(),
items: Vec::new(),
sort: Sort::default(),
sort_open: false,
name,
error: None,
loading: true,
filters: Vec::new(),
compact: false,
places_open: false,
replacing: None,
new_folder: None,
notice: None,
focus: None,
sender: sender.clone(),
wrap,
};
chooser.enter( home() );
chooser
}
/// Start at `dir` instead of the home folder.
pub fn dir( mut self, dir: impl Into<PathBuf> ) -> Self
{
self.enter( dir.into() );
self
}
/// Show only the files of these types besides the folders: MIME types such as `text/plain`, or a whole kind such as `image/*`.
pub fn filter( mut self, types: &[ &str ] ) -> Self
{
self.filters = types.iter().map( |t| t.to_string() ).collect();
let dir = self.dir.clone();
self.enter( dir );
self
}
/// In this order instead of by name, as the app kept it from [`Self::current_sort`].
pub fn sort( mut self, sort: Sort ) -> Self
{
self.set_sort( sort );
self
}
pub fn current_sort( &self ) -> Sort
{
self.sort
}
/// Laid out for a narrow screen: the places behind a button instead of beside the files.
pub fn compact( mut self, on: bool ) -> Self
{
self.compact = on;
self
}
pub fn purpose( &self ) -> Purpose
{
self.purpose
}
pub fn current_dir( &self ) -> &Path
{
&self.dir
}
/// The field to focus, once after it changed; an app hands it on from [`crate::App::take_focus_request`].
pub fn take_focus_request( &mut self ) -> Option<WidgetId>
{
self.focus.take()
}
pub fn view( &self ) -> Element<Msg>
{
view::view( self )
}
/// Take one of the chooser's messages; `Some` once the user chose.
pub fn update( &mut self, msg: FileChooserMsg ) -> Option<Chosen>
{
match msg
{
FileChooserMsg::Listed( dir, result ) => self.listed( &dir, result ),
FileChooserMsg::Enter( dir ) =>
{
self.places_open = false;
self.enter( dir );
}
FileChooserMsg::Up => if let Some( parent ) = self.parent() { self.enter( parent ); },
FileChooserMsg::Pick( path ) => match self.purpose
{
Purpose::Open => return Some( Chosen::Path( path ) ),
Purpose::Save =>
{
self.name = path.file_name().map( |name| name.to_string_lossy().into_owned() ).unwrap_or_default();
self.replacing = None;
self.focus = Some( NAME );
}
},
FileChooserMsg::Name( name ) =>
{
self.name = name;
self.replacing = None;
}
FileChooserMsg::Confirm =>
{
let target = self.target()?;
if self.replaces()
{
self.replacing = Some( target );
return None;
}
return Some( Chosen::Path( target ) );
}
FileChooserMsg::Replace => return self.replacing.take().map( Chosen::Path ),
FileChooserMsg::KeepFile =>
{
self.replacing = None;
self.focus = Some( NAME );
}
FileChooserMsg::NewFolder =>
{
self.new_folder = Some( String::new() );
self.focus = Some( FOLDER_NAME );
}
FileChooserMsg::FolderName( name ) => if let Some( folder ) = &mut self.new_folder { *folder = name; },
FileChooserMsg::CreateFolder =>
{
let path = self.new_folder_path()?;
self.new_folder = None;
let wrap = Arc::clone( &self.wrap );
let made = path.clone();
files::create_dir( path, &self.sender, move |result| wrap( FileChooserMsg::FolderCreated( made, result.map_err( |e| describe( &e ) ) ) ) );
}
FileChooserMsg::CancelFolder => self.new_folder = None,
FileChooserMsg::FolderCreated( path, result ) => match result
{
Ok( () ) => self.enter( path ),
Err( error ) => self.notice = Some( error ),
},
FileChooserMsg::Mount =>
{
let wrap = Arc::clone( &self.wrap );
files::mount( &self.sender, move |result| wrap( FileChooserMsg::Mounted( result.map_err( |e|
{
( e.kind() != io::ErrorKind::Interrupted ).then( || describe( &e ) )
} ) ) ) );
}
FileChooserMsg::Mounted( result ) => match result
{
Ok( mount ) => self.enter( mount.path ),
Err( Some( error ) ) => self.notice = Some( error ),
Err( None ) => {}
},
FileChooserMsg::TogglePlaces => self.places_open = !self.places_open,
FileChooserMsg::ToggleSort => self.sort_open = !self.sort_open,
FileChooserMsg::SetSort( sort ) => self.set_sort( sort ),
FileChooserMsg::CloseNotice => self.notice = None,
FileChooserMsg::Cancel => return Some( Chosen::Cancelled ),
}
None
}
fn msg( &self, msg: FileChooserMsg ) -> Msg
{
( self.wrap )( msg )
}
fn enter( &mut self, dir: PathBuf )
{
self.dir = dir.clone();
self.items.clear();
self.error = None;
self.loading = true;
self.replacing = None;
let wrap = Arc::clone( &self.wrap );
files::list( dir.clone(), &self.sender, move |result| wrap( FileChooserMsg::Listed( dir, result.map_err( |e| describe( &e ) ) ) ) );
}
/// The listing of `dir`, unless the chooser has moved on to another folder.
fn listed( &mut self, dir: &Path, result: Result<Vec<files::Entry>, String> )
{
if dir != self.dir { return; }
self.loading = false;
match result
{
Ok( entries ) =>
{
self.items = items( dir, entries, &self.filters, self.sort );
self.error = None;
}
Err( error ) => self.error = Some( error ),
}
}
fn set_sort( &mut self, sort: Sort )
{
self.sort = sort;
self.items.sort_by( |a, b| sort.compare( a, b ) );
}
fn parent( &self ) -> Option<PathBuf>
{
self.dir.parent().map( Path::to_path_buf )
}
/// Where to save, once there is a name.
fn target( &self ) -> Option<PathBuf>
{
valid_name( &self.name ).map( |name| self.dir.join( name ) )
}
/// Whether saving to the target would replace a file the folder holds.
fn replaces( &self ) -> bool
{
let name = self.name.trim();
self.items.iter().any( |item| !item.is_dir && item.name == name )
}
fn new_folder_path( &self ) -> Option<PathBuf>
{
valid_name( self.new_folder.as_deref()? ).map( |name| self.dir.join( name ) )
}
}
fn valid_name( name: &str ) -> Option<&str>
{
let name = name.trim();
( !name.is_empty() && name != "." && name != ".." && !name.contains( '/' ) ).then_some( name )
}
/// What a folder shows: the hidden entries and the files no filter takes left out, folders first, in `sort`'s order.
pub( crate ) fn items( dir: &Path, entries: Vec<files::Entry>, filters: &[ String ], sort: Sort ) -> Vec<Item>
{
let mut items: Vec<Item> = entries.into_iter()
.filter_map( |entry|
{
let name = entry.name.to_string_lossy().into_owned();
if name.starts_with( '.' ) { return None; }
let is_dir = entry.kind == Kind::Directory;
let mime = if is_dir { None } else { files::mime_type( &name ) };
if !is_dir && !filters.is_empty() && !mime.is_some_and( |mime| filters.iter().any( |f| matches( f, mime ) ) ) { return None; }
Some( Item { path: dir.join( &entry.name ), is_dir, size: entry.size, mime, modified: entry.modified, accessed: entry.accessed, name } )
} )
.collect();
items.sort_by( |a, b| sort.compare( a, b ) );
items
}
fn matches( filter: &str, mime: &str ) -> bool
{
match filter.strip_suffix( "/*" )
{
Some( kind ) => mime.split_once( '/' ).is_some_and( |( top, _ )| top == kind ),
None => filter == mime,
}
}
/// An error in the user's words.
fn describe( error: &io::Error ) -> String
{
match error.kind()
{
io::ErrorKind::NotFound => rust_i18n::t!( "file_chooser.not_found" ).to_string(),
io::ErrorKind::PermissionDenied => rust_i18n::t!( "file_chooser.denied" ).to_string(),
io::ErrorKind::AlreadyExists => rust_i18n::t!( "file_chooser.exists" ).to_string(),
io::ErrorKind::Unsupported => rust_i18n::t!( "file_chooser.unsupported" ).to_string(),
_ => error.to_string(),
}
}