A text field that serves as an editor, a file chooser, ltk::files with callbacks, Text::fit, App::window_title, and a stack that keeps its children inside it
CI / build + test (push) Canceled after 0s
CI / cargo audit (push) Canceled after 0s

A multiline text field was a box for a few lines: it wrapped its whole value by shaping each character alone on every frame, every click and every caret motion, so a file of some size made it crawl; it drew a tab as the font's glyph for it, had no scroll bar, no page keys and no way to number its lines, kept no record of the view it showed, so once the cursor had left the first screen it stayed on the last row and the arrows moved the text, and an app could neither colour its text, type a tab with Tab, give it a face of its own, ask it to copy, cut, paste or select, nor hear where its cursor was. Notes, the Eydos text editor, needs all of it, and every app that opens or saves the user's files needed a dialog of its own.
Speed. `Canvas::measure_char` measures a character's advance once per font and size and keeps it (`text_shaping::char_advance_cached`, emptied with the shaped lines), and `compute_visual_lines` keeps the last four layouts by the value's hash and length, the row width, the size and the face, so a value is wrapped again only when one of them changes, and drawing, hit testing and caret motion over the same value wrap it once.
The view. `TextEdit::draw` returns the view it showed, which the frame keeps in `text_scroll`, so the view moves only when the cursor leaves it, and by the least; a `TextCommand::Select` no longer resets it. `Window::shown` gives the lines as the last frame showed them, wherever the cursor went since, and a press, the wheel, the scroll bar and the page keys act on them: a press that gave a field the focus, which puts its cursor at the end, landed where the view would have gone to show that cursor, near the end of the text, instead of on the character pressed. The cursor a scroll keeps is taken back to the value's length as the view's is, so a scroll made with the cursor at its end sentinel holds instead of going back to the cursor at once.
Tabs. In a multiline field a tab reaches the next stop, every four digits' widths, as four monospace columns are (`theme::TAB_COLUMNS`, `text_edit/tabs.rs`), when it is drawn, selected, clicked and crossed with the arrows. `TextEdit::tab_text( text )` has Tab type `text` while the field has the focus instead of moving the focus on; Shift+Tab still moves it back and Ctrl+Tab still reaches the app.
The scroll bar. A field whose lines do not all fit shows a scroll bar along its right edge (`Window::scrollbar`): its thumb is held and dragged, or a press on its track brings the thumb there, by pointer or touch, without moving the cursor (`AppData::text_scrollbar_grab`, `handle_text_scrollbar_press`, `handle_text_scrollbar_drag`); the pointer over it is the arrow rather than the text cursor, and a long press that holds it no longer opens the Copy / Cut / Paste menu.
Page Up and Page Down move the cursor of a multiline field by the lines on screen but one, at the same height on screen, and the view with it, to the start or the end from the first or the last page (`cursor_visual_page`, `handle_cursor_page`); Shift extends the selection, and with Ctrl, or in any other widget, the keys still reach the app. A key without Ctrl that types no text, such as F3, was dropped while a text field had the focus; it now goes to `App::on_key_with_modifiers`, as it does with no field focused.
The text as an editor's. `TextEdit::highlights( Arc<Vec<TextHighlight>> )` draws runs of a multiline value, byte ranges in order, in colours of their own, what no run covers in the field's colour and a run off a character boundary left out. `TextEdit::font( face )` lays a multiline field's text out in a face of its own at the field's size: wrapping, drawing, the selection, the cursor, clicks, tab stops and the arrows all measure through one `TextFont`, the size and the face, which `text_input_geometry` now gives the runtime's paths where it gave them the size; `Canvas::measure_char_with_font` is `measure_char` in another face. `ltk::monospace_font()` finds a monospace face, DejaVu Sans Mono from the app's resources, which a page and an APK carry, else the first of the system's installed, loaded once. `TextEdit::line_numbers( true )` numbers the lines in a column at the field's left, in the monospace face when there is one, as wide as the number of the last line needs, a wrapped line numbered on its first row and the cursor's in the text colour while the field has the focus; the text starts right of the column alike when drawn and in every runtime path, since they all lay it out in the rect `gutter::text_rect` gives. `borderless()` now also drops a multiline field's background and border.
Talking to the field. `App::take_text_command` hands a field, by its `WidgetId`, a `TextCommand` after the next frame: `Copy`, `Cut`, `Paste` and `SelectAll` through the paths the keys take, and `Select { start, end }`, which focuses the field, selects the range with its ends taken back to the value and to its characters' starts, and scrolls to it. `Reveal { start, end }` does the same without moving the focus, as a search does while its own field keeps the keys, and a multiline field without the focus now shows its selection dimmed (`theme::selection_inactive`). `TextEdit::on_cursor( |at| … )` sends the cursor's byte offset once it is placed and whenever it moves or the value changes length (`report_text_cursors`, after every frame), as an editor's status bar showing the line needs.
A file chooser. `ltk::FileChooser` (`src/file_chooser/`) picks a file to open or a folder and a name to save one as, over `ltk::files`, alike natively and in a browser. The app holds it, puts its `view()` in its own and hands its `FileChooserMsg`s to `update()`, which returns `Chosen::Path` or `Chosen::Cancelled` once the user chose; `wrap` makes the app's message of the chooser's, so its listings reach it through the app's `ChannelSender`. It offers the home folder, the xdg-user-dirs folders that exist, the root and the folders mounted in a browser, with a press there to mount another; it lists folders first, the hidden entries left out, each with its type's icon, a file with its size and the date of its last access or change, sorted as Crate sorts, by name, last access or size, each key in a direction of its own (`Sort`, `SortKey`, `Directions`). `dir` starts elsewhere, `filter( &[ "text/*" ] )` shows only some types of files, `compact( true )` puts the places behind a button for a phone, `sort` starts in an order kept from `current_sort`, and `take_focus_request` gives the field to focus. Saving asks before replacing a file and can create a folder; its errors are in the user's words, and its strings in ltk's seven locales. `files::mounts()` gives the folders mounted in a browser as the desktop last said, which the web backend now keeps. `docs/widgets.md` describes it and `examples/file_chooser.rs` shows it, in `make examples`.
ltk::files::callback. The operations of `ltk::files` with a function in place of a message (`list`, `stat`, `read`, `read_range`, `write`, `create_dir`, `rename`, `remove`, `remove_all`, `copy`, `copy_all`, `mount` and `unmount`), for code with no run loop's `ChannelSender` to take one, such as Prompt's session daemon, which in a browser runs in the page beside the window. `done` is called on ltk's worker thread natively and on the page's thread in a browser.
Closing. An app that keeps its window open in `on_close_requested`, to ask whether to save, was not drawn again, so its question appeared only at the next event, such as a press. Every close request, from the compositor, the title bar's close button, back and the browser, now goes through `AppData::request_close`, which draws the view again when the app refused it.
`App::window_title`. The main window's title, read when the window is made, which the title bar, the task switcher and the dock show; by default the `app_id`. A `ShellMode::Window` app was titled "ltk" on Wayland, whatever the app, with no way to name it but the deprecated `window_config`; in a browser its title was its `app_id`, and is now this.
`Text::fit` and `Text::valign`. `fit()` draws a text at the largest size up to its own at which it fits the rect the layout gives it, on one line within its width and height or, with `wrap`, all its lines within its height, so a text whose length varies, such as a calculator's display, neither overflows a box the window sizes nor needs its size worked out from the window and its content; its preferred size is still the one at its own size. `valign( VAlign )` places the lines at the top, the centre or the bottom of the rect.
A stack keeps its children inside it. A child that `Stack` aligned to an edge or the centre took its preferred size even when that was larger than the stack, so one aligned to the bottom started above the stack's top and one aligned to the right left of its left edge, drawn over whatever was there. Each child's preferred size is now capped by the stack's, less its margin, before it is aligned; children placed with `push_placed` and the offsets of `push_translated` are as they were.
Tests cover Tab with and without `tab_text`, the text commands, `Reveal` leaving the focus alone, a highlight into a character, `on_cursor` reporting once, a refused close drawing again, a key that types nothing reaching the app from a field, tab stops, a click on a tab, the kept layouts, the scroll bar, a view kept while the cursor moves inside it and after a scroll with the cursor at its sentinel, a click landing on the view shown, the page keys, the width of the line numbers, the file chooser's listing, filters, names, user folders, sizes, sorting and its open, save and replace flows, `Text::fit` and a stack's aligned children. `CHANGELOG.md` and `docs/widgets.md` describe the changes.
This commit is contained in:
2026-10-26 23:00:33 +01:00
parent 18a0e02249
commit 8882078743
62 changed files with 3191 additions and 185 deletions
+428
View File
@@ -0,0 +1,428 @@
// 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;
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(),
}
}