From b364034c797ea670f427171c0edd246fad42cb1c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 21:05:08 -0700 Subject: [PATCH 1/4] ALI-2601: Format a removable drive from the sidebar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A drive's menu under Devices gets Format…, only for a drive that can come out (removable, USB or a card slot), never for one udisks2 marks as the system's, one holding a mounted system path (/, /boot, /home, /usr and the like) or swap, or one in a RAID or LVM set. The dialog asks for a name, checked against the format's limits (exFAT 15 characters, FAT32 11 in capitals, ext4 16 bytes), and a format: exFAT (the default), FAT32 or ext4. A format udisks2's Manager.CanFormat says can't be made is unavailable and names its package. The warning names the drive by make, model and size, and lists each partition with how much it holds. There's no typed confirmation. The keyboard starts on Cancel, Enter never presses Erase and Format (Space on it, or a click, does), and polkit asks for the password. The dialog is an alert whose description is the warning; the name's error is its description and marks it invalid; the formats are radio buttons. The format runs as a job: everything on the drive is unmounted and locked, then Block.Format "gpt" and PartitionTable.CreatePartitionAndFormat from 1 MiB filling the drive, then the new filesystem is mounted. It can be stopped until the erasing starts. The udisks2 stand-in serves Block.Format, CreatePartitionAndFormat and Manager.CanFormat, changing only its own pretend drives and writing down what it was asked. New tokens: radio, radio-dot, format-dialog-width, format-option-row. --- README.md | 12 +- crates/app/src/a11y.rs | 46 ++- crates/app/src/a11y_atspi.rs | 5 +- crates/app/src/app.rs | 367 ++++++++++++++++++-- crates/app/src/chooser.rs | 2 +- crates/app/src/drives.rs | 34 +- crates/app/src/format_drive.rs | 206 ++++++++++++ crates/app/src/main.rs | 25 +- crates/app/src/paint.rs | 56 ++++ crates/core/examples/udisks-standin.rs | 215 +++++++++++- crates/core/src/disks.rs | 445 ++++++++++++++++++++++++- crates/core/src/ops.rs | 8 + crates/core/src/places.rs | 2 +- crates/core/src/tokens.rs | 34 +- design/tokens.json | 24 +- tests/a11y_client.py | 2 +- tests/e2e.py | 270 ++++++++++++++- 17 files changed, 1672 insertions(+), 81 deletions(-) create mode 100644 crates/app/src/format_drive.rs diff --git a/README.md b/README.md index 78a85c7..657622f 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,8 @@ At run time, Gannet uses these: | `bsdtar` (libarchive) and `bubblewrap` | Extracting archives and Compress to ZIP | Each says what's missing | | `xdg-terminal-exec` | Open in terminal, in whichever terminal is set up | Open in terminal isn't offered | | `libmpv` (part of `mpv` on many systems) and `bubblewrap` | Video and sound previews | Videos show a message saying what's needed | -| `udisks2` | Mounting, unlocking and ejecting drives | Only drives that are already mounted show | +| `udisks2` | Mounting, unlocking, ejecting and formatting drives | Only drives that are already mounted show | +| `exfatprogs`, `dosfstools`, `e2fsprogs` | Formatting a drive as exFAT, FAT32 or ext4 (udisks2 runs them) | That format is shown as unavailable, with the package it needs | | `gvfs` | Network shares and connecting to servers: SFTP and FTP; SMB with `gvfs-smb` (which brings `smbclient`), NFS with `gvfs-nfs`, WebDAV with `gvfs-dnssd` | Connecting says GVfs isn't installed, and no shares show; an address for a missing backend says which package it needs | | `shared-mime-info` | Saying what a file is, like "PDF document" | Previews name types like `application/pdf` | | `poppler` (`pdfinfo`, `pdftoppm`) and `bubblewrap` | PDF previews | PDFs say what they are, or show a thumbnailer's picture | @@ -471,6 +472,15 @@ This goes through udisks2, which most Linux desktops run. Polkit decides what's asks for a password if the system says to. Before acting on a drive, Gannet checks it's still the one you picked, as another stick put in can take the same place. +To reuse a stick or card, right-click it and choose **Format…**. Give it a name, and pick exFAT +(the default, for Windows, macOS and Linux, and files of any size), FAT32 (for older devices, +files up to 4 GB) or ext4 (Linux only). The dialog says what will be erased: the drive by make +and size, and each partition on it with how much it holds. The keyboard starts on Cancel, and +Enter never erases: choose Erase and Format with the pointer, or Tab to it and press Space. +The system then asks for your password. The whole drive gets a new partition table and one +partition, which is mounted when it's done. Format is only offered for drives that can come +out, never for one udisks2 marks as the system's or one the system is mounted from or swaps to. + ## Network shares To connect to a server, type its address in the path bar (Ctrl+L), like diff --git a/crates/app/src/a11y.rs b/crates/app/src/a11y.rs index 8ca7229..dc4513e 100644 --- a/crates/app/src/a11y.rs +++ b/crates/app/src/a11y.rs @@ -103,6 +103,11 @@ pub const SERVER_USER: u64 = 37; pub const SERVER_DOMAIN: u64 = 38; /// The recent servers offered under the path bar, and each by its place among them. pub const SUGGESTIONS: u64 = 39; +/// The format dialog's name, its group of formats, and each format by its place in +/// `FsKind::ALL`. +pub const FORMAT_NAME: u64 = 40; +pub const FORMAT_KINDS: u64 = 41; +pub const FORMAT_KIND0: u64 = 42; pub const SUGGESTION0: u64 = 1 << 21; pub const MENU_ITEM0: u64 = 1 << 17; pub const DIALOG_BUTTON0: u64 = 1 << 18; @@ -136,6 +141,8 @@ pub enum Role { PasswordText, Menu, MenuItem, + /// One of a group of choices, of which one is picked: its `checked`. + RadioButton, } /// A thing a part does when a screen reader asks: its name and description, as AT-SPI has @@ -1058,13 +1065,14 @@ fn dialog(app: &mut App) -> Option<(Vec, Modal, u64)> { let r = app.dialog_rect_for(&d); let (title, message) = app.dialog_text(&d); let rects = app.dialog_button_rects(&d); - let default = DIALOG_BUTTON0 + App::dialog_default(&d) as u64; + // The format dialog has no default while the keyboard isn't on Cancel. + let default = Some(App::dialog_default(&d)).filter(|&i| i < App::dialog_buttons(&d).len()).map(|i| DIALOG_BUTTON0 + i as u64); // A question a job just asked, as a clash, takes no answer for a moment, as with the // keyboard and the pointer, but its buttons aren't drawn as unavailable meanwhile, and aren't // said to be: a screen reader would read "grayed" as the dialog opens, and never hear that // it's over. The server refuses a press meanwhile, as the app would drop it. let mut parts = Vec::new(); - let mut has = default; + let mut has = default.unwrap_or(DIALOG); match &d { Dialog::Conflict { apply_to_all, .. } => { let mut check = Node::new(DIALOG_CHECK, Role::CheckBox, "Do the same for the rest", app.dialog_check_rect(), DIALOG).doing(Action::new("toggle", "Answer the rest the same way", "a")); @@ -1110,6 +1118,32 @@ fn dialog(app: &mut App) -> Option<(Vec, Modal, u64)> { Stop::Button(i) => DIALOG_BUTTON0 + i as u64, }; } + Dialog::Format(a) => { + use crate::format_drive::Stop; + let l = app.format_layout(a); + // The name, described by why it can't be used or by the format's rule for names, so + // the error is heard with the field it's about. + let mut name = Node::new(FORMAT_NAME, Role::Entry, "Name", l.name, DIALOG).described(a.name_line()); + name.field = Some(a.name.clone()); + let kinds: Vec = gannet_core::disks::FsKind::ALL + .into_iter() + .zip(&l.kinds) + .enumerate() + .map(|(i, (kind, rect))| { + let mut n = Node::new(FORMAT_KIND0 + i as u64, Role::RadioButton, kind.name(), *rect, FORMAT_KINDS).described(a.note(kind)).enabled(a.missing(kind).is_none()).doing(click("Choose it", "")); + n.checked = Some(a.kind == kind); + n + }) + .collect(); + let group = Rect::new(l.kinds_label.x, l.kinds_label.y, l.name.right() - l.kinds_label.x, l.kinds.iter().map(|r| r.h).sum()); + parts.extend([name, Node::new(FORMAT_KINDS, Role::Panel, "Format", group, DIALOG).with_children(kinds.iter().map(|n| n.id).collect())]); + parts.extend(kinds); + has = match a.focus { + Stop::Name => FORMAT_NAME, + Stop::Kind => FORMAT_KIND0 + gannet_core::disks::FsKind::ALL.iter().position(|k| *k == a.kind).unwrap_or(0) as u64, + Stop::Button(i) => DIALOG_BUTTON0 + i as u64, + }; + } Dialog::RenameMany(rm) => { let l = app.rename_layout(rm.names.len()); let mut find = Node::new(RENAME_FIND, Role::Entry, "Find", l.find, DIALOG); @@ -1135,19 +1169,21 @@ fn dialog(app: &mut App) -> Option<(Vec, Modal, u64)> { _ => {} } for (i, (b, rect)) in App::dialog_buttons(&d).iter().zip(rects).enumerate() { - // The rename dialog's Rename waits until something changes and nothing clashes. - let can = !matches!(&d, Dialog::RenameMany(rm) if i == 0 && !rm.can_rename()); + // The rename dialog's Rename waits until something changes and nothing clashes, and the + // format dialog's Erase and Format until the name fits the format. + let can = !matches!(&d, Dialog::RenameMany(rm) if i == 0 && !rm.can_rename()) && !matches!(&d, Dialog::Format(a) if i == 0 && a.ready().is_none()); let keys = if b.key == "Esc" { "Escape" } else { b.key }; parts.push(Node::new(DIALOG_BUTTON0 + i as u64, Role::PushButton, b.label.as_ref(), rect, DIALOG).enabled(can).doing(click("Press it", keys))); } // A login is a form to fill in; a question that has to be answered first is an alert. + // Formatting a drive asks before erasing it, so it's an alert, and its warning is heard. let role = if matches!(&d, Dialog::Unlock { .. } | Dialog::RenameMany(_)) || matches!(&d, Dialog::Server(a) if a.is_login()) { Role::Dialog } else { Role::Alert }; let kids = parts.iter().filter(|n| n.parent == DIALOG).map(|n| n.id).collect(); // Lines drawn one under another are heard as one. parts.insert(0, Node::new(DIALOG, role, title, r, FRAME).described(message.replace('\n', " ")).with_children(kids)); let asked = matches!(d, Dialog::Conflict { .. } | Dialog::Expands { .. } | Dialog::Server(_)).then(|| app.dialog_asked()).flatten(); app.dialog = Some(d); - Some((parts, Modal { id: DIALOG, default: Some(default), asked }, has)) + Some((parts, Modal { id: DIALOG, default, asked }, has)) } /// The list's columns, placed as `paint_header` draws them. Recent, the Trash and search diff --git a/crates/app/src/a11y_atspi.rs b/crates/app/src/a11y_atspi.rs index 5938f16..5e4864f 100644 --- a/crates/app/src/a11y_atspi.rs +++ b/crates/app/src/a11y_atspi.rs @@ -253,6 +253,7 @@ fn role_of(r: Role) -> (u32, &'static str) { Role::PasswordText => (40, "password text"), Role::Menu => (33, "menu"), Role::MenuItem => (35, "menu item"), + Role::RadioButton => (44, "radio button"), } } @@ -600,7 +601,7 @@ impl Ctx { Role::ListItem => on.extend([STATE_SELECTABLE, STATE_FOCUSABLE]), Role::Menu => on.push(STATE_FOCUSABLE), Role::PushButton => on.push(STATE_FOCUSABLE), - Role::CheckBox => on.extend([STATE_FOCUSABLE, STATE_CHECKABLE]), + Role::CheckBox | Role::RadioButton => on.extend([STATE_FOCUSABLE, STATE_CHECKABLE]), Role::Entry => on.extend([STATE_FOCUSABLE, STATE_EDITABLE, STATE_SINGLE_LINE, STATE_SELECTABLE_TEXT]), Role::PasswordText => on.extend([STATE_FOCUSABLE, STATE_EDITABLE, STATE_SINGLE_LINE]), Role::MenuItem => on.extend([STATE_SELECTABLE, STATE_FOCUSABLE]), @@ -820,7 +821,7 @@ impl Ctx { Target::Fixed(n) if Self::is_place(n) => self.show_place(n, snap), // A part of the menu or dialog that's open, which moving to picks, as the // keyboard or pointer does. - Target::Fixed(n) if snap.modal.is_some() && n.enabled && matches!(n.role, Role::MenuItem | Role::PushButton | Role::Entry) => { + Target::Fixed(n) if snap.modal.is_some() && n.enabled && matches!(n.role, Role::MenuItem | Role::PushButton | Role::Entry | Role::RadioButton) => { self.hub.send(Msg::A11y(Act::Focus(n.id))); true } diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 7be24ed..d597eae 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -17,7 +17,7 @@ use gannet_core::mounts::Mount; use gannet_core::trash; use gannet_core::ops::{self, Answer, Choice, Conflict, Engine, Expands, Job, Request, Undo}; use gannet_core::watch::Watch; -use gannet_core::disks::{DiskError, Volume}; +use gannet_core::disks::{DiskError, FormatTarget, FsKind, Volume}; use gannet_core::gvfs::{ConnectError, Share, ShareError}; use gannet_core::servers::{self, Address}; use gannet_core::bookmarks::{self, Spot}; @@ -31,6 +31,7 @@ use xkbcommon::xkb::keysyms as k; use crate::canvas::Rect; use crate::connect::{ServerAsk, Stop as ServerStop, Suggest}; use crate::field::Field; +use crate::format_drive::{FormatAsk, Stop as FormatStop}; use crate::icons::Icons; use crate::preview::{self, Preview}; use crate::rename_many::{Focus, RenameMany}; @@ -99,6 +100,10 @@ pub enum Msg { NoUdisks, /// A mount, unlock, unmount or eject has finished: where it's mounted, for the first two. DiskDone { volume: Volume, doing: Doing, result: Result, DiskError> }, + /// What's on a drive picked to be formatted, or why it can't be. + FormatLooked { volume: Volume, result: Result }, + /// Formatting has finished: where the new filesystem is mounted, if it could be. + FormatDone { job: u64, target: FormatTarget, kind: FsKind, result: Result, DiskError> }, /// The network shares GVfs has connected now. Shares(Vec), /// A share has been disconnected, or couldn't be. @@ -230,6 +235,8 @@ enum JobKind { Undo, /// What it put back goes on the undo list again. Redo, + /// Formatting a drive, which udisks2 does: nothing to undo, and the undo list is kept. + Format, } /// A question that has to be answered before anything else happens. @@ -250,6 +257,8 @@ pub enum Dialog { RenameMany(Box), /// A password, or a question, GVfs asks while connecting to a server. Server(Box), + /// Formatting a drive: its new name and format, and what will be erased. + Format(Box), } /// A question a job is waiting on, kept while another dialog is open. @@ -269,6 +278,20 @@ pub struct RenameLayout { pub row_h: i32, } +/// Where the format dialog's parts are. See [`App::format_layout`]. +pub struct FormatLayout { + pub rect: Rect, + /// The warning's lines, under the title. + pub lines: Vec, + pub name: Rect, + /// The line under the name: why it can't be used, or the format's rule for names. + pub name_line: Rect, + /// Where the formats' heading is drawn, beside the first. + pub kinds_label: Rect, + /// Each format's row, in `FsKind::ALL`'s order. + pub kinds: Vec, +} + /// Where a server dialog's parts are. See [`App::server_layout`]. pub struct ServerLayout { pub rect: Rect, @@ -329,6 +352,10 @@ pub enum Hit { DialogField(Focus), /// A field, or the "Remember password" box, in a server's login dialog. ServerField(ServerStop), + /// The format dialog's name field. + FormatName, + /// One of the format dialog's formats, by its place in `FsKind::ALL`. + FormatKind(usize), /// A recent server offered under the path bar. Suggestion(usize), PreviewBody, @@ -535,6 +562,7 @@ pub enum Action { OpenDrive, Unmount, Eject, + FormatDrive, /// For the network share whose menu it is. OpenShare, Disconnect, @@ -1664,6 +1692,8 @@ impl App { Msg::NoUdisks => self.set_volumes(Vec::new(), false), Msg::A11y(act) => self.a11y_act(act), Msg::DiskDone { volume, doing, result } => self.drive_done(volume, doing, result), + Msg::FormatLooked { volume, result } => self.format_looked(volume, result), + Msg::FormatDone { job, target, kind, result } => self.format_done(job, target, kind, result), Msg::Shares(shares) => self.set_shares(shares), Msg::ShareDone { share, result } => self.share_done(share, result), Msg::ServerAsks(asked) => self.server_asks(asked), @@ -1734,6 +1764,13 @@ impl App { _ => None, }; } + // The format dialog's name, while it has the keyboard. + if matches!(self.dialog, Some(Dialog::Format(_))) { + return match &mut self.dialog { + Some(Dialog::Format(a)) if a.focus == FormatStop::Name => Some(&mut a.name), + _ => None, + }; + } match &mut self.edit { Edit::Path(f) | Edit::Filter(f) | Edit::NewFolder(f) | Edit::Rename { field: f, .. } => Some(f), // The rename dialog's field with the keyboard. @@ -1951,12 +1988,7 @@ impl App { self.invalidate_all(); } } - Act::Press(id) if id >= STOP0 => { - if let Some(j) = self.jobs.iter().find(|j| j.job.id == id - STOP0) { - j.job.cancel(); - self.invalidate(self.layout().notices); - } - } + Act::Press(id) if id >= STOP0 => self.stop_job(id - STOP0), Act::Press(_) | Act::Choose(..) | Act::Wake => {} Act::OpenCrumb(dir, i) => { if *dir == self.dir @@ -2009,7 +2041,7 @@ impl App { /// What a screen reader asked of the dialog that's open: a button pressed, which waits out a /// new clash as a key does, the box ticked, or the keyboard moved to a part. fn a11y_dialog_act(&mut self, act: crate::a11y::Act) { - use crate::a11y::{Act, DIALOG_BUTTON0, DIALOG_CHECK, PASSPHRASE, RENAME_FIND, RENAME_REPLACE, SERVER_DOMAIN, SERVER_USER}; + use crate::a11y::{Act, DIALOG_BUTTON0, DIALOG_CHECK, FORMAT_KIND0, FORMAT_NAME, PASSPHRASE, RENAME_FIND, RENAME_REPLACE, SERVER_DOMAIN, SERVER_USER}; let guarded = self.dialog_guarded(); let edit_gen = self.edit_gen; let Some(d) = self.dialog.as_mut() else { return }; @@ -2019,6 +2051,18 @@ impl App { let Some(i) = button(id).filter(|&i| Self::dialog_buttons(d).get(i).is_some_and(|b| b.label == name)) else { return }; self.press_dialog_button(i); } + // A format picked, as clicking it does. + Act::Press(id) if (FORMAT_KIND0..FORMAT_KIND0 + FsKind::ALL.len() as u64).contains(&id) => { + let Dialog::Format(a) = d else { return }; + a.pick(FsKind::ALL[(id - FORMAT_KIND0) as usize]); + a.focus = FormatStop::Kind; + } + // Its name: given the keyboard, then changed as typing would, and checked. + Act::EditText(FORMAT_NAME, asked, op) if asked == edit_gen => { + let Dialog::Format(a) = d else { return }; + a.focus = FormatStop::Name; + return self.a11y_edit(op); + } Act::Press(DIALOG_CHECK) if !guarded => match d { Dialog::Conflict { apply_to_all, .. } => *apply_to_all = !*apply_to_all, Dialog::Server(a) => a.toggle_save(), @@ -2076,6 +2120,9 @@ impl App { (Dialog::RenameMany(rm), RENAME_FIND) => rm.focus = Focus::Find, (Dialog::RenameMany(rm), RENAME_REPLACE) => rm.focus = Focus::Replace, (Dialog::RenameMany(rm), id) if button(id).is_some_and(|i| i < n) => rm.focus = Focus::Button(button(id).unwrap_or(0)), + (Dialog::Format(a), FORMAT_NAME) => a.focus = FormatStop::Name, + (Dialog::Format(a), id) if (FORMAT_KIND0..FORMAT_KIND0 + FsKind::ALL.len() as u64).contains(&id) => a.focus = FormatStop::Kind, + (Dialog::Format(a), id) if button(id).is_some_and(|i| i < n) => a.focus = FormatStop::Button(button(id).unwrap_or(0)), (Dialog::Server(a), id) => { let stop = match id { SERVER_USER => ServerStop::User, @@ -2426,10 +2473,11 @@ impl App { self.share_act(share); } } - Action::OpenDrive | Action::Unmount | Action::Eject => { + Action::OpenDrive | Action::Unmount | Action::Eject | Action::FormatDrive => { let Some(v) = self.drive_menu.take() else { return }; match a { Action::OpenDrive => self.open_volume(v), + Action::FormatDrive => self.look_to_format(v), Action::Unmount => { self.drive_act(v, Doing::Unmount); } @@ -3277,6 +3325,11 @@ impl App { Dialog::ConfirmReplace { .. } => vec![b("Replace", "", true), b("Cancel", "Esc", false)], Dialog::Unlock { .. } => vec![b("Unlock", "", false), b("Cancel", "Esc", false)], Dialog::RenameMany(_) => vec![b("Rename", "", false), b("Cancel", "Esc", false)], + // No letter, and Enter never presses it: erasing a drive takes a deliberate choice. + Dialog::Format(_) => { + let [erase, cancel] = FormatAsk::buttons(); + vec![DialogButton { label: erase, key: "", danger: true }, DialogButton { label: cancel, key: "Esc", danger: false }] + } // Escape cancels, whatever the last button says. Dialog::Server(a) => { let labels = a.buttons(); @@ -3340,6 +3393,7 @@ impl App { } Dialog::RenameMany(d) => (d.title(), d.summary().0), Dialog::Server(a) => (a.title(), a.body()), + Dialog::Format(a) => (a.title(), a.warning()), } } @@ -3350,6 +3404,9 @@ impl App { Dialog::Conflict { at, .. } | Dialog::Expands { at, .. } | Dialog::ConfirmDelete { at, .. } | Dialog::ConfirmQuit { at } | Dialog::Unlock { at, .. } | Dialog::ConfirmReplace { at, .. } => *at, Dialog::RenameMany(d) => if let Focus::Button(i) = d.focus { i } else { 0 }, Dialog::Server(a) => a.default_button(), + // Enter presses only Cancel, and only while it has the keyboard. No button is the + // default otherwise. + Dialog::Format(a) => if a.focus == FormatStop::Button(crate::format_drive::CANCEL) { crate::format_drive::CANCEL } else { usize::MAX }, } } @@ -3473,6 +3530,23 @@ impl App { self.start_job(Request::RenameMany { renames: d.renames() }); } } + Dialog::Format(mut a) => { + if i == crate::format_drive::ERASE { + match a.ready() { + Some((kind, label)) => self.start_format(*a, kind, label), + // What's stopping it is said where it is, and the keyboard goes there. + None => { + a.focus = if a.name.error.is_some() { FormatStop::Name } else { FormatStop::Kind }; + self.edit_gen += 1; + self.dialog = Some(Dialog::Format(a)); + self.invalidate_all(); + return; + } + } + } + // A paste asked for in its name mustn't land in a field after it. + self.edit_gen += 1; + } Dialog::Server(a) => { let reply = a.answer_for(i); let connect = a.connect; @@ -3551,6 +3625,9 @@ impl App { if matches!(self.dialog, Some(Dialog::Server(_))) { return self.server_dialog_key(sym, utf8, m); } + if matches!(self.dialog, Some(Dialog::Format(_))) { + return self.format_dialog_key(sym, utf8, m); + } let Some(d) = self.dialog.as_mut() else { return }; let buttons = Self::dialog_buttons(d); let n = buttons.len(); @@ -3600,7 +3677,7 @@ impl App { let at = match d { Dialog::Conflict { at, .. } | Dialog::Expands { at, .. } | Dialog::ConfirmDelete { at, .. } | Dialog::ConfirmQuit { at } | Dialog::Unlock { at, .. } | Dialog::ConfirmReplace { at, .. } => at, // Have their own keys, above. - Dialog::RenameMany(_) | Dialog::Server(_) => return, + Dialog::RenameMany(_) | Dialog::Server(_) | Dialog::Format(_) => return, }; match sym { k::KEY_Left => *at = (*at + n - 1) % n, @@ -3642,6 +3719,7 @@ impl App { match d { Dialog::RenameMany(rm) => self.rename_rect(rm.names.len()), Dialog::Server(a) => self.server_layout(a).rect, + Dialog::Format(a) => self.format_layout(a).rect, Dialog::Conflict { .. } | Dialog::Unlock { .. } => self.dialog_rect(), _ => self.dialog_rect_sized(false), } @@ -3780,7 +3858,8 @@ impl App { self.notice(format!("Couldn't {} “{}”: udisks2 isn't running", doing.verb(), Self::drive_name(&v))); return false; }; - if self.drives_busy.contains(&v.block) { + // Nothing else is done to a drive while it's formatted. + if self.drives_busy.contains(&v.block) || self.drives_busy.contains(&v.drive) { return false; } self.drives_busy.push(v.block.clone()); @@ -3842,7 +3921,7 @@ impl App { /// Closes the dialog, and shows the next question a job is waiting on, if there is one. fn close_dialog(&mut self) { // A paste asked for in a passphrase prompt mustn't land in a field after it. - if matches!(self.dialog, Some(Dialog::Unlock { .. } | Dialog::Server(_))) { + if matches!(self.dialog, Some(Dialog::Unlock { .. } | Dialog::Server(_) | Dialog::Format(_))) { self.edit_gen += 1; } self.dialog = None; @@ -3858,6 +3937,12 @@ impl App { MenuItem { label: if v.unlocked && v.mount.is_none() { "Lock" } else { "Unmount" }, keys: "", action: Action::Unmount, enabled: v.mount.is_some() || v.unlocked }, MenuItem { label: "Eject", keys: "", action: Action::Eject, enabled: v.removable }, ]; + // Only for a drive meant to come out, never the system's (`Snapshot::format_refusal`), and + // not in a chooser, which another program is waiting on. + let mut items = items; + if v.formattable && self.chooser.is_none() { + items.push(MenuItem { label: "Format…", keys: "", action: Action::FormatDrive, enabled: !self.drives_busy.contains(&v.drive) }); + } self.drive_menu = Some(v); self.menu = Some(Menu { items, x, y, at: usize::MAX }); self.invalidate_all(); @@ -3880,6 +3965,13 @@ impl App { { self.close_dialog(); } + // So has the drive about to be formatted, or another is in its place. + if let Some(Dialog::Format(a)) = &self.dialog + && !volumes.iter().any(|v| v.drive == a.target.drive && v.identity == a.target.identity) + && leave + { + self.close_dialog(); + } let mut places = self.standard_places.clone(); places.extend(self.pins.iter().cloned()); places.extend(gannet_core::places::all_disk_places(&volumes, &mounts, Self::drive_name)); @@ -3965,6 +4057,165 @@ impl App { self.invalidate_all(); } + // ---- Formatting drives ---- + + /// Starts looking at a volume's drive to format it. The dialog opens once what's on it and + /// which formats can be made are known (`format_looked`). + fn look_to_format(&mut self, v: Volume) { + let Some(address) = self.system_bus.clone() else { + self.notice(format!("Couldn't format “{}”: udisks2 isn't running", Self::drive_name(&v))); + return; + }; + if self.drives_busy.contains(&v.drive) { + return; + } + crate::drives::look_to_format(self.hub.clone(), address, v); + } + + /// Opens the format dialog, keyboard on Cancel, unless another question is open meanwhile. + fn format_looked(&mut self, volume: Volume, result: Result) { + match result { + Ok(target) if self.dialog.is_none() && !self.drives_busy.contains(&target.drive) => { + // A paste asked for before mustn't land in its name. + self.edit_gen += 1; + self.dialog = Some(Dialog::Format(Box::new(FormatAsk::new(target)))); + } + Ok(_) | Err(DiskError::Cancelled) => {} + Err(e) => self.notice(format!("Couldn't format “{}”: {e}", Self::drive_name(&volume))), + } + self.invalidate_all(); + } + + /// Formats the drive, as a job: the window lets go of every folder on it first, and nothing + /// else is done to it until it's finished. + fn start_format(&mut self, a: FormatAsk, kind: FsKind, label: String) { + let Some(address) = self.system_bus.clone() else { + self.notice(format!("Couldn't format “{}”: udisks2 isn't running", a.drive_name())); + return; + }; + let drive = a.target.drive.clone(); + if self.drives_busy.iter().any(|b| *b == drive || self.volumes.iter().any(|v| v.drive == drive && v.block == *b)) { + self.notice(format!("Couldn't format “{}”: something's already under way on it. Try again in a moment", a.drive_name())); + return; + } + self.drives_busy.push(drive.clone()); + let mounts: Vec = self.volumes.iter().filter(|v| v.drive == drive).filter_map(|v| v.mount.clone()).collect(); + self.let_go_of(&mounts); + let job = self.engine.outside_job(format!("Formatting “{}” as {}", a.drive_name(), kind.name())); + self.jobs.push(JobView { job: job.clone(), started: Instant::now(), kind: JobKind::Format, selection_epoch: self.selection_epoch, change_epoch: self.change_epoch, say_made: false }); + crate::drives::format(self.hub.clone(), address, a.target, kind, label, job); + self.invalidate_all(); + } + + /// A format has finished. The drive shows under Devices by its new name as udisks2 says so. + fn format_done(&mut self, id: u64, target: FormatTarget, kind: FsKind, result: Result, DiskError>) { + self.drives_busy.retain(|b| *b != target.drive); + let view = self.jobs.iter().position(|j| j.job.id == id).map(|i| self.jobs.remove(i)); + let stopped = view.as_ref().is_some_and(|v| v.job.is_cancelled()); + if self.jobs_ended.len() >= 16 { + self.jobs_ended.remove(0); + } + self.jobs_ended.push((id, result.is_ok())); + let name = FormatAsk::new(target).drive_name(); + match result { + Ok(_) => self.note(format!("Formatted “{name}” as {}", kind.name())), + // Stopped before anything was erased. + Err(DiskError::Cancelled) if stopped => self.note(format!("Stopped formatting “{name}”. Nothing was erased")), + // The user said no at polkit's prompt, and knows. + Err(DiskError::Cancelled) => {} + Err(e) => self.notice(format!("Couldn't format “{name}”: {e}")), + } + self.clamp_scroll(); + self.invalidate_all(); + if self.quit_when_idle && self.jobs.is_empty() { + self.cmds.push(Cmd::Quit); + } + } + + /// Keys in the format dialog. Tab goes round the name, the formats and the buttons; the + /// arrows pick among the formats; Space presses the button with the keyboard. Enter presses + /// Cancel when it has the keyboard, and nothing else: never Erase and Format. Escape cancels. + fn format_dialog_key(&mut self, sym: u32, utf8: &str, m: Mods) { + use crate::format_drive::CANCEL; + let Some(Dialog::Format(a)) = self.dialog.as_mut() else { return }; + let focus = a.focus; + match sym { + k::KEY_Escape => return self.press_dialog_button(CANCEL), + k::KEY_Return | k::KEY_KP_Enter => { + if focus == FormatStop::Button(CANCEL) { + return self.press_dialog_button(CANCEL); + } + return; + } + k::KEY_Tab | k::KEY_ISO_Left_Tab => { + a.tab(m.shift || sym == k::KEY_ISO_Left_Tab); + self.edit_gen += 1; + } + k::KEY_Up | k::KEY_Left if focus == FormatStop::Kind => a.step_kind(-1), + k::KEY_Down | k::KEY_Right if focus == FormatStop::Kind => a.step_kind(1), + k::KEY_Left | k::KEY_Right if matches!(focus, FormatStop::Button(_)) => { + let FormatStop::Button(i) = focus else { return }; + a.focus = FormatStop::Button(1 - i.min(1)); + } + k::KEY_space if matches!(focus, FormatStop::Button(_)) => { + let FormatStop::Button(i) = focus else { return }; + return self.press_dialog_button(i); + } + k::KEY_v if m.ctrl && focus == FormatStop::Name => { + self.cmds.push(Cmd::ReadClipboard(Paste::IntoField { edit: self.edit_gen })); + return; + } + _ if focus == FormatStop::Name => { + let f = &mut a.name; + match sym { + k::KEY_Left => f.left(m.ctrl, m.shift), + k::KEY_Right => f.right(m.ctrl, m.shift), + k::KEY_Home => f.move_to(0, m.shift), + k::KEY_End => f.move_to(f.text.len(), m.shift), + k::KEY_BackSpace => f.backspace(m.ctrl), + k::KEY_Delete => f.delete(m.ctrl), + k::KEY_a if m.ctrl => f.select_all(), + _ if !m.ctrl && !m.alt && !m.logo && !utf8.is_empty() && !utf8.chars().any(char::is_control) => f.insert(utf8), + _ => return, + } + a.check(); + } + _ => return, + } + self.invalidate_all(); + } + + /// Where the format dialog's parts are: the warning's lines wrapped under the title, the + /// name field with its label and the line under it, and each format's row, two lines tall. + pub fn format_layout(&mut self, a: &FormatAsk) -> FormatLayout { + let w = self.px(size::FORMAT_DIALOG_WIDTH).min(self.w - self.px(spacing::DIALOG_MARGIN * 2.0)).max(1); + let pad = self.px(spacing::SPACE_16); + let row = self.px(size::DIALOG_LINE); + let max = (w - 2 * pad) as f32; + let text = &mut self.text; + let mut lines = crate::connect::wrap(&a.warning(), max, |s| text.measure(s)); + let field_h = self.target(size::CONTROL_HEIGHT); + let label = self.px(size::FORM_LABEL); + let kind_h = self.target(size::FORMAT_OPTION_ROW); + let n = gannet_core::disks::FsKind::ALL.len() as i32; + let gap = self.px(spacing::SPACE_8); + let rest = self.px(spacing::SPACE_12) + row + gap + field_h + row + gap + n * kind_h + self.px(spacing::SPACE_10) + self.dialog_button_h() + self.px(spacing::SPACE_12); + // In a short window, the warning's lines that don't fit go, the last kept ending in "…". + // A screen reader still has it all. + let room = ((self.h - self.px(spacing::DIALOG_MARGIN * 2.0) - rest) / row.max(1)).max(0) as usize; + let text = &mut self.text; + crate::connect::cut(&mut lines, room, max, |s| text.measure(s)); + let h = (rest + row * lines.len() as i32).min(self.h - self.px(spacing::DIALOG_MARGIN * 2.0)).max(1); + let rect = Rect::new((self.w - w) / 2, (self.h - h) / 2, w, h); + let y = rect.y + self.px(spacing::SPACE_12) + row * (1 + lines.len() as i32) + gap; + let name = Rect::new(rect.x + pad + label, y, w - 2 * pad - label, field_h); + let name_line = Rect::new(name.x, name.bottom(), name.w, row); + let top = name_line.bottom() + gap; + let kinds: Vec = (0..n).map(|i| Rect::new(name.x, top + i * kind_h, name.w, kind_h)).collect(); + let kinds_label = Rect::new(rect.x + pad, top, label, kind_h); + FormatLayout { rect, lines, name, name_line, kinds_label, kinds } + } + // ---- Network shares ---- /// The share at a place in the sidebar, if it's one. @@ -5323,6 +5574,9 @@ impl App { if let Some(Dialog::RenameMany(d)) = self.dialog.as_mut() { d.update(); } + if let Some(Dialog::Format(a)) = self.dialog.as_mut() { + a.check(); + } self.invalidate_all(); } @@ -5528,12 +5782,26 @@ impl App { } } - pub(crate) fn stop_newest_job(&self) { - if let Some(j) = self.jobs.last() { - j.job.cancel(); + pub(crate) fn stop_newest_job(&mut self) { + if let Some(id) = self.jobs.last().map(|j| j.job.id) { + self.stop_job(id); } } + /// Stops a job, except a format that's begun erasing, which can't be stopped: that's said. + fn stop_job(&mut self, id: u64) { + let Some(j) = self.jobs.iter().find(|j| j.job.id == id) else { return }; + if j.kind == JobKind::Format && j.job.progress.done_items.load(Ordering::Relaxed) >= gannet_core::disks::FormatStep::Erasing as u64 { + let note = "Formatting can't be stopped once the drive is being erased".to_string(); + if !self.notices.contains(¬e) { + self.note(note); + } + return; + } + j.job.cancel(); + self.invalidate(self.layout().notices); + } + fn keyboard_menu(&mut self) { let l = self.layout(); let row_y = (l.list.y as f64 + self.cursor as f64 * l.row_h as f64 - self.scroll + l.row_h as f64) as i32; @@ -5558,7 +5826,17 @@ impl App { } _ => None, }; + let format = match &d { + Dialog::Format(a) => { + let l = self.format_layout(a); + if l.name.contains(x, y) { Some(Hit::FormatName) } else { l.kinds.iter().position(|r| r.contains(x, y)).map(Hit::FormatKind) } + } + _ => None, + }; self.dialog = Some(d); + if let Some(h) = format { + return h; + } if check { return Hit::DialogCheck; } @@ -6007,6 +6285,19 @@ impl App { self.invalidate_all(); } } + Hit::FormatName | Hit::FormatKind(_) => { + if let Some(Dialog::Format(a)) = self.dialog.as_mut() { + let to = if hit == Hit::FormatName { FormatStop::Name } else { FormatStop::Kind }; + if let Hit::FormatKind(i) = hit { + a.pick(FsKind::ALL[i]); + } + if a.focus != to { + a.focus = to; + self.edit_gen += 1; + } + self.invalidate_all(); + } + } Hit::ServerField(stop) => { if let Some(Dialog::Server(a)) = self.dialog.as_mut() { if stop == ServerStop::Remember { @@ -6142,11 +6433,12 @@ impl App { } } Hit::JobCancel(i) => { - if let Some(j) = self.visible_jobs().nth(i) { - j.job.cancel(); + let id = self.visible_jobs().nth(i).map(|j| j.job.id); + if let Some(id) = id { + self.stop_job(id); } } - Hit::DialogButton(_) | Hit::DialogCheck | Hit::DialogField(_) | Hit::ServerField(_) | Hit::Suggestion(_) | Hit::PreviewBody | Hit::PinGap(_) => {} + Hit::DialogButton(_) | Hit::DialogCheck | Hit::DialogField(_) | Hit::ServerField(_) | Hit::FormatName | Hit::FormatKind(_) | Hit::Suggestion(_) | Hit::PreviewBody | Hit::PinGap(_) => {} Hit::ChooserName | Hit::ChooserFilter | Hit::ChooserAccept | Hit::ChooserCancel => self.chooser_click(hit, x), Hit::Row(row) => { self.chooser_clicked_list(Some(row)); @@ -7136,8 +7428,8 @@ fn look_for_gone(home: &Path, uid: u32, dir: &Path, above: &Path, now_at: Option fn cursor_for(h: Hit) -> Cursor { match h { - Hit::Header(_) | Hit::Crumb(_) | Hit::Back | Hit::Forward | Hit::Up | Hit::EmptyTrash | Hit::Gone(_) | Hit::Place(_) | Hit::Eject(_) | Hit::MenuItem(_) | Hit::NoticeClose(_) | Hit::JobCancel(_) | Hit::DialogButton(_) | Hit::DialogCheck | Hit::ChooserFilter | Hit::ChooserAccept | Hit::ChooserCancel => Cursor::Pointer, - Hit::PathBar | Hit::FilterBox | Hit::ChooserName | Hit::DialogField(_) => Cursor::Text, + Hit::Header(_) | Hit::Crumb(_) | Hit::Back | Hit::Forward | Hit::Up | Hit::EmptyTrash | Hit::Gone(_) | Hit::Place(_) | Hit::Eject(_) | Hit::MenuItem(_) | Hit::NoticeClose(_) | Hit::JobCancel(_) | Hit::DialogButton(_) | Hit::DialogCheck | Hit::FormatKind(_) | Hit::ChooserFilter | Hit::ChooserAccept | Hit::ChooserCancel => Cursor::Pointer, + Hit::PathBar | Hit::FilterBox | Hit::ChooserName | Hit::DialogField(_) | Hit::FormatName => Cursor::Text, _ => Cursor::Default, } } @@ -10877,7 +11169,7 @@ mod tests { fn stick(r: &Rig, label: Option<&str>, mount: Option<&Path>, locked: bool) -> Volume { let _ = r; - Volume { block: format!("/b/{}", label.unwrap_or("none")), drive: "/d/stick".into(), label: label.map(String::from), size: 8_000_000_000, mount: mount.map(Path::to_path_buf), locked, unlocked: false, removable: true, identity: gannet_core::disks::Identity { id: "stick".into(), size: 1, media_detected: 1 } } + Volume { block: format!("/b/{}", label.unwrap_or("none")), drive: "/d/stick".into(), label: label.map(String::from), size: 8_000_000_000, mount: mount.map(Path::to_path_buf), locked, unlocked: false, removable: true, formattable: true, identity: gannet_core::disks::Identity { id: "stick".into(), size: 1, media_detected: 1 } } } fn drive_rig(tag: &str) -> Rig { @@ -12347,6 +12639,37 @@ mod tests { assert_eq!(r.app.dir, r.root, "Alt+Up went up from Home"); } + #[test] + fn the_format_dialog_starts_on_cancel_and_enter_never_erases() { + use gannet_core::disks::Part; + let mut r = drive_rig("format-keys"); + let v = stick(&r, Some("PHOTOS"), None, false); + r.app.on_msg(Msg::Volumes(vec![v.clone()])); + r.app.system_bus = Some("unix:path=/nonexistent".into()); + let target = FormatTarget { drive: v.drive.clone(), identity: v.identity.clone(), whole: "/b/whole".into(), model: "SanDisk Ultra".into(), size: 16_000_000_000, parts: vec![Part { label: Some("PHOTOS".into()), size: 8_000_000_000, stored: None, locked: false }], missing: vec![] }; + r.app.on_msg(Msg::FormatLooked { volume: v.clone(), result: Ok(target.clone()) }); + let focus = |r: &Rig| match &r.app.dialog { + Some(Dialog::Format(a)) => Some(a.focus), + _ => None, + }; + assert_eq!(focus(&r), Some(FormatStop::Button(crate::format_drive::CANCEL))); + // Shift+Tab to Erase and Format, where Enter does nothing. + r.key(k::KEY_ISO_Left_Tab, ""); + assert_eq!(focus(&r), Some(FormatStop::Button(crate::format_drive::ERASE))); + r.key(k::KEY_Return, ""); + r.key(k::KEY_KP_Enter, ""); + assert!(r.app.jobs.is_empty() && focus(&r).is_some(), "Enter didn't erase"); + // Space does, as a job, and nothing else is done to the drive meanwhile. + r.key(k::KEY_space, " "); + assert!(r.app.dialog.is_none()); + assert_eq!(r.app.jobs.len(), 1); + assert!(r.app.drives_busy.contains(&v.drive) && !r.app.drive_act(v.clone(), Doing::Mount)); + let id = r.app.jobs[0].job.id; + r.app.on_msg(Msg::FormatDone { job: id, target, kind: FsKind::Exfat, result: Ok(None) }); + assert!(r.app.jobs.is_empty() && r.app.drives_busy.is_empty()); + assert!(r.app.notices.contains(&"Formatted “SanDisk Ultra, 16.0 GB” as exFAT".to_string()), "{:?}", r.app.notices); + } + #[test] fn the_menu_key_opens_a_drives_menu_in_the_sidebar() { let mut r = drive_rig("drive-keys"); @@ -12359,7 +12682,7 @@ mod tests { assert_eq!(r.app.places[1].label, "PHOTOS"); r.key(k::KEY_Menu, ""); let m = r.app.menu.as_ref().expect("the drive's menu"); - assert_eq!(m.items.iter().map(|i| i.label).collect::>(), ["Open", "Unmount", "Eject"]); + assert_eq!(m.items.iter().map(|i| i.label).collect::>(), ["Open", "Unmount", "Eject", "Format…"]); // Its items do what they do from a right-click. r.key(k::KEY_Down, ""); r.key(k::KEY_Down, ""); diff --git a/crates/app/src/chooser.rs b/crates/app/src/chooser.rs index 4b9259d..8c346b9 100644 --- a/crates/app/src/chooser.rs +++ b/crates/app/src/chooser.rs @@ -903,7 +903,7 @@ fn allows(a: Action) -> bool { Action::Open | Action::Preview | Action::ToggleHidden | Action::SortBy(_) | Action::Reload => true, Action::Rename | Action::NewFolder | Action::Trash | Action::Undo | Action::Redo => true, Action::ShowInFolder | Action::OpenPin | Action::Unpin | Action::OpenDrive | Action::Unmount | Action::Eject | Action::OpenShare | Action::Disconnect | Action::ChooseFilter(_) => true, - Action::NewWindow | Action::Cut | Action::Copy | Action::Paste | Action::DeleteForGood | Action::Restore | Action::EmptyTrash | Action::SetBackground | Action::Extract | Action::Compress | Action::OpenWith | Action::OpenTerminal => false, + Action::NewWindow | Action::Cut | Action::Copy | Action::Paste | Action::DeleteForGood | Action::Restore | Action::EmptyTrash | Action::SetBackground | Action::Extract | Action::Compress | Action::OpenWith | Action::OpenTerminal | Action::FormatDrive => false, } } diff --git a/crates/app/src/drives.rs b/crates/app/src/drives.rs index 432b534..dab61b3 100644 --- a/crates/app/src/drives.rs +++ b/crates/app/src/drives.rs @@ -1,14 +1,17 @@ //! The sidebar's drives, from udisks2 (see `gannet_core::disks`). One thread follows udisks2's //! signals and sends the window the volumes again after each burst of changes, so nothing runs -//! while nothing changes. Mounting, unlocking, unmounting and ejecting each get a thread of their -//! own, as polkit may keep one waiting on a person. +//! while nothing changes. Mounting, unlocking, unmounting, ejecting and formatting each get a +//! thread of their own, as polkit may keep one waiting on a person. use std::path::PathBuf; use std::sync::mpsc::channel; use std::time::Duration; use gannet_core::bus::{Bus, zbus}; -use gannet_core::disks::{self, DiskError, Udisks, Volume}; +use std::sync::atomic::Ordering; + +use gannet_core::disks::{self, DiskError, FormatStep, FormatTarget, FsKind, Udisks, Volume}; +use gannet_core::ops::Job; use crate::app::{Hub, Msg}; @@ -107,3 +110,28 @@ pub fn act(hub: Hub, address: String, volume: Volume, doing: Doing) { hub.send(Msg::DiskDone { volume, doing, result }); }); } + +/// Looks at the volume's drive to format it: whether it can be, what's on it, and which formats +/// can be made. Sends `Msg::FormatLooked`. +pub fn look_to_format(hub: Hub, address: String, volume: Volume) { + let _ = std::thread::Builder::new().name("gannet-drive".into()).spawn(move || { + let result = Udisks::connect(&address).and_then(|udisks| udisks.look_to_format(&volume)); + hub.send(Msg::FormatLooked { volume, result }); + }); +} + +/// Formats the drive as `kind`, named `label`, keeping `job`'s progress: one step of four as +/// each starts. A stop asked for before the erasing begins stops it. Sends `Msg::FormatDone`. +pub fn format(hub: Hub, address: String, target: FormatTarget, kind: FsKind, label: String, job: Job) { + let _ = std::thread::Builder::new().name("gannet-format".into()).spawn(move || { + let p = job.progress.clone(); + p.total_items.store(4, Ordering::Relaxed); + let mut step = |s: FormatStep| { + p.done_items.store(s as u64, Ordering::Relaxed); + hub.send(Msg::Op(gannet_core::ops::Event::Progress(job.id))); + !(job.is_cancelled() && s <= FormatStep::Erasing) + }; + let result = Udisks::connect(&address).and_then(|udisks| udisks.format(&target, kind, &label, &mut step)); + hub.send(Msg::FormatDone { job: job.id, target, kind, result }); + }); +} diff --git a/crates/app/src/format_drive.rs b/crates/app/src/format_drive.rs new file mode 100644 index 0000000..1f361fc --- /dev/null +++ b/crates/app/src/format_drive.rs @@ -0,0 +1,206 @@ +//! Formatting a drive: the dialog that asks for its new name and format and warns what will be +//! erased. The work is udisks2's (`gannet_core::disks::Udisks::format`), on a thread of its own +//! (`crate::drives::format`), shown as a job. +//! +//! There's nothing to type to confirm. What keeps a drive from being erased by mistake is the +//! warning, which names the drive and lists what's on it; the keyboard starting on Cancel, with +//! Enter never pressing Erase and Format; and the system's own password prompt after it. + +use std::borrow::Cow; + +use gannet_core::disks::{FormatTarget, FsKind}; + +use crate::field::Field; + +/// A part of the dialog that takes the keyboard, in Tab order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stop { + Name, + /// The formats, a group of choices: the arrows move among them. + Kind, + Button(usize), +} + +/// Erase and Format, then Cancel. +pub const ERASE: usize = 0; +pub const CANCEL: usize = 1; + +/// What each format is for, said under its name. +pub fn kind_note(kind: FsKind) -> &'static str { + match kind { + FsKind::Exfat => "Windows, macOS and Linux. Files of any size", + FsKind::Fat32 => "For older devices. Files up to 4 GB", + FsKind::Ext4 => "For Linux only", + } +} + +pub struct FormatAsk { + pub target: FormatTarget, + pub name: Field, + pub kind: FsKind, + pub focus: Stop, +} + +impl FormatAsk { + /// Starts on Cancel, with exFAT picked, or the first format that can be made here. + pub fn new(target: FormatTarget) -> Self { + let kind = FsKind::ALL.into_iter().find(|k| !target.missing.iter().any(|(m, _)| m == k)).unwrap_or(FsKind::Exfat); + let mut a = Self { target, name: Field::new(""), kind, focus: Stop::Button(CANCEL) }; + a.check(); + a + } + + pub fn buttons() -> [Cow<'static, str>; 2] { + [Cow::Borrowed("Erase and Format"), Cow::Borrowed("Cancel")] + } + + /// The package `kind` needs, if it can't be made here. + pub fn missing(&self, kind: FsKind) -> Option<&str> { + self.target.missing.iter().find(|(k, _)| *k == kind).map(|(_, p)| p.as_str()) + } + + /// What a format's choice says under its name: what it's for, or what it needs. + pub fn note(&self, kind: FsKind) -> String { + match self.missing(kind) { + Some(package) => format!("Unavailable: needs the {package} package"), + None => kind_note(kind).to_string(), + } + } + + /// How the drive is named: its make and model and its size, like “SanDisk Ultra, 116 GB”. + pub fn drive_name(&self) -> String { + let size = crate::format::size(self.target.size); + if self.target.model.is_empty() { format!("{size} drive") } else { format!("{}, {size}", self.target.model) } + } + + pub fn title(&self) -> String { + format!("Format “{}”?", self.drive_name()) + } + + /// What will be erased, partition by partition, as it's said and drawn. + pub fn warning(&self) -> String { + let parts: Vec = self + .target + .parts + .iter() + .map(|p| { + let size = crate::format::size(p.size); + match (&p.label, p.stored, p.locked) { + (_, _, true) => format!("an encrypted {size} partition"), + (Some(l), Some(stored), _) => format!("the “{l}” partition, with {} of files", crate::format::size(stored)), + (Some(l), None, _) => format!("the {size} “{l}” partition"), + (None, Some(stored), _) => format!("an unnamed {size} partition, with {} of files", crate::format::size(stored)), + (None, None, _) => format!("an unnamed {size} partition"), + } + }) + .collect(); + let what = match parts.as_slice() { + [] => String::new(), + [one] => format!(": {one}"), + [rest @ .., last] => format!(": {}, and {last}", rest.join(", ")), + }; + format!("Everything on “{}” will be erased{what}. This can't be undone.", self.drive_name()) + } + + /// The line under the name: why it can't be used, or the format's rule for names. + pub fn name_line(&self) -> String { + self.name.error.clone().unwrap_or_else(|| self.kind.label_rule().to_string()) + } + + /// Checks the name against the format picked, and says why it can't be used, under it. + pub fn check(&mut self) { + self.name.error = self.kind.label(&self.name.text).err(); + } + + /// Picks a format, if it can be made here. + pub fn pick(&mut self, kind: FsKind) -> bool { + if self.missing(kind).is_some() { + return false; + } + self.kind = kind; + self.check(); + true + } + + /// Picks the next format that can be made, `by` one way or the other, round past the ends. + pub fn step_kind(&mut self, by: isize) { + let all = FsKind::ALL; + let n = all.len() as isize; + let mut i = all.iter().position(|k| *k == self.kind).unwrap_or(0) as isize; + for _ in 0..n { + i = (i + by).rem_euclid(n); + if self.pick(all[i as usize]) { + return; + } + } + } + + pub fn tab(&mut self, back: bool) { + let stops = [Stop::Name, Stop::Kind, Stop::Button(ERASE), Stop::Button(CANCEL)]; + let n = stops.len(); + let i = stops.iter().position(|s| *s == self.focus).unwrap_or(0); + self.focus = stops[if back { (i + n - 1) % n } else { (i + 1) % n }]; + } + + /// The name to write and the format, when Erase and Format can go ahead: the name fits the + /// format and the format can be made here. + pub fn ready(&self) -> Option<(FsKind, String)> { + if self.missing(self.kind).is_some() { + return None; + } + self.kind.label(&self.name.text).ok().map(|l| (self.kind, l)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gannet_core::disks::{Identity, Part}; + + fn target(parts: Vec, missing: Vec<(FsKind, String)>) -> FormatTarget { + FormatTarget { drive: "/d".into(), identity: Identity { id: "x".into(), size: 1, media_detected: 1 }, whole: "/b".into(), model: "SanDisk Ultra".into(), size: 116_000_000_000, parts, missing } + } + + #[test] + fn the_warning_names_the_drive_and_lists_what_is_on_it() { + let iso = Part { label: Some("ARCH_202601".into()), size: 1_300_000_000, stored: Some(1_200_000_000), locked: false }; + let efi = Part { label: Some("ARCHISO_EFI".into()), size: 263_000_000, stored: None, locked: false }; + let a = FormatAsk::new(target(vec![iso.clone()], vec![])); + assert_eq!(a.warning(), "Everything on “SanDisk Ultra, 116 GB” will be erased: the “ARCH_202601” partition, with 1.2 GB of files. This can't be undone."); + let a = FormatAsk::new(target(vec![iso, efi, Part { label: None, size: 8_000_000_000, stored: None, locked: true }], vec![])); + assert_eq!(a.warning(), "Everything on “SanDisk Ultra, 116 GB” will be erased: the “ARCH_202601” partition, with 1.2 GB of files, the 263 MB “ARCHISO_EFI” partition, and an encrypted 8.0 GB partition. This can't be undone."); + let mut t = target(vec![], vec![]); + t.model.clear(); + assert_eq!(FormatAsk::new(t).warning(), "Everything on “116 GB drive” will be erased. This can't be undone."); + } + + #[test] + fn it_starts_on_cancel_with_the_first_format_that_can_be_made() { + let a = FormatAsk::new(target(vec![], vec![])); + assert_eq!((a.focus, a.kind), (Stop::Button(CANCEL), FsKind::Exfat)); + let mut a = FormatAsk::new(target(vec![], vec![(FsKind::Exfat, "exfatprogs".into())])); + assert_eq!(a.kind, FsKind::Fat32); + assert_eq!(a.note(FsKind::Exfat), "Unavailable: needs the exfatprogs package"); + assert!(!a.pick(FsKind::Exfat), "can't be picked"); + a.step_kind(1); + assert_eq!(a.kind, FsKind::Ext4); + a.step_kind(1); + assert_eq!(a.kind, FsKind::Fat32, "round past exFAT, which can't be made"); + } + + #[test] + fn the_name_is_checked_against_the_format() { + let mut a = FormatAsk::new(target(vec![], vec![])); + a.name = Field::new("Holiday photos"); + a.check(); + assert_eq!(a.ready(), Some((FsKind::Exfat, "Holiday photos".into()))); + a.pick(FsKind::Fat32); + assert_eq!(a.name.error.as_deref(), Some("FAT32 allows 11 characters. This has 14.")); + assert_eq!(a.ready(), None); + a.name = Field::new("photos"); + a.check(); + assert_eq!(a.ready(), Some((FsKind::Fat32, "PHOTOS".into())), "kept in capitals"); + a.pick(FsKind::Ext4); + assert_eq!(a.name_line(), FsKind::Ext4.label_rule()); + } +} diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 4587e9f..8f100b3 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11,6 +11,7 @@ mod drives; mod docview; mod field; mod format; +mod format_drive; mod icons; mod media; mod network; @@ -889,7 +890,7 @@ mod bench { Edit::NewFolder(f) => format!("newfolder:{}", f.text), }; format!( - "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", + "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"format\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", esc(&a.dir.to_string_lossy()), a.loading, a.rows.len(), @@ -928,6 +929,7 @@ mod bench { Some(crate::app::Dialog::RenameMany(_)) => "rename-many", Some(crate::app::Dialog::Server(a)) if a.is_login() => "server-login", Some(crate::app::Dialog::Server(_)) => "server-question", + Some(crate::app::Dialog::Format(_)) => "format", }), a.undo.len(), a.redo.len(), @@ -947,6 +949,7 @@ mod bench { thumbs(a), a.side_focus().map_or(-1, |i| i as i64), server(a), + format_dialog(a), suggest(a), a.list_message().map_or_else(|| "null".to_string(), |m| esc(&m.0)), targets, @@ -974,6 +977,26 @@ mod bench { ) } + /// The format dialog's title, warning, name and the line under it, the formats (each with + /// whether it can be made and what it says), the one picked, which part has the keyboard, and + /// whether Erase and Format can go ahead. + fn format_dialog(a: &App) -> String { + let Some(crate::app::Dialog::Format(d)) = &a.dialog else { return "null".to_string() }; + let kinds: Vec = gannet_core::disks::FsKind::ALL.iter().map(|k| format!("[{},{},{}]", esc(k.name()), d.missing(*k).is_none(), esc(&d.note(*k)))).collect(); + format!( + "{{\"title\":{},\"warning\":{},\"name\":{},\"line\":{},\"error\":{},\"kinds\":[{}],\"kind\":{},\"focus\":{},\"ready\":{}}}", + esc(&d.title()), + esc(&d.warning()), + esc(&d.name.text), + esc(&d.name_line()), + d.name.error.is_some(), + kinds.join(","), + esc(d.kind.name()), + esc(&format!("{:?}", d.focus)), + d.ready().is_some() + ) + } + /// The recent servers offered under the path bar, and which is picked. fn suggest(a: &App) -> String { let Some(s) = &a.suggest else { return "null".to_string() }; diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 00fc803..72a5946 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -15,6 +15,7 @@ use crate::format; use crate::icons::Icon; use crate::rename_many::{Focus, RenameMany}; use crate::connect::{AskKind, ServerAsk, Stop as ServerStop}; +use crate::format_drive::{FormatAsk, Stop as FormatStop}; impl App { pub fn paint(&mut self, c: &mut Canvas) { @@ -786,6 +787,14 @@ impl App { self.dialog = Some(d); return; } + if let Dialog::Format(a) = &d { + self.paint_format_dialog(c, a); + // Only a button with the keyboard shows as focused: Enter presses none otherwise. + let at = if let FormatStop::Button(i) = a.focus { i } else { usize::MAX }; + self.paint_dialog_buttons(c, &d, at, a.ready().is_none() && at != crate::format_drive::ERASE); + self.dialog = Some(d); + return; + } let (title, line2) = self.dialog_text(&d); let at = App::dialog_default(&d); let x = (r.x + self.px(spacing::SPACE_16)) as f32; @@ -869,6 +878,53 @@ impl App { } } + /// The format dialog: its title, the warning under it, the name with its label and the line + /// under it (red with a red outline when the name can't be used), and the formats as round + /// buttons, each with what it's for, or what it needs, under its name. + fn paint_format_dialog(&mut self, c: &mut Canvas, a: &FormatAsk) { + let co = self.colors; + let l = self.format_layout(a); + let r = l.rect; + let x = (r.x + self.px(spacing::SPACE_16)) as f32; + let max = (r.w - self.px(spacing::SPACE_16 * 2.0)) as f32; + let row = self.px(size::DIALOG_LINE); + let top = r.y + self.px(spacing::SPACE_12); + self.text.draw_fitted(c, &a.title(), x, self.baseline(top, row), max, co.foreground); + for (i, line) in l.lines.iter().enumerate() { + self.text.draw_fitted(c, line, x, self.baseline(top + row * (i as i32 + 1), row), max, co.foreground); + } + let label_max = (l.name.x - r.x) as f32 - self.px(spacing::SPACE_24) as f32; + self.text.draw_fitted(c, "Name", x, self.baseline(l.name.y, l.name.h), label_max, co.muted); + self.paint_field(c, l.name, &a.name, a.focus == FormatStop::Name); + let line_color = if a.name.error.is_some() { co.danger } else { co.muted }; + self.text.draw_fitted(c, &a.name_line(), l.name_line.x as f32, self.baseline(l.name_line.y, l.name_line.h), l.name_line.w as f32, line_color); + let half = |r: Rect| r.h / 2; + self.text.draw_fitted(c, "Format", x, self.baseline(l.kinds_label.y, half(l.kinds_label)), label_max, co.muted); + let ring = self.px(size::RADIO); + let dot = self.px(size::RADIO_DOT); + let edge = self.px(size::BORDER_WIDTH).max(1); + for (kind, kr) in gannet_core::disks::FsKind::ALL.into_iter().zip(&l.kinds) { + let can = a.missing(kind).is_none(); + let picked = a.kind == kind; + let h = half(*kr); + // The round button: an outline, filled with a dot when it's the one picked. + let b = Rect::new(kr.x + self.px(spacing::SPACE_4), kr.y + (h - ring) / 2, ring, ring); + c.rrect(b, ring / 2, if !can { co.muted } else if picked { co.accent_mark } else { co.control_border }); + c.rrect(Rect::new(b.x + edge, b.y + edge, b.w - 2 * edge, b.h - 2 * edge), (ring - 2 * edge) / 2, co.surface); + if picked && can { + c.rrect(Rect::new(b.x + (ring - dot) / 2, b.y + (ring - dot) / 2, dot, dot), dot / 2, co.accent_mark); + } + let tx = (b.right() + self.px(spacing::SPACE_8)) as f32; + let tmax = (kr.right() - self.px(spacing::SPACE_4)) as f32 - tx; + self.text.draw_fitted(c, kind.name(), tx, self.baseline(kr.y, h), tmax, if can { co.foreground } else { co.muted }); + self.text.draw_fitted(c, &a.note(kind), tx, self.baseline(kr.y + h, h), tmax, co.muted); + // The keyboard's outline goes round the one picked while the formats have it. + if picked && a.focus == FormatStop::Kind { + c.frame(*kr, self.px(size::FOCUS_OUTLINE).max(1), co.accent_mark); + } + } + } + /// The recent servers offered under the path bar, with the one picked by Up or Down, or under /// the pointer, highlighted. fn paint_suggestions(&mut self, c: &mut Canvas) { diff --git a/crates/core/examples/udisks-standin.rs b/crates/core/examples/udisks-standin.rs index 8c4c6e6..5d239ad 100644 --- a/crates/core/examples/udisks-standin.rs +++ b/crates/core/examples/udisks-standin.rs @@ -2,17 +2,30 @@ //! folders under a scratch root rather than mounting anything. It reads commands on stdin, one a //! line, and answers each with `ok` or `error ...`: //! -//! drive NAME ID a removable drive, which can be powered off -//! fs NAME DRIVE LABEL a filesystem on it, mounting at ROOT/LABEL -//! luks NAME DRIVE PASSPHRASE LABEL an encrypted volume holding a filesystem called LABEL +//! drive NAME ID a removable USB drive, which can be powered off, with a partition +//! table on its whole disk (the block NAME) +//! internal NAME ID a drive that's neither removable nor on USB +//! model DRIVE VENDOR MODEL what udisks2 says made it and what it's called +//! fs NAME DRIVE LABEL a filesystem in a partition on it, mounting at ROOT/LABEL +//! luks NAME DRIVE PASSPHRASE LABEL an encrypted partition holding a filesystem called LABEL //! unplug DRIVE the drive and everything on it go //! busy NAME unmounting NAME says it's busy until `idle NAME` //! idle NAME //! mount NAME mounted by someone else +//! at NAME PATH said to be mounted at PATH, which isn't touched +//! system NAME udisks2 marks the block as the system's (HintSystem) +//! lacks TYPE UTILITY Manager.CanFormat says TYPE needs UTILITY, which isn't installed +//! refuse the next Format is refused, as when polkit's prompt is dismissed +//! asked each Format and CreatePartitionAndFormat asked for, a line each +//! starting `asked `, before the `ok` //! //! As with the kernel, unmounting a filesystem is also refused while any process has a file, //! folder or working directory open inside its folder. //! +//! Formatting changes only this stand-in's own state: `Block.Format` on a whole disk drops its +//! partitions, and `PartitionTable.CreatePartitionAndFormat` adds one with the filesystem and +//! label asked for. Both are written down for `asked`. No device is ever opened. +//! //! Usage: udisks-standin ADDRESS ROOT use std::collections::{BTreeMap, HashMap}; @@ -28,6 +41,9 @@ const ROOT: &str = "/org/freedesktop/UDisks2"; #[derive(Clone, Default)] struct DriveState { id: String, + vendor: String, + model: String, + removable: bool, } #[derive(Clone, Default)] @@ -35,7 +51,13 @@ struct BlockState { drive: String, label: String, usage: String, + id_type: String, backing: String, + /// For a whole disk: it has a partition table. + table: bool, + /// For a partition: its disk's block. + partition_of: Option, + system: bool, /// `Some` for a filesystem: where it's mounted, if it is. mounted: Option>, /// `Some` for an encrypted volume: its passphrase, the label inside, and its contents' path. @@ -48,6 +70,11 @@ struct State { root: PathBuf, drives: BTreeMap, blocks: BTreeMap, + /// Filesystem types CanFormat says can't be made, and the program each needs. + lacks: HashMap, + refuse: bool, + /// The formatting calls made, as `asked` lists them. + asked: Vec, } type Shared = Arc>; @@ -59,6 +86,7 @@ enum UdError { ZBus(zbus::Error), DeviceBusy(String), Failed(String), + NotAuthorizedDismissed(String), AlreadyMounted(String), NotMounted(String), } @@ -104,8 +132,20 @@ impl DriveIface { 16_000_000_000 } #[zbus(property)] + fn vendor(&self) -> String { + self.state.lock().unwrap().drives.get(&self.at).map(|d| d.vendor.clone()).unwrap_or_default() + } + #[zbus(property)] + fn model(&self) -> String { + self.state.lock().unwrap().drives.get(&self.at).map(|d| d.model.clone()).unwrap_or_default() + } + #[zbus(property)] fn removable(&self) -> bool { - true + self.state.lock().unwrap().drives.get(&self.at).is_some_and(|d| d.removable) + } + #[zbus(property)] + fn connection_bus(&self) -> String { + if self.removable() { "usb".into() } else { String::new() } } #[zbus(property)] fn ejectable(&self) -> bool { @@ -113,7 +153,7 @@ impl DriveIface { } #[zbus(property)] fn can_power_off(&self) -> bool { - true + self.removable() } #[zbus(property)] fn time_media_detected(&self) -> u64 { @@ -157,12 +197,16 @@ impl BlockIface { self.get(|b| b.usage.clone()) } #[zbus(property)] + fn id_type(&self) -> String { + self.get(|b| b.id_type.clone()) + } + #[zbus(property)] fn size(&self) -> u64 { - 8_000_000_000 + if self.get(|b| b.table) { 16_000_000_000 } else { 8_000_000_000 } } #[zbus(property)] fn hint_system(&self) -> bool { - false + self.get(|b| b.system) } #[zbus(property)] fn hint_ignore(&self) -> bool { @@ -172,6 +216,37 @@ impl BlockIface { fn crypto_backing_device(&self) -> OwnedObjectPath { object(&self.get(|b| b.backing.clone())) } + + /// A new, empty partition table on a whole disk, in this stand-in's state alone. + async fn format(&self, kind: String, options: HashMap, #[zbus(connection)] conn: &Connection) -> Result<(), UdError> { + let gone: Vec = { + let mut s = self.state.lock().unwrap(); + s.asked.push(format!("Format {} {kind} {}", self.at.rsplit('/').next().unwrap_or(""), written(&options))); + if std::mem::take(&mut s.refuse) { + return Err(UdError::NotAuthorizedDismissed("Not authorized to perform operation".into())); + } + let Some(drive) = s.blocks.get(&self.at).filter(|b| b.table).map(|b| b.drive.clone()) else { return Err(UdError::Failed("not a whole disk".into())) }; + // As with the kernel: nothing on it can be in use. + let on: Vec = s.blocks.iter().filter(|(p, b)| b.drive == drive && **p != self.at).map(|(p, _)| p.clone()).collect(); + let inside: Vec = s.blocks.iter().filter(|(_, b)| on.contains(&b.backing)).map(|(p, _)| p.clone()).collect(); + if on.iter().chain(&inside).any(|p| matches!(s.blocks[p].mounted, Some(Some(_)))) || !inside.is_empty() { + return Err(UdError::DeviceBusy("Error wiping device: Device or resource busy".into())); + } + for p in &on { + s.blocks.remove(p); + } + on + }; + // Inside a call, so the object server is asked directly rather than through `remove`. + let server = conn.object_server(); + for p in &gone { + let _ = server.remove::(p.as_str()).await; + let _ = server.remove::(p.as_str()).await; + let _ = server.remove::(p.as_str()).await; + let _ = server.remove::(p.as_str()).await; + } + Ok(()) + } } struct FilesystemIface { @@ -196,7 +271,7 @@ impl FilesystemIface { if let Some(Some(_)) = b.mounted { return Err(UdError::AlreadyMounted("already mounted".into())); } - let at = root.join(&b.label); + let at = root.join(if b.label.is_empty() { self.at.rsplit('/').next().unwrap_or("disk") } else { &b.label }); std::fs::create_dir_all(&at).map_err(|e| UdError::Failed(e.to_string()))?; b.mounted = Some(Some(at.clone())); at @@ -274,12 +349,89 @@ impl EncryptedIface { } } +/// Options as they're written down: each key and value, in order. +fn written(options: &HashMap) -> String { + let mut v: Vec = options.iter().map(|(k, val)| format!("{k}={}", match &**val { + Variant::Str(s) => s.to_string(), + Variant::Bool(b) => b.to_string(), + other => format!("{other:?}"), + })).collect(); + v.sort(); + v.join(" ") +} + +struct PartitionIface { + at: String, + state: Shared, +} + +#[zbus::interface(name = "org.freedesktop.UDisks2.Partition")] +impl PartitionIface { + #[zbus(property)] + fn table(&self) -> OwnedObjectPath { + let s = self.state.lock().unwrap(); + object(s.blocks.get(&self.at).and_then(|b| b.partition_of.clone()).as_deref().unwrap_or("/")) + } +} + +struct TableIface { + at: String, + state: Shared, +} + +#[zbus::interface(name = "org.freedesktop.UDisks2.PartitionTable")] +impl TableIface { + #[zbus(property, name = "Type")] + fn kind(&self) -> String { + "gpt".into() + } + + /// Adds a partition with a filesystem, as udisks2 would, but only to this stand-in's state. + #[allow(clippy::too_many_arguments)] + async fn create_partition_and_format(&self, offset: u64, size: u64, kind: String, name: String, _options: HashMap, format_type: String, format_options: HashMap, #[zbus(connection)] conn: &Connection) -> Result { + let made = { + let mut s = self.state.lock().unwrap(); + s.asked.push(format!("CreatePartitionAndFormat {} {offset} {size} {kind} {name:?} {format_type} {}", self.at.rsplit('/').next().unwrap_or(""), written(&format_options))); + let whole = s.blocks.get(&self.at).cloned().ok_or_else(|| UdError::Failed("gone".into()))?; + if s.blocks.values().any(|b| b.partition_of.as_deref() == Some(self.at.as_str())) { + return Err(UdError::Failed("no room: the disk already has a partition".into())); + } + let label = match format_options.get("label").map(|v| &**v) { + Some(Variant::Str(l)) => l.to_string(), + _ => String::new(), + }; + let made = format!("{}1", self.at); + s.blocks.insert(made.clone(), BlockState { drive: whole.drive, label, usage: "filesystem".into(), id_type: format_type, backing: "/".into(), partition_of: Some(self.at.clone()), mounted: Some(None), ..BlockState::default() }); + made + }; + let server = conn.object_server(); + server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; + server.at(made.as_str(), FilesystemIface { at: made.clone(), state: self.state.clone() }).await?; + server.at(made.as_str(), PartitionIface { at: made.clone(), state: self.state.clone() }).await?; + Ok(object(&made)) + } +} + +struct ManagerIface { + state: Shared, +} + +#[zbus::interface(name = "org.freedesktop.UDisks2.Manager")] +impl ManagerIface { + fn can_format(&self, kind: String) -> (bool, String) { + match self.state.lock().unwrap().lacks.get(&kind) { + Some(utility) => (false, utility.clone()), + None => (true, String::new()), + } + } +} + /// Serves a block's interfaces, as its state says it has. fn serve_block(conn: &Connection, state: &Shared, at: &str) { - let (fs, luks) = { + let (fs, luks, table, partition) = { let s = state.lock().unwrap(); let b = &s.blocks[at]; - (b.mounted.is_some(), b.luks.is_some()) + (b.mounted.is_some(), b.luks.is_some(), b.table, b.partition_of.is_some()) }; let server = conn.object_server(); block_on(server.at(at, BlockIface { at: at.into(), state: state.clone() })).unwrap(); @@ -289,10 +441,18 @@ fn serve_block(conn: &Connection, state: &Shared, at: &str) { if luks { block_on(server.at(at, EncryptedIface { at: at.into(), state: state.clone() })).unwrap(); } + if partition { + block_on(server.at(at, PartitionIface { at: at.into(), state: state.clone() })).unwrap(); + } + if table { + block_on(server.at(at, TableIface { at: at.into(), state: state.clone() })).unwrap(); + } } fn remove(conn: &Connection, at: &str) { let server = conn.object_server(); + let _ = block_on(server.remove::(at)); + let _ = block_on(server.remove::(at)); let _ = block_on(server.remove::(at)); let _ = block_on(server.remove::(at)); let _ = block_on(server.remove::(at)); @@ -319,21 +479,47 @@ fn unplug(conn: &Connection, state: &Shared, drive: &str) { fn command(conn: &Connection, state: &Shared, line: &str) -> Result<(), String> { let words: Vec<&str> = line.split_whitespace().collect(); match words.as_slice() { - ["drive", name, id] => { + [kind @ ("drive" | "internal"), name, id] => { let at = path("drives", name); - state.lock().unwrap().drives.insert(at.clone(), DriveState { id: id.to_string() }); + let whole = path("block_devices", name); + { + let mut s = state.lock().unwrap(); + s.drives.insert(at.clone(), DriveState { id: id.to_string(), removable: *kind == "drive", ..DriveState::default() }); + s.blocks.insert(whole.clone(), BlockState { drive: at.clone(), backing: "/".into(), table: true, ..BlockState::default() }); + } block_on(conn.object_server().at(at.as_str(), DriveIface { at: at.clone(), state: state.clone() })).map_err(|e| e.to_string())?; + serve_block(conn, state, &whole); + } + ["model", drive, vendor, model] => { + let mut s = state.lock().unwrap(); + let d = s.drives.get_mut(&path("drives", drive)).ok_or("no such drive")?; + (d.vendor, d.model) = (vendor.to_string(), model.to_string()); } ["fs", name, drive, label] => { let at = path("block_devices", name); - state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: path("drives", drive), label: label.to_string(), usage: "filesystem".into(), backing: "/".into(), mounted: Some(None), ..BlockState::default() }); + state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: path("drives", drive), label: label.to_string(), usage: "filesystem".into(), id_type: "vfat".into(), backing: "/".into(), partition_of: Some(path("block_devices", drive)), mounted: Some(None), ..BlockState::default() }); serve_block(conn, state, &at); } ["luks", name, drive, passphrase, label] => { let at = path("block_devices", name); - state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: path("drives", drive), label: String::new(), usage: "crypto".into(), backing: "/".into(), luks: Some((passphrase.to_string(), label.to_string(), None)), ..BlockState::default() }); + state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: path("drives", drive), label: String::new(), usage: "crypto".into(), backing: "/".into(), partition_of: Some(path("block_devices", drive)), luks: Some((passphrase.to_string(), label.to_string(), None)), ..BlockState::default() }); serve_block(conn, state, &at); } + ["at", name, to] => { + let at = path("block_devices", name); + state.lock().unwrap().blocks.get_mut(&at).ok_or("no such block")?.mounted = Some(Some(PathBuf::from(to))); + block_on(changed(conn, &at, "Filesystem")); + } + ["system", name] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.system = true, + ["lacks", kind, utility] => { + state.lock().unwrap().lacks.insert(kind.to_string(), utility.to_string()); + } + ["refuse"] => state.lock().unwrap().refuse = true, + ["asked"] => { + for a in &state.lock().unwrap().asked { + println!("asked {a}"); + } + } ["unplug", drive] => unplug(conn, state, &path("drives", drive)), ["busy" | "idle", name] => { let at = path("block_devices", name); @@ -366,6 +552,7 @@ fn main() { let conn = bus.connection().clone(); block_on(conn.object_server().at(ROOT, zbus::fdo::ObjectManager)).expect("the object manager"); let state: Shared = Arc::new(Mutex::new(State { root: PathBuf::from(root), ..State::default() })); + block_on(conn.object_server().at(format!("{ROOT}/Manager"), ManagerIface { state: state.clone() })).expect("the manager"); assert!(bus.own_name("org.freedesktop.UDisks2").expect("the name"), "someone else is udisks2 on this bus"); println!("ok"); for line in std::io::stdin().lock().lines() { diff --git a/crates/core/src/disks.rs b/crates/core/src/disks.rs index 4f0d439..71751fe 100644 --- a/crates/core/src/disks.rs +++ b/crates/core/src/disks.rs @@ -1,6 +1,6 @@ -//! Drives through udisks2: which volumes there are, and mounting, unmounting, unlocking and -//! ejecting them. udisks2 does the work on the system bus, and polkit decides what's allowed, -//! asking for a password if the system says to. +//! Drives through udisks2: which volumes there are, and mounting, unmounting, unlocking, +//! ejecting and formatting them. udisks2 does the work on the system bus, and polkit decides +//! what's allowed, asking for a password if the system says to. //! //! What udisks2 reports is read into a plain model first (`Snapshot`), so the rules for which //! volumes show in the sidebar (`volumes`) are tested without a bus. @@ -19,6 +19,7 @@ use crate::bus::Bus; pub const SERVICE: &str = "org.freedesktop.UDisks2"; pub const ROOT: &str = "/org/freedesktop/UDisks2"; +const MANAGER: &str = "/org/freedesktop/UDisks2/Manager"; const PREFIX: &str = "org.freedesktop.UDisks2."; /// udisks2's way of saying "none" for an object path. const NONE: &str = "/"; @@ -32,6 +33,9 @@ pub struct Drive { pub path: String, /// Make, model and serial, as one string. pub id: String, + /// Who made it and what it's called, like "SanDisk" and "Ultra", when udisks2 knows. + pub vendor: String, + pub model: String, pub size: u64, pub removable: bool, pub ejectable: bool, @@ -68,6 +72,12 @@ pub struct Block { pub mount_points: Option>, /// For an encrypted block, its unlocked contents, or `None` while it's locked. pub encrypted: Option>, + /// It holds a partition table: it's a whole disk. + pub table: bool, + /// For a partition, the block whose table it's in. Empty for anything else. + pub partition_of: String, + /// It's swap, in use. + pub swap: bool, } /// Everything udisks2 knows about drives and the blocks on them, at one moment. @@ -100,6 +110,8 @@ pub struct Volume { pub unlocked: bool, /// Whether the drive can be taken out, so it gets an eject button. pub removable: bool, + /// Whether its drive can be offered for formatting. See [`Snapshot::format_refusal`]. + pub formattable: bool, pub identity: Identity, } @@ -150,6 +162,8 @@ impl Snapshot { Drive { path: path.clone(), id: string_of(d, "Id"), + vendor: string_of(d, "Vendor").trim().to_string(), + model: string_of(d, "Model").trim().to_string(), size: u64_of(d, "Size"), removable: bool_of(d, "Removable") || bool_of(d, "MediaRemovable"), ejectable: bool_of(d, "Ejectable"), @@ -177,6 +191,9 @@ impl Snapshot { crypto_backing: string_of(b, "CryptoBackingDevice"), mount_points, encrypted, + table: iface("PartitionTable").is_some(), + partition_of: iface("Partition").map(|p| string_of(p, "Table")).filter(|t| t != NONE).unwrap_or_default(), + swap: iface("Swapspace").is_some_and(|w| bool_of(w, "Active")), }, ); } @@ -198,6 +215,7 @@ impl Snapshot { /// shows as what's inside it. pub fn volumes(&self) -> Vec { let mut out = Vec::new(); + let mut formattable: HashMap<&str, bool> = HashMap::new(); for block in self.blocks.values() { let underlying = self.underlying(block); let Some(drive) = self.drives.get(&underlying.drive) else { continue }; @@ -220,6 +238,7 @@ impl Snapshot { locked, unlocked: block.crypto_backing != NONE && !block.crypto_backing.is_empty(), removable: drive.can_come_out(), + formattable: *formattable.entry(drive.path.as_str()).or_insert_with(|| self.format_refusal(&drive.path).is_none()), identity: Identity { id: drive.id.clone(), size: drive.size, media_detected: drive.media_detected }, }); } @@ -235,6 +254,187 @@ impl Snapshot { fn on_drive(&self, drive: &str) -> Vec<&Block> { self.blocks.values().filter(|b| self.underlying(b).drive == drive).collect() } + + /// The block that's the whole of a drive: the one with the partition table, or the only + /// block on it that isn't a partition, as on a card with no table. + pub fn whole_disk(&self, drive: &str) -> Option<&Block> { + let whole: Vec<&Block> = self.blocks.values().filter(|b| b.drive == drive && b.partition_of.is_empty() && (b.crypto_backing.is_empty() || b.crypto_backing == NONE)).collect(); + whole.iter().find(|b| b.table).or(if whole.len() == 1 { whole.first() } else { None }).copied() + } + + /// Why the drive at `drive` can't be formatted, if it can't. Only a drive meant to come + /// out can be: removable, or on USB or a card slot. Never one udisks2 says is the system's, + /// one with the system mounted from it or swap in use on it, or one that's part of a RAID or + /// LVM set. + pub fn format_refusal(&self, drive: &str) -> Option<&'static str> { + let Some(d) = self.drives.get(drive) else { return Some("it's been taken out") }; + if !(d.removable || ["usb", "sdio", "ieee1394"].contains(&d.connection.as_str())) { + return Some("it isn't a removable drive"); + } + let blocks = self.on_drive(drive); + let system_mount = |b: &Block| b.mount_points.as_ref().is_some_and(|m| m.iter().any(|p| is_system_path(p))); + if blocks.iter().any(|b| b.hint_system || b.swap || system_mount(b)) { + return Some("the system uses it"); + } + if blocks.iter().any(|b| b.id_usage == "raid" || b.id_type == "LVM2_member") { + return Some("it's part of a RAID or LVM set"); + } + if self.whole_disk(drive).is_none() { + return Some("udisks2 doesn't show the whole drive"); + } + None + } + + /// What's on a drive, for the warning before it's formatted: each partition, or the whole + /// disk's own filesystem when it has no partitions. An unlocked partition is told by what's + /// inside it. + fn parts(&self, drive: &str) -> Vec<(&Block, Option<&Block>)> { + let Some(whole) = self.whole_disk(drive) else { return Vec::new() }; + let mut parts: Vec<&Block> = self.blocks.values().filter(|b| b.partition_of == whole.path).collect(); + if parts.is_empty() && !whole.id_usage.is_empty() { + parts.push(whole); + } + parts.into_iter().map(|p| (p, p.encrypted.clone().flatten().and_then(|c| self.blocks.get(&c)))).collect() + } +} + +/// Where the running system's own filesystems are mounted. A drive with one of them mounted from +/// it is never formatted. +fn is_system_path(p: &std::path::Path) -> bool { + const AT: [&str; 11] = ["/", "/boot", "/efi", "/home", "/usr", "/var", "/opt", "/srv", "/nix", "/root", "/etc"]; + AT.iter().any(|a| p == std::path::Path::new(a)) || ["/boot/", "/efi/", "/usr/", "/var/"].iter().any(|a| p.to_str().is_some_and(|p| p.starts_with(a))) +} + +/// A filesystem a drive can be formatted with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FsKind { + Exfat, + Fat32, + Ext4, +} + +impl FsKind { + /// In the order they're offered, the one for most drives first. + pub const ALL: [FsKind; 3] = [FsKind::Exfat, FsKind::Fat32, FsKind::Ext4]; + + /// What it's called. + pub fn name(self) -> &'static str { + match self { + FsKind::Exfat => "exFAT", + FsKind::Fat32 => "FAT32", + FsKind::Ext4 => "ext4", + } + } + + /// What udisks2 calls it. + pub fn udisks(self) -> &'static str { + match self { + FsKind::Exfat => "exfat", + FsKind::Fat32 => "vfat", + FsKind::Ext4 => "ext4", + } + } + + /// Its partition's type in a GPT: Microsoft basic data for the two that Windows and macOS + /// read, Linux filesystem data for ext4. + fn partition_type(self) -> &'static str { + match self { + FsKind::Exfat | FsKind::Fat32 => "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", + FsKind::Ext4 => "0fc63daf-8483-4772-8e79-3d69d8477de4", + } + } + + /// What its names can be, in a few words, for under the name field. + pub fn label_rule(self) -> &'static str { + match self { + FsKind::Exfat => "Up to 15 characters.", + FsKind::Fat32 => "Up to 11 letters and numbers, in capitals.", + FsKind::Ext4 => "Up to 16 bytes: accented letters take 2 or more.", + } + } + + /// The name as it'll be written, or why it can't be. FAT32 keeps names in capitals, and its + /// names are plain ASCII without the characters FAT reserves. None can have a slash, as the + /// name becomes the folder it's mounted at. An empty name is allowed: the drive then has none. + pub fn label(self, typed: &str) -> Result { + if let Some(c) = typed.chars().find(|c| c.is_control() || *c == '/') { + return Err(if c == '/' { "Names can't have “/” in them.".to_string() } else { "Names can't have control characters.".to_string() }); + } + match self { + FsKind::Exfat => { + let n = typed.encode_utf16().count(); + if n > 15 { + return Err(format!("exFAT allows 15 characters. This has {n}.")); + } + Ok(typed.to_string()) + } + FsKind::Fat32 => { + if let Some(c) = typed.chars().find(|c| !c.is_ascii() || "\"*+,./:;<=>?[\\]|".contains(*c)) { + return Err(format!("FAT32 names can't have “{c}”. Use A–Z, 0–9 and spaces.")); + } + let n = typed.len(); + if n > 11 { + return Err(format!("FAT32 allows 11 characters. This has {n}.")); + } + Ok(typed.to_ascii_uppercase()) + } + FsKind::Ext4 => { + let n = typed.len(); + if n > 16 { + return Err(format!("ext4 allows 16 bytes. This has {n}.")); + } + Ok(typed.to_string()) + } + } + } +} + +/// The package that has a program udisks2 needs to make a filesystem, as Arch names it, or the +/// program itself when it's one this doesn't know. +pub fn package_for(utility: &str) -> String { + match utility { + "mkfs.exfat" | "mkexfatfs" => "exfatprogs", + "mkfs.vfat" | "mkfs.fat" | "mkdosfs" => "dosfstools", + "mkfs.ext4" | "mke2fs" => "e2fsprogs", + other => other, + } + .to_string() +} + +/// One partition on a drive about to be formatted, as the warning tells it. +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub label: Option, + pub size: u64, + /// How much is stored on it, when it's mounted and that can be asked. + pub stored: Option, + /// It's encrypted and locked, so what's on it can't be seen. + pub locked: bool, +} + +/// A drive picked to be formatted, and what's on it now. +#[derive(Clone, Debug, PartialEq)] +pub struct FormatTarget { + pub drive: String, + pub identity: Identity, + /// The block that's the whole drive, which gets the new partition table. + pub whole: String, + /// Its maker and model, like "SanDisk Ultra", or empty when udisks2 doesn't say. + pub model: String, + pub size: u64, + pub parts: Vec, + /// The formats that can't be made here, each with the package it needs. + pub missing: Vec<(FsKind, String)>, +} + +/// How far a format has got, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum FormatStep { + Unmounting, + /// Writing a new, empty partition table. From here it can't be stopped. + Erasing, + Making, + Opening, } /// Why something couldn't be done, in words the window can show. @@ -416,14 +616,12 @@ impl Udisks { Ok(()) } - /// Unmounts everything on the volume's drive, locks what's encrypted, then ejects the media - /// if the drive can, and powers the drive off if it can, so it's safe to pull out. - pub fn eject(&self, volume: &Volume) -> Result<(), DiskError> { - let now = self.checked(volume)?; - let blocks = now.on_drive(&volume.drive); + /// Unmounts everything on a drive and locks what's encrypted. + fn release(&self, now: &Snapshot, drive: &str) -> Result<(), DiskError> { + let blocks = now.on_drive(drive); // What's inside an encrypted volume comes out first, then the volume can be locked. let mut order: Vec<&Block> = blocks.clone(); - order.sort_by_key(|b| b.crypto_backing == NONE); + order.sort_by_key(|b| b.crypto_backing == NONE || b.crypto_backing.is_empty()); for b in &order { if b.mount_points.as_ref().is_some_and(|m| !m.is_empty()) { self.unmount_block(&b.path)?; @@ -434,6 +632,14 @@ impl Udisks { self.call::<()>(&b.path, "Encrypted", "Lock", &(options(),), false)?; } } + Ok(()) + } + + /// Unmounts everything on the volume's drive, locks what's encrypted, then ejects the media + /// if the drive can, and powers the drive off if it can, so it's safe to pull out. + pub fn eject(&self, volume: &Volume) -> Result<(), DiskError> { + let now = self.checked(volume)?; + self.release(&now, &volume.drive)?; let Some(drive) = now.drives.get(&volume.drive) else { return Err(DiskError::Changed) }; // Ejecting opens a tray or lets a card go. Powering off then makes it safe to pull out, // and a drive that can be powered off doesn't need its eject to have worked. @@ -456,6 +662,81 @@ impl Udisks { } Ok(()) } + + /// The program udisks2 is missing to make `kind`, if it is. A udisks2 too old to say is + /// taken at its word when it formats. + fn missing(&self, kind: FsKind) -> Option { + match self.call::<(bool, String)>(MANAGER, "Manager", "CanFormat", &(kind.udisks(),), false) { + Ok((false, utility)) => Some(utility), + _ => None, + } + } + + /// The volume's drive, and what's on it, once it's been checked that it can be formatted. + pub fn look_to_format(&self, volume: &Volume) -> Result { + let now = self.checked(volume)?; + if let Some(why) = now.format_refusal(&volume.drive) { + return Err(DiskError::Other(why.to_string())); + } + let (Some(drive), Some(whole)) = (now.drives.get(&volume.drive), now.whole_disk(&volume.drive)) else { return Err(DiskError::Changed) }; + let parts = now + .parts(&volume.drive) + .into_iter() + .map(|(p, inside)| { + let shown = inside.unwrap_or(p); + let label = [&shown.label, &shown.hint_name, &p.label, &p.hint_name].into_iter().find(|l| !l.is_empty()).cloned(); + // What's stored, as the filesystem says, when it's mounted to ask. + let stored = shown.mount_points.as_ref().and_then(|m| m.first()).and_then(|at| rustix::fs::statvfs(at).ok()).map(|s| (s.f_blocks - s.f_bfree.min(s.f_blocks)).saturating_mul(s.f_frsize)); + Part { label, size: p.size, stored, locked: p.encrypted == Some(None) } + }) + .collect(); + let model = [drive.vendor.as_str(), drive.model.as_str()].into_iter().filter(|s| !s.is_empty()).collect::>().join(" "); + let missing = FsKind::ALL.into_iter().filter_map(|k| self.missing(k).map(|u| (k, package_for(&u)))).collect(); + Ok(FormatTarget { drive: drive.path.clone(), identity: volume.identity.clone(), whole: whole.path.clone(), model, size: drive.size, parts, missing }) + } + + /// Erases the whole drive and makes one partition of `kind` filling it, named `label` (as + /// `FsKind::label` gives it), then mounts it and says where. It unmounts and locks what's + /// on the drive first, writes a new GPT partition table, then makes the partition from 1 MiB + /// in. `step` hears each step as it starts, and saying no before the erasing stops it there; + /// after that it can't be stopped. A drive that's changed, or can't be formatted now, is left + /// alone. polkit asks once, at the erasing. + pub fn format(&self, target: &FormatTarget, kind: FsKind, label: &str, step: &mut dyn FnMut(FormatStep) -> bool) -> Result, DiskError> { + let now = self.snapshot()?; + if !now.same_drive(&target.drive, &target.identity) || now.whole_disk(&target.drive).map(|b| b.path.as_str()) != Some(target.whole.as_str()) { + return Err(DiskError::Changed); + } + if let Some(why) = now.format_refusal(&target.drive) { + return Err(DiskError::Other(why.to_string())); + } + if !step(FormatStep::Unmounting) { + return Err(DiskError::Cancelled); + } + self.release(&now, &target.drive)?; + if !step(FormatStep::Erasing) { + return Err(DiskError::Cancelled); + } + self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false)?; + step(FormatStep::Making); + let mut made = options(); + made.insert("label", Variant::from(label.to_string())); + // On ext4, the drive's top folder is made the user's, or nothing could be put on it. + if kind == FsKind::Ext4 { + made.insert("take-ownership", Variant::from(true)); + } + let created: OwnedObjectPath = self.call(&target.whole, "PartitionTable", "CreatePartitionAndFormat", &(1u64 << 20, 0u64, kind.partition_type(), "", options(), kind.udisks(), made), false)?; + step(FormatStep::Opening); + // It's formatted. Its filesystem can take a moment to show, and not opening it isn't + // worth more than saying it's done. + for _ in 0..20 { + match self.mount_block(created.as_str()) { + Ok(at) => return Ok(Some(at)), + Err(DiskError::Changed) => std::thread::sleep(Duration::from_millis(50)), + Err(_) => break, + } + } + Ok(None) + } } #[cfg(test)] @@ -493,6 +774,10 @@ mod tests { ]) } + fn partition_of(table: &str) -> Properties { + props(vec![("Table", v(Variant::from(OwnedObjectPath::try_from(format!("{ROOT}/block_devices/{table}")).unwrap())))]) + } + fn mounts(points: &[&str]) -> Properties { let list: Vec> = points.iter().map(|p| [p.as_bytes(), b"\0"].concat()).collect(); props(vec![("MountPoints", v(Variant::from(list)))]) @@ -506,10 +791,10 @@ mod tests { drive(&mut o, "Stick", "Kingston-DataTraveler-1234", true); object(&mut o, "block_devices/nvme0n1p1", vec![("Block", block("nvme0n1p1", "Internal", "", "filesystem", true)), ("Filesystem", mounts(&["/boot"]))]); object(&mut o, "block_devices/sdb", vec![("Block", block("sdb", "Stick", "", "", false)), ("PartitionTable", props(vec![]))]); - object(&mut o, "block_devices/sdb1", vec![("Block", block("sdb1", "Stick", "PHOTOS", "filesystem", false)), ("Filesystem", mounts(&["/run/media/me/PHOTOS"]))]); + object(&mut o, "block_devices/sdb1", vec![("Block", block("sdb1", "Stick", "PHOTOS", "filesystem", false)), ("Filesystem", mounts(&["/run/media/me/PHOTOS"])), ("Partition", partition_of("sdb"))]); let cleartext = if unlocked { format!("{ROOT}/block_devices/dm_2d1") } else { "/".to_string() }; - object(&mut o, "block_devices/sdb2", vec![("Block", block("sdb2", "Stick", "", "crypto", false)), ("Encrypted", props(vec![("CleartextDevice", v(Variant::from(OwnedObjectPath::try_from(cleartext).unwrap())))]))]); - object(&mut o, "block_devices/sdb3", vec![("Block", block("sdb3", "Stick", "SPARE", "filesystem", false)), ("Filesystem", mounts(&[]))]); + object(&mut o, "block_devices/sdb2", vec![("Block", block("sdb2", "Stick", "", "crypto", false)), ("Encrypted", props(vec![("CleartextDevice", v(Variant::from(OwnedObjectPath::try_from(cleartext).unwrap())))])), ("Partition", partition_of("sdb"))]); + object(&mut o, "block_devices/sdb3", vec![("Block", block("sdb3", "Stick", "SPARE", "filesystem", false)), ("Filesystem", mounts(&[])), ("Partition", partition_of("sdb"))]); if unlocked { object(&mut o, "block_devices/dm_2d1", vec![("Block", block("dm_2d1", "/", "SECRETS", "filesystem", false)), ("Filesystem", mounts(&["/run/media/me/SECRETS"]))]); } @@ -565,6 +850,58 @@ mod tests { assert!(!Snapshot::from_objects(&gone).same_drive(&picked.drive, &picked.identity)); } + #[test] + fn only_a_removable_drive_the_system_does_not_use_can_be_formatted() { + let stick = format!("{ROOT}/drives/Stick"); + let s = Snapshot::from_objects(&machine(true)); + assert_eq!(s.format_refusal(&stick), None); + assert!(s.volumes().iter().all(|v| v.formattable), "the stick's volumes offer it"); + assert_eq!(s.whole_disk(&stick).map(|b| b.path.as_str()), Some(format!("{ROOT}/block_devices/sdb").as_str())); + let parts: Vec<(&str, bool)> = s.parts(&stick).iter().map(|(p, inside)| (inside.map_or(p.label.as_str(), |i| i.label.as_str()), p.encrypted.is_some())).collect(); + assert_eq!(parts, [("PHOTOS", false), ("SECRETS", true), ("SPARE", false)], "each partition, an unlocked one by what's inside"); + assert_eq!(s.format_refusal(&format!("{ROOT}/drives/Internal")), Some("it isn't a removable drive")); + // An internal disk udisks2 doesn't call the system's still shows, but isn't offered. + let mut o = machine(false); + drive(&mut o, "Data", "WD-Blue", false); + object(&mut o, "block_devices/sdc1", vec![("Block", block("sdc1", "Data", "DATA", "filesystem", false)), ("Filesystem", mounts(&["/run/media/me/DATA"]))]); + let data = Snapshot::from_objects(&o).volumes().into_iter().find(|v| v.label.as_deref() == Some("DATA")).unwrap(); + assert!(!data.formattable); + // A stick with anything of the system's on it: marked so, holding /boot, or swap. + for (what, iface) in [("system", None), ("boot", Some(("Filesystem", mounts(&["/boot"])))), ("efi", Some(("Filesystem", mounts(&["/boot/efi"])))), ("swap", Some(("Swapspace", props(vec![("Active", v(Variant::Bool(true)))]))))] { + let mut o = machine(false); + let mut parts = vec![("Block", block("sdb4", "Stick", "X", "other", what == "system")), ("Partition", partition_of("sdb"))]; + parts.extend(iface); + object(&mut o, "block_devices/sdb4", parts); + let s = Snapshot::from_objects(&o); + assert_eq!(s.format_refusal(&stick), Some("the system uses it"), "{what}"); + assert!(s.volumes().iter().all(|v| !v.formattable), "{what}: no volume on it offers it"); + } + // Part of an LVM set. + let mut o = machine(false); + let mut pv = block("sdb4", "Stick", "", "raid", false); + pv.insert("IdType".into(), v(Variant::from("LVM2_member".to_string()))); + object(&mut o, "block_devices/sdb4", vec![("Block", pv)]); + assert_eq!(Snapshot::from_objects(&o).format_refusal(&stick), Some("it's part of a RAID or LVM set")); + } + + #[test] + fn names_fit_the_format() { + assert_eq!(FsKind::Exfat.label("Holiday photos"), Ok("Holiday photos".into())); + assert_eq!(FsKind::Exfat.label("Fotos de férias!"), Err("exFAT allows 15 characters. This has 16.".into())); + assert_eq!(FsKind::Exfat.label("Fotos de féria"), Ok("Fotos de féria".into()), "characters, not bytes"); + assert_eq!(FsKind::Fat32.label("photos 2026"), Ok("PHOTOS 2026".into()), "in capitals"); + assert_eq!(FsKind::Fat32.label("photos 20266"), Err("FAT32 allows 11 characters. This has 12.".into())); + assert_eq!(FsKind::Fat32.label("fotos.old"), Err("FAT32 names can't have “.”. Use A–Z, 0–9 and spaces.".into())); + assert_eq!(FsKind::Fat32.label("férias"), Err("FAT32 names can't have “é”. Use A–Z, 0–9 and spaces.".into())); + assert_eq!(FsKind::Ext4.label("sixteen-letters!"), Ok("sixteen-letters!".into())); + assert_eq!(FsKind::Ext4.label("dezasseis-férias"), Err("ext4 allows 16 bytes. This has 17.".into())); + assert_eq!(FsKind::Ext4.label("a/b"), Err("Names can't have “/” in them.".into())); + assert_eq!(FsKind::Fat32.label(""), Ok(String::new()), "no name at all is fine"); + assert_eq!(package_for("mkfs.exfat"), "exfatprogs"); + assert_eq!(package_for("mkfs.vfat"), "dosfstools"); + assert_eq!(package_for("mkfs.ext4"), "e2fsprogs"); + } + #[test] fn udisks_errors_become_words() { let err = |name: &str, message: &str| zbus::Error::MethodError(name.try_into().unwrap(), Some(message.to_string()), zbus::message::Message::method_call("/", "x").build(&()).unwrap()); @@ -612,6 +949,22 @@ mod tests { self.output.read_line(&mut line).unwrap(); assert_eq!(line.trim(), "ok", "{command}"); } + + /// The formatting calls it was asked to make. + fn asked(&mut self) -> Vec { + use std::io::{BufRead, Write}; + writeln!(self.input, "asked").unwrap(); + let mut out = Vec::new(); + loop { + let mut line = String::new(); + self.output.read_line(&mut line).unwrap(); + match line.trim().strip_prefix("asked ") { + Some(a) => out.push(a.to_string()), + None => break assert_eq!(line.trim(), "ok"), + } + } + out + } } impl Drop for StandIn { @@ -675,6 +1028,74 @@ mod tests { assert!(udisks.snapshot().unwrap().volumes().is_empty(), "powered off and gone"); } + #[test] + fn formatting_a_drive_through_udisks() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + standin.say("drive Stick Kingston-1234"); + standin.say("model Stick SanDisk Ultra"); + standin.say("fs sdb1 Stick PHOTOS"); + standin.say("luks sdb2 Stick hunter2 SECRETS"); + let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let photos = udisks.snapshot().unwrap().volumes()[0].clone(); + assert!(photos.formattable); + udisks.mount(&photos).unwrap(); + let secret = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.locked).unwrap(); + udisks.unlock(&secret, "hunter2").unwrap(); + standin.say("lacks ext4 mkfs.ext4"); + let target = udisks.look_to_format(&photos).unwrap(); + assert_eq!(target.model, "SanDisk Ultra"); + assert_eq!(target.whole, format!("{ROOT}/block_devices/Stick")); + let parts: Vec<(Option<&str>, bool, bool)> = target.parts.iter().map(|p| (p.label.as_deref(), p.stored.is_some(), p.locked)).collect(); + assert_eq!(parts, [(Some("PHOTOS"), true, false), (Some("SECRETS"), true, false)], "what's on it, and how much is stored where it's mounted"); + assert_eq!(target.missing, [(FsKind::Ext4, "e2fsprogs".to_string())]); + // Stopped before the erasing: nothing's asked of udisks2 but the unmounting. + let mut steps = Vec::new(); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |s| { steps.push(s); s < FormatStep::Erasing }), Err(DiskError::Cancelled)); + assert_eq!(steps, [FormatStep::Unmounting, FormatStep::Erasing]); + assert!(standin.asked().is_empty()); + // A no at polkit's prompt changes nothing. + let target = udisks.look_to_format(&udisks.snapshot().unwrap().volumes()[0]).unwrap(); + standin.say("refuse"); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |_| true), Err(DiskError::Cancelled)); + assert_eq!(udisks.snapshot().unwrap().volumes().len(), 2, "still there"); + // Formatted: everything was unmounted and locked first, the stand-in refusing otherwise, + // then a new table and one partition, which is mounted. + let mut steps = Vec::new(); + let at = udisks.format(&target, FsKind::Exfat, "Holiday", &mut |s| { steps.push(s); true }).unwrap(); + assert_eq!(steps, [FormatStep::Unmounting, FormatStep::Erasing, FormatStep::Making, FormatStep::Opening]); + assert_eq!(at, Some(standin.root.path().join("Holiday"))); + let now = udisks.snapshot().unwrap().volumes(); + let shown: Vec<(Option<&str>, bool)> = now.iter().map(|v| (v.label.as_deref(), v.mount.is_some())).collect(); + assert_eq!(shown, [(Some("Holiday"), true)]); + assert_eq!(standin.asked(), [ + "Format Stick gpt auth.no_user_interaction=false", + "Format Stick gpt auth.no_user_interaction=false", + "CreatePartitionAndFormat Stick 1048576 0 ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 \"\" exfat auth.no_user_interaction=false label=Holiday", + ]); + // ext4's top folder is made the user's. + let target = udisks.look_to_format(&now[0]).unwrap(); + udisks.format(&target, FsKind::Ext4, "linux", &mut |_| true).unwrap(); + assert!(standin.asked().last().unwrap().ends_with("0fc63daf-8483-4772-8e79-3d69d8477de4 \"\" ext4 auth.no_user_interaction=false label=linux take-ownership=true")); + // Another stick in its place is left alone. + standin.say("unplug Stick"); + std::thread::sleep(Duration::from_millis(100)); + standin.say("drive Stick SanDisk-9999"); + standin.say("fs sdb1 Stick OTHER"); + assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true), Err(DiskError::Changed)); + // A drive that isn't removable, or that the system uses, is never formatted. + standin.say("internal Disk WD-1"); + standin.say("fs sdc1 Disk DATA"); + let data = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("DATA")).unwrap(); + assert!(!data.formattable); + assert_eq!(udisks.look_to_format(&data), Err(DiskError::Other("it isn't a removable drive".into()))); + let other = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("OTHER")).unwrap(); + let target = udisks.look_to_format(&other).unwrap(); + standin.say("at sdb1 /boot"); + assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true), Err(DiskError::Other("the system uses it".into()))); + assert_eq!(standin.asked().len(), 5, "nothing more was asked"); + } + #[test] fn something_else_mounting_it_first_still_says_where_it_is() { assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); diff --git a/crates/core/src/ops.rs b/crates/core/src/ops.rs index 4afd3ee..5d9c212 100644 --- a/crates/core/src/ops.rs +++ b/crates/core/src/ops.rs @@ -272,6 +272,14 @@ impl Engine { Self { trash, sink, next_id: Arc::new(AtomicU64::new(1)), force_exdev: false, force_sync_error: false, force_no_sendfile: false, slow_copy: None, extractor: crate::archive::BSDTAR.into(), extract_limits: crate::archive::Limits::default() } } + /// A job for work done somewhere else, like formatting a drive, so it shows and can be + /// stopped as the others are. Its number is from the same count. Whatever does the work + /// keeps its progress and says when it's over; nothing here runs it. + pub fn outside_job(&self, label: String) -> Job { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + Job { id, label, progress: Arc::new(Progress::default()), cancel: Arc::new(AtomicBool::new(false)) } + } + pub fn start(&self, request: Request) -> Job { let request = clean_request(request); let id = self.next_id.fetch_add(1, Ordering::Relaxed); diff --git a/crates/core/src/places.rs b/crates/core/src/places.rs index ed2820f..3536c75 100644 --- a/crates/core/src/places.rs +++ b/crates/core/src/places.rs @@ -203,7 +203,7 @@ mod tests { use crate::disks::Identity; let m = parse_mountinfo(b"5 1 8:17 / /run/media/me/PHOTOS rw - exfat /dev/sdb1 rw\n7 1 0:9 / /mnt/share rw - nfs4 host:/x rw\n"); let identity = Identity { id: "stick".into(), size: 1, media_detected: 1 }; - let volume = |label: Option<&str>, mount: Option<&str>| Volume { block: "b".into(), drive: "d".into(), label: label.map(String::from), size: 8_000_000_000, mount: mount.map(PathBuf::from), locked: false, unlocked: false, removable: true, identity: identity.clone() }; + let volume = |label: Option<&str>, mount: Option<&str>| Volume { block: "b".into(), drive: "d".into(), label: label.map(String::from), size: 8_000_000_000, mount: mount.map(PathBuf::from), locked: false, unlocked: false, removable: true, formattable: true, identity: identity.clone() }; let volumes = [volume(Some("PHOTOS"), Some("/run/media/me/PHOTOS")), volume(None, None)]; let places = all_disk_places(&volumes, &m, |v| format!("{} GB Volume", v.size / 1_000_000_000)); let shown: Vec<(&str, &str, bool)> = places.iter().map(|p| (p.label.as_str(), p.path.to_str().unwrap(), p.volume.is_some())).collect(); diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index 5430236..06c2374 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -60,7 +60,7 @@ pub mod aliasos { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xB9827B; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -132,7 +132,7 @@ pub mod aliasos_amber { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xC97B72; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -204,7 +204,7 @@ pub mod aliasos_azure { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xC97B72; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -276,7 +276,7 @@ pub mod aliasos_teal { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xC97B72; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -348,7 +348,7 @@ pub mod ayu_dark { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xEA6C73; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -420,7 +420,7 @@ pub mod last_horizon { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xC38B7B; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -492,7 +492,7 @@ pub mod matte_black { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xD16969; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -564,7 +564,7 @@ pub mod osaka_jade { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xFF5345; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -636,7 +636,7 @@ pub mod retro_82 { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xF85525; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -708,7 +708,7 @@ pub mod light { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xB8382B; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0xFFFFFF; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -780,7 +780,7 @@ pub mod dark { /// Errors: a name that can't be used, a failed job's bar, an error notice's bar, Quick View's muted speaker. The theme's color1 (or red), moved toward the text until it has 4.5:1 on base, surface and hover. pub const DANGER: u32 = 0xE0727A; - /// The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast. + /// The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast. pub const ON_DANGER: u32 = 0x000000; /// Behind an error notice and a rename's problem: surface blended 16% toward danger, held so text, quieter text and danger stay at 4.5:1 on it. @@ -1062,6 +1062,12 @@ pub mod size { /// A checkbox's box. pub const CHECKBOX: f32 = 14.0; + /// A choice's round button among others, like the format dialog's formats: its outline. + pub const RADIO: f32 = 14.0; + + /// The dot in the round button of the choice picked. + pub const RADIO_DOT: f32 = 6.0; + /// The small mark on a file's icon (a link). pub const EMBLEM: f32 = 12.0; @@ -1131,6 +1137,12 @@ pub mod size { /// A dialog's field label column (Find, Replace with, User, Password). pub const FORM_LABEL: f32 = 104.0; + /// The Format dialog's width (crates/app/src/format_drive.rs). + pub const FORMAT_DIALOG_WIDTH: f32 = 560.0; + + /// A format's row in the Format dialog: its name, and what it's for under it. A 44 px target. + pub const FORMAT_OPTION_ROW: f32 = 44.0; + /// The Rename many dialog's width. pub const RENAME_MANY_WIDTH: f32 = 680.0; diff --git a/design/tokens.json b/design/tokens.json index 1e14109..df0637d 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -375,7 +375,7 @@ "light": "#ffffff", "dark": "#000000" }, - "usage": "The label of a focused Delete or Empty Trash button on its danger fill: black or white, whichever has more contrast." + "usage": "The label of a focused Delete, Empty Trash or Erase and Format button on its danger fill: black or white, whichever has more contrast." }, { "name": "danger-tint", @@ -892,6 +892,16 @@ "value": "14px", "usage": "A checkbox's box." }, + { + "name": "radio", + "value": "14px", + "usage": "A choice's round button among others, like the format dialog's formats: its outline." + }, + { + "name": "radio-dot", + "value": "6px", + "usage": "The dot in the round button of the choice picked." + }, { "name": "emblem", "value": "12px", @@ -1007,6 +1017,16 @@ "value": "104px", "usage": "A dialog's field label column (Find, Replace with, User, Password)." }, + { + "name": "format-dialog-width", + "value": "560px", + "usage": "The Format dialog's width (crates/app/src/format_drive.rs)." + }, + { + "name": "format-option-row", + "value": "44px", + "usage": "A format's row in the Format dialog: its name, and what it's for under it. A 44 px target." + }, { "name": "rename-many-width", "value": "680px", @@ -1559,7 +1579,7 @@ "fg": "on-danger", "bg": "danger", "min": 4.5, - "usage": "A focused Delete or Empty Trash button's label." + "usage": "A focused Delete, Empty Trash or Erase and Format button's label." }, { "fg": "foreground", diff --git a/tests/a11y_client.py b/tests/a11y_client.py index 2603bb4..66cc275 100644 --- a/tests/a11y_client.py +++ b/tests/a11y_client.py @@ -180,7 +180,7 @@ def describe(f): STATES = {"focused": Atspi.StateType.FOCUSED, "selected": Atspi.StateType.SELECTED, "enabled": Atspi.StateType.SENSITIVE, "showing": Atspi.StateType.SHOWING, "checked": Atspi.StateType.CHECKED, "editable": Atspi.StateType.EDITABLE, "active": Atspi.StateType.ACTIVE} -STATES |= {"default": Atspi.StateType.IS_DEFAULT, "modal": Atspi.StateType.MODAL} +STATES |= {"default": Atspi.StateType.IS_DEFAULT, "modal": Atspi.StateType.MODAL, "invalid": Atspi.StateType.INVALID_ENTRY} def window(sub): diff --git a/tests/e2e.py b/tests/e2e.py index 076062b..b45b81e 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -1561,6 +1561,16 @@ def say(self, *lines): answer = self.proc.stdout.readline().strip() assert answer == "ok", f"{line}: {answer}" + def asked(self): + """The formatting calls the stand-in was asked to make, oldest first.""" + self.proc.stdin.write("asked\n") + self.proc.stdin.flush() + out = [] + while (line := self.proc.stdout.readline().strip()) != "ok": + assert line.startswith("asked "), line + out.append(line[len("asked "):]) + return out + def stop(self): self.proc.kill() self.proc.wait() @@ -1653,9 +1663,7 @@ def drives_mount_unlock_and_eject_from_the_sidebar(h): s = a.wait(lambda s: not s["dir"].startswith(str(media)), "gone home") # The preview can cover the eject button, so it's ejected from the drive's menu. a.click(60, place_y(s, "CARD"), 0x111) - a.wait(lambda s: s["menu"], "the drive's menu") - a.key("Up") - a.key("Return") + menu_choose(a, "Eject") s = a.wait(lambda s: place_flags(s, "CARD") is None, "ejected", timeout=10) assert not any("CARD" in n for n in s["notices"]), s["notices"] assert s["previewing"] is None, "the preview of its picture closed" @@ -1665,6 +1673,258 @@ def drives_mount_unlock_and_eject_from_the_sidebar(h): disks.stop() +def open_format_dialog(a, label): + """Opens the Format dialog from a drive's menu in the sidebar.""" + s = a.state() + a.click(60, place_y(s, label), 0x111) + # It's always last, and Unmount above it can be unavailable, which Down skips. + items = a.wait(lambda s: s["menu"], "the menu")["menu_items"] + assert items[-1] == "Format…", items + a.key("Up", "Return") + return a.wait(lambda s: s["dialog"] == "format", "the Format dialog", timeout=10) + + +def format_focus(a, focus): + return a.wait(lambda s: s["format"] and s["format"]["focus"] == focus, f"{focus} has the keyboard") + + +@check +def a_removable_drive_is_formatted_from_the_sidebar(h): + """Only through the stand-in udisks2, which formats nothing: it writes down what it was + asked and changes its own pretend drives.""" + fs = fresh_fs() + media = SCRATCH / "media" + shutil.rmtree(media, ignore_errors=True) + tree(media, {"ARCH_202512/arch/boot.img": "x" * 5000}) + disks = StandIn(media) + gtk = SCRATCH / "client/config/gtk-4.0" + shutil.rmtree(SCRATCH / "client/home/.local/state/aliasos", ignore_errors=True) + try: + disks.say("drive Stick SanDisk-1234", "model Stick SanDisk Ultra", "fs sdb1 Stick ARCH_202512", "fs sdb2 Stick ARCHISO_EF1") + # Drives never offered: one that isn't removable, one holding /boot, and one with a + # partition udisks2 marks as the system's. + disks.say("internal Disk WD-1", "fs sdc1 Disk DATA") + disks.say("drive Card SD-1", "fs mmc1 Card CARDBOOT", "fs mmc2 Card CARDDATA", "at mmc1 /boot") + disks.say("drive Sys SYS-1", "fs sys1 Sys SYSDATA", "fs sys2 Sys HIDDEN", "system sys2") + env = {"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address} + a = App(h, fs, extra_env=env) + s = a.wait(lambda s: all(place_flags(s, l) is not None for l in ("ARCH_202512", "ARCHISO_EF1", "DATA", "CARDDATA", "SYSDATA")), "the drives") + assert s["base"] == 0xfafafa, "light" + for label in ("DATA", "CARDDATA", "SYSDATA"): + a.click(60, place_y(s, label), 0x111) + items = a.wait(lambda s: s["menu"], f"{label}'s menu")["menu_items"] + assert "Format…" not in items, f"{label}: {items}" + a.key("Escape") + a.wait(lambda s: not s["menu"], "closed") + # Opened, so the warning can say how much is stored on it. + click_place(a, s, "ARCH_202512") + a.wait(lambda s: s["dir"] == str(media / "ARCH_202512") and s["names"] == ["arch"], "the stick's files", timeout=10) + a.wait(lambda s: place_flags(s, "ARCH_202512") == {"mounted", "eject"}, "shown as mounted") + + # The warning names the drive and lists what's on it, and the keyboard starts on Cancel. + s = open_format_dialog(a, "ARCH_202512") + f = s["format"] + assert f["title"] == "Format “SanDisk Ultra, 16.0 GB”?", f + assert re.fullmatch(r"Everything on “SanDisk Ultra, 16.0 GB” will be erased: the “ARCH_202512” partition, with [0-9.]+ [kMGT]?B of files, and the 8\.0 GB “ARCHISO_EF1” partition\. This can't be undone\.", f["warning"]), f["warning"] + assert (f["focus"], f["kind"], f["name"], f["ready"]) == ("Button(1)", "exFAT", "", True), f + assert [k[0] for k in f["kinds"]] == ["exFAT", "FAT32", "ext4"] and all(k[1] for k in f["kinds"]), f["kinds"] + a.shot("format-dialog-light") + # Enter on Cancel cancels. + a.key("Return") + a.wait(lambda s: s["dialog"] == "", "cancelled") + + # Enter never confirms: not from the name, the formats, or Erase and Format itself. + open_format_dialog(a, "ARCH_202512") + a.key("Tab") + format_focus(a, "Name") + a.type("Holiday") + a.wait(lambda s: s["format"]["name"] == "Holiday", "named") + for focus in ("Name", "Kind", "Button(0)"): + format_focus(a, focus) + a.key("Return") + a.key("KP_Enter") + time.sleep(0.3) + assert a.state()["dialog"] == "format", f"Enter on {focus} closed it" + if focus == "Kind": + a.shot("format-kinds-focused-light") + a.key("Tab") + format_focus(a, "Button(1)") + a.key("ISO_Left_Tab", mods=["shift"]) + format_focus(a, "Button(0)") + a.shot("format-erase-focused-light") + assert disks.asked() == [], "nothing was asked of udisks2" + + # The name is checked against each format's limits, under the field. + a.key("ISO_Left_Tab", mods=["shift"]) + format_focus(a, "Kind") + a.key("Down") + a.wait(lambda s: s["format"]["kind"] == "FAT32", "FAT32") + a.key("ISO_Left_Tab", mods=["shift"]) + format_focus(a, "Name") + a.type(" photos") + s = a.wait(lambda s: s["format"]["error"], "too long for FAT32") + assert s["format"]["line"] == "FAT32 allows 11 characters. This has 14." and not s["format"]["ready"], s["format"] + a.shot("format-name-error-light") + # Erase and Format pressed with a name that can't be used goes back to the name. + a.key("Tab", "Tab") + format_focus(a, "Button(0)") + a.key("space") + format_focus(a, "Name") + assert a.state()["dialog"] == "format" and disks.asked() == [] + a.key("Down") + a.key("Up") + a.key("Tab") + format_focus(a, "Kind") + a.key("Down") + s = a.wait(lambda s: s["format"]["kind"] == "ext4" and not s["format"]["error"], "fits ext4") + assert s["format"]["line"].startswith("Up to 16 bytes"), s["format"] + a.key("Down") + a.wait(lambda s: s["format"]["kind"] == "exFAT" and s["format"]["ready"], "fits exFAT, round past ext4") + a.key("ISO_Left_Tab", mods=["shift"]) + format_focus(a, "Name") + a.type(" 2026") + s = a.wait(lambda s: s["format"]["error"], "too long for exFAT") + assert s["format"]["line"] == "exFAT allows 15 characters. This has 19.", s["format"] + a.key("a", mods=["ctrl"]) + a.type("Holiday") + + # exFAT: erased on purpose, with Space on Erase and Format. The window lets go of the + # drive first, then it's there again by its new name, mounted. + a.key("Tab", "Tab") + format_focus(a, "Button(0)") + a.key("space") + s = a.wait(lambda s: place_flags(s, "Holiday") == {"mounted", "eject"} and s["jobs"] == 0, "formatted and mounted", timeout=10) + assert place_flags(s, "ARCH_202512") is None and place_flags(s, "ARCHISO_EF1") is None, s["places"] + assert not s["dir"].startswith(str(media / "ARCH_202512")), "the window left the drive" + assert "Formatted “SanDisk Ultra, 16.0 GB” as exFAT" in s["notices"], s["notices"] + asked = disks.asked() + assert asked == ["Format Stick gpt auth.no_user_interaction=false", 'CreatePartitionAndFormat Stick 1048576 0 ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 "" exfat auth.no_user_interaction=false label=Holiday'], asked + + # FAT32, its name kept in capitals. + s = open_format_dialog(a, "Holiday") + assert re.fullmatch(r"Everything on “SanDisk Ultra, 16.0 GB” will be erased: the “Holiday” partition, with .+ of files\. This can't be undone\.", s["format"]["warning"]), s["format"] + a.key("Tab") + a.type("camera") + a.key("Tab", "Down") + a.wait(lambda s: s["format"]["kind"] == "FAT32" and s["format"]["ready"], "FAT32") + a.key("Tab", "space") + s = a.wait(lambda s: place_flags(s, "CAMERA") == {"mounted", "eject"} and s["jobs"] == 0, "formatted as FAT32", timeout=10) + assert disks.asked()[-1] == 'CreatePartitionAndFormat Stick1 1048576 0 ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 "" vfat auth.no_user_interaction=false label=CAMERA' or disks.asked()[-1].endswith('"" vfat auth.no_user_interaction=false label=CAMERA'), disks.asked() + + # ext4, whose top folder is made the user's. + open_format_dialog(a, "CAMERA") + a.key("Tab") + a.type("linux") + a.key("Tab", "Down", "Down") + a.wait(lambda s: s["format"]["kind"] == "ext4" and s["format"]["ready"], "ext4") + a.key("Tab", "space") + s = a.wait(lambda s: place_flags(s, "linux") == {"mounted", "eject"} and s["jobs"] == 0, "formatted as ext4", timeout=10) + assert disks.asked()[-1].endswith('0fc63daf-8483-4772-8e79-3d69d8477de4 "" ext4 auth.no_user_interaction=false label=linux take-ownership=true'), disks.asked() + + # A no at the password prompt changes nothing, and needs no notice. + notices = s["notices"] + disks.say("refuse") + open_format_dialog(a, "linux") + a.key("ISO_Left_Tab", mods=["shift"]) + format_focus(a, "Button(0)") + a.key("space") + s = a.wait(lambda s: s["dialog"] == "" and s["jobs"] == 0 and disks.asked()[-1].startswith("Format Stick gpt"), "asked, and refused", timeout=10) + time.sleep(0.3) + s = a.state() + assert place_flags(s, "linux") is not None and s["notices"] == notices, s + + # A format whose tool isn't installed is unavailable, and names its package. + disks.say("lacks exfat mkfs.exfat") + s = open_format_dialog(a, "linux") + f = s["format"] + assert f["kinds"][0] == ["exFAT", False, "Unavailable: needs the exfatprogs package"] and f["kind"] == "FAT32", f + a.key("Tab", "Tab", "Down", "Down") + a.wait(lambda s: s["format"]["kind"] == "FAT32", "round past exFAT to FAT32") + a.shot("format-missing-tool-light") + a.key("Escape") + a.wait(lambda s: s["dialog"] == "", "cancelled") + assert a.alive() + a.close() + + # The same dialog in the dark theme. + gtk.mkdir(parents=True, exist_ok=True) + (gtk / "settings.ini").write_text("[Settings]\ngtk-application-prefer-dark-theme=1\n") + a = App(h, fs, extra_env=env) + s = a.wait(lambda s: place_flags(s, "linux") is not None, "the stick") + assert s["base"] != 0xfafafa and s["base"] < 0x808080, f"dark: {s['base']:06x}" + open_format_dialog(a, "linux") + a.shot("format-missing-tool-dark") + a.key("Tab") + a.type("A name far too long") + a.wait(lambda s: s["format"]["error"], "too long") + a.shot("format-name-error-dark") + a.key("Tab") + format_focus(a, "Kind") + a.shot("format-kinds-focused-dark") + a.key("Tab") + format_focus(a, "Button(0)") + a.shot("format-erase-focused-dark") + a.key("Tab") + format_focus(a, "Button(1)") + a.shot("format-dialog-dark") + a.key("Escape") + a.close() + finally: + shutil.rmtree(gtk, ignore_errors=True) + disks.stop() + + +@check +def a_screen_reader_hears_the_format_warning(h): + assert REGISTRYD.exists(), "needs at-spi2-core" + fs = fresh_fs() + media = SCRATCH / "media" + shutil.rmtree(media, ignore_errors=True) + disks = StandIn(media) + sr = ScreenReader() + try: + disks.say("drive Stick SanDisk-1234", "model Stick SanDisk Ultra", "fs sdb1 Stick PHOTOS", "lacks ext4 mkfs.ext4") + a = App(h, fs, extra_env={"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address, "DBUS_SESSION_BUS_ADDRESS": sr.session.address}) + a.wait(lambda s: place_flags(s, "PHOTOS") is not None, "the stick") + sr.screen_reader(True) + sr.until("apps", lambda x: x == ["Gannet"], "registered once a screen reader is on") + s = open_format_dialog(a, "PHOTOS") + title, warning = s["format"]["title"], s["format"]["warning"] + win = json.dumps([fs.name]) + # An alert, described by its warning, which a screen reader reads as it opens. + w = sr.until(f"dump {win}", lambda w: a11y_find(w, title, "alert"), "the dialog, as an alert") + alert = a11y_find(w, title, "alert") + assert alert["description"] == warning and warning.startswith("Everything on “SanDisk Ultra, 16.0 GB” will be erased"), alert + assert "modal" in alert["states"], alert + name = a11y_find(alert, "Name", "entry") + assert name and name["description"] == "Up to 15 characters." and "invalid" not in name["states"], name + radios = [a11y_find(alert, k, "radio button") for k in ("exFAT", "FAT32", "ext4")] + assert all(radios), alert + assert "checked" in radios[0]["states"] and "enabled" in radios[0]["states"], radios[0] + assert "enabled" not in radios[2]["states"] and radios[2]["description"] == "Unavailable: needs the e2fsprogs package", radios[2] + erase, cancel = a11y_find(alert, "Erase and Format", "button"), a11y_find(alert, "Cancel", "button") + assert a11y_focus(w) == ["Cancel"], a11y_focus(w) + assert "default" in cancel["states"] and "default" not in erase["states"], (cancel, erase) + # A name too long: the field is marked so, and says why. + a.key("Tab") + a.type("Sixteen letters!") + w = sr.until(f"dump {win}", lambda w: "invalid" in (a11y_find(w, "Name", "entry") or {"states": []})["states"], "the name marked as invalid") + name = a11y_find(w, "Name", "entry") + assert name["description"] == "exFAT allows 15 characters. This has 16.", name + assert "enabled" not in a11y_find(w, "Erase and Format", "button")["states"], "can't go ahead" + assert "default" not in a11y_find(w, "Cancel", "button")["states"], "Enter presses nothing from the name" + # A format picked with the screen reader, and Cancel pressed with it. + assert sr.ask(f'do {json.dumps([fs.name, title, "Format", "FAT32"])}') is True + a.wait(lambda s: s["format"]["kind"] == "FAT32", "FAT32 picked") + assert sr.ask(f'do {json.dumps([fs.name, title, "Cancel"])}') is True + a.wait(lambda s: s["dialog"] == "", "cancelled") + assert disks.asked() == [] + a.close() + finally: + sr.stop() + disks.stop() + + class Tracker: """The stand-in GVfs mount tracker, on a private session bus, with shares that are folders.""" @@ -3035,7 +3295,7 @@ def pin_and_drive_menus_open_from_the_keyboard_and_a_screen_reader(h): a.key(*["Up"] * (len(s["places"]) - 1 - photos)) a.wait(lambda s: s["side_focus"] == photos, "on the drive") a.key("Menu") - assert a.wait(lambda s: s["menu"], "the drive's menu")["menu_items"] == ["Open", "Unmount", "Eject"] + assert a.wait(lambda s: s["menu"], "the drive's menu")["menu_items"] == ["Open", "Unmount", "Eject", "Format…"] a.shot("drive-menu-from-the-keyboard") a.key("Return") a.wait(lambda s: "mounted" in place_flags(s, "PHOTOS") and s["dir"] == str(media / "PHOTOS"), "mounted and opened", timeout=10) @@ -3078,7 +3338,7 @@ def pin_and_drive_menus_open_from_the_keyboard_and_a_screen_reader(h): t = sr.until("tree", lambda t: "Notes" not in t["places"], "the pin gone") photos = t["places"].index("PHOTOS") assert sr.ask(f"place_do {photos} 1") is True - assert a.wait(lambda s: s["menu"], "the drive's menu")["menu_items"] == ["Open", "Unmount", "Eject"] + assert a.wait(lambda s: s["menu"], "the drive's menu")["menu_items"] == ["Open", "Unmount", "Eject", "Format…"] assert sr.ask(f'do ["{w}", "", "Unmount"]') is True a.wait(lambda s: place_flags(s, "PHOTOS") == {"eject"}, "unmounted", timeout=10) a.close() From a0a485df859ea660447f9041adf2f660b7736565 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 21:58:46 -0700 Subject: [PATCH 2/4] ALI-2601: Review fixes for formatting a drive - Check the drive again after unmounting, before Block.Format: the same drive, the same whole disk and nothing of the system's on it. Abort with a clear message if it changed. Document that polkit's wait is inside Block.Format, and that identical sticks with no serial can pass as each other. - Never offer the stick a live or installer system runs from: mounted under /run/archiso, /run/initramfs, /run/live, /cdrom or /lib/live/mount, holding a loop device's backing file, or matching the boot device on the kernel's command line (root=, archisodevice=, archisolabel=). - Mount again what was mounted when a format stops or fails before the erase, and say whether nothing was erased and all of it is back, or it was left unmounted. - Show the drive as busy, and disable Unmount, Eject and Format, during a format. - Spell out FAT32's allowed characters, and refuse names that start or end with a space (or are only spaces), for every format. - Ask for FAT32 with mkfs-args -F 32 where udisks2 (2.10 or newer) passes it on. Otherwise mkfs.fat picks FAT32 from 512 MiB, and smaller drives aren't offered FAT32. - Leave MBR extended containers out of the warning; their logical partitions are listed. --- README.md | 7 +- crates/app/src/a11y.rs | 2 +- crates/app/src/app.rs | 60 ++-- crates/app/src/drives.rs | 5 +- crates/app/src/format_drive.rs | 8 +- crates/app/src/main.rs | 5 +- crates/app/src/paint.rs | 6 +- crates/core/examples/udisks-standin.rs | 76 ++++- crates/core/src/disks.rs | 381 ++++++++++++++++++++++--- tests/e2e.py | 20 +- 10 files changed, 490 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 657622f..3c70d51 100644 --- a/README.md +++ b/README.md @@ -478,8 +478,11 @@ files up to 4 GB) or ext4 (Linux only). The dialog says what will be erased: the and size, and each partition on it with how much it holds. The keyboard starts on Cancel, and Enter never erases: choose Erase and Format with the pointer, or Tab to it and press Space. The system then asks for your password. The whole drive gets a new partition table and one -partition, which is mounted when it's done. Format is only offered for drives that can come -out, never for one udisks2 marks as the system's or one the system is mounted from or swaps to. +partition, which is mounted when it's done. Cancelling at the password prompt, or stopping the +job before the erasing starts, leaves everything as it was and mounts again what was mounted; +an unlocked encrypted partition stays locked, and Gannet says so. Format is only offered for +drives that can come out, never for one udisks2 marks as the system's, one the system is +mounted from or swaps to, or the stick a live or installer system is running from. ## Network shares diff --git a/crates/app/src/a11y.rs b/crates/app/src/a11y.rs index dc4513e..19707d3 100644 --- a/crates/app/src/a11y.rs +++ b/crates/app/src/a11y.rs @@ -1257,7 +1257,7 @@ fn sidebar(app: &App, l: &Layout, mut places: Vec) -> (Vec, Vec let Some(r) = app.eject_rect(i) else { continue }; let id = EJECT0 + i as u64; let button = if let Some(v) = app.places.get(i).and_then(|p| p.volume.as_ref()) { - Node::new(id, Role::PushButton, format!("Eject {}", n.name), r, n.id).enabled(!app.drives_busy.contains(&v.block)).doing(click("Eject the drive", "")) + Node::new(id, Role::PushButton, format!("Eject {}", n.name), r, n.id).enabled(!app.drive_busy(v)).doing(click("Eject the drive", "")) } else if let Some(share) = app.share_at(i) { Node::new(id, Role::PushButton, format!("Disconnect {}", n.name), r, n.id).enabled(!app.shares_busy.contains(&share.path)).doing(click("Disconnect the share", "")) } else { diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index d597eae..b1ce79d 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -17,7 +17,7 @@ use gannet_core::mounts::Mount; use gannet_core::trash; use gannet_core::ops::{self, Answer, Choice, Conflict, Engine, Expands, Job, Request, Undo}; use gannet_core::watch::Watch; -use gannet_core::disks::{DiskError, FormatTarget, FsKind, Volume}; +use gannet_core::disks::{DiskError, FormatFailed, FormatTarget, FsKind, Volume}; use gannet_core::gvfs::{ConnectError, Share, ShareError}; use gannet_core::servers::{self, Address}; use gannet_core::bookmarks::{self, Spot}; @@ -103,7 +103,7 @@ pub enum Msg { /// What's on a drive picked to be formatted, or why it can't be. FormatLooked { volume: Volume, result: Result }, /// Formatting has finished: where the new filesystem is mounted, if it could be. - FormatDone { job: u64, target: FormatTarget, kind: FsKind, result: Result, DiskError> }, + FormatDone { job: u64, target: FormatTarget, kind: FsKind, result: Result, FormatFailed> }, /// The network shares GVfs has connected now. Shares(Vec), /// A share has been disconnected, or couldn't be. @@ -284,8 +284,10 @@ pub struct FormatLayout { /// The warning's lines, under the title. pub lines: Vec, pub name: Rect, - /// The line under the name: why it can't be used, or the format's rule for names. + /// The lines under the name: why it can't be used, or the format's rule for names, wrapped + /// to its width. It's as tall as the longest rule, so it doesn't jump as formats are picked. pub name_line: Rect, + pub name_lines: Vec, /// Where the formats' heading is drawn, beside the first. pub kinds_label: Rect, /// Each format's row, in `FsKind::ALL`'s order. @@ -3499,7 +3501,7 @@ impl App { Dialog::Unlock { volume, field, error, .. } => { if label == "Unlock" { // Kept open, waiting, until udisks2 says whether it worked. - let busy = self.drives_busy.contains(&volume.block); + let busy = self.drive_busy(&volume); let waiting = !field.text.is_empty() && self.drive_act(volume.clone(), Doing::Unlock(field.text.clone())); if waiting { self.opening = Some((volume.block.clone(), self.dir.clone())); @@ -3859,7 +3861,7 @@ impl App { return false; }; // Nothing else is done to a drive while it's formatted. - if self.drives_busy.contains(&v.block) || self.drives_busy.contains(&v.drive) { + if self.drive_busy(&v) { return false; } self.drives_busy.push(v.block.clone()); @@ -3929,19 +3931,26 @@ impl App { self.invalidate_all(); } + /// Whether something's under way on a volume: on it, or on its whole drive, as a format is. + pub fn drive_busy(&self, v: &Volume) -> bool { + self.drives_busy.contains(&v.block) || self.drives_busy.contains(&v.drive) + } + fn open_drive_menu(&mut self, v: Volume, x: i32, y: i32) { + // Nothing but opening while it's formatted. + let formatting = self.drives_busy.contains(&v.drive); let items = vec![ MenuItem { label: if v.locked { "Unlock" } else { "Open" }, keys: "", action: Action::OpenDrive, enabled: true }, // Unmounting what's inside an encrypted volume locks it, and one that's unlocked but // not mounted can still be locked. - MenuItem { label: if v.unlocked && v.mount.is_none() { "Lock" } else { "Unmount" }, keys: "", action: Action::Unmount, enabled: v.mount.is_some() || v.unlocked }, - MenuItem { label: "Eject", keys: "", action: Action::Eject, enabled: v.removable }, + MenuItem { label: if v.unlocked && v.mount.is_none() { "Lock" } else { "Unmount" }, keys: "", action: Action::Unmount, enabled: (v.mount.is_some() || v.unlocked) && !formatting }, + MenuItem { label: "Eject", keys: "", action: Action::Eject, enabled: v.removable && !formatting }, ]; // Only for a drive meant to come out, never the system's (`Snapshot::format_refusal`), and // not in a chooser, which another program is waiting on. let mut items = items; if v.formattable && self.chooser.is_none() { - items.push(MenuItem { label: "Format…", keys: "", action: Action::FormatDrive, enabled: !self.drives_busy.contains(&v.drive) }); + items.push(MenuItem { label: "Format…", keys: "", action: Action::FormatDrive, enabled: !formatting }); } self.drive_menu = Some(v); self.menu = Some(Menu { items, x, y, at: usize::MAX }); @@ -4108,7 +4117,9 @@ impl App { } /// A format has finished. The drive shows under Devices by its new name as udisks2 says so. - fn format_done(&mut self, id: u64, target: FormatTarget, kind: FsKind, result: Result, DiskError>) { + /// What's said depends on what it left: nothing erased and all mounted again, nothing erased + /// but some of it left unmounted (or locked), or erased with no partition made. + fn format_done(&mut self, id: u64, target: FormatTarget, kind: FsKind, result: Result, FormatFailed>) { self.drives_busy.retain(|b| *b != target.drive); let view = self.jobs.iter().position(|j| j.job.id == id).map(|i| self.jobs.remove(i)); let stopped = view.as_ref().is_some_and(|v| v.job.is_cancelled()); @@ -4119,11 +4130,14 @@ impl App { let name = FormatAsk::new(target).drive_name(); match result { Ok(_) => self.note(format!("Formatted “{name}” as {}", kind.name())), + Err(FormatFailed { error, erased: true, .. }) => self.notice(format!("Couldn't format “{name}”: {error}. It was erased, and has no partition now")), // Stopped before anything was erased. - Err(DiskError::Cancelled) if stopped => self.note(format!("Stopped formatting “{name}”. Nothing was erased")), - // The user said no at polkit's prompt, and knows. - Err(DiskError::Cancelled) => {} - Err(e) => self.notice(format!("Couldn't format “{name}”: {e}")), + Err(FormatFailed { error: DiskError::Cancelled, left_unmounted: false, .. }) if stopped => self.note(format!("Stopped formatting “{name}”. Nothing was erased")), + // The user said no at polkit's prompt, knows, and it's as it was. + Err(FormatFailed { error: DiskError::Cancelled, left_unmounted: false, .. }) => {} + Err(FormatFailed { error: DiskError::Cancelled, .. }) => self.note(format!("Didn't format “{name}”. Nothing was erased, but it was left unmounted")), + Err(FormatFailed { error, left_unmounted: false, .. }) => self.notice(format!("Couldn't format “{name}”: {error}. Nothing was erased")), + Err(FormatFailed { error, .. }) => self.notice(format!("Couldn't format “{name}”: {error}. Nothing was erased, but it was left unmounted")), } self.clamp_scroll(); self.invalidate_all(); @@ -4199,7 +4213,11 @@ impl App { let kind_h = self.target(size::FORMAT_OPTION_ROW); let n = gannet_core::disks::FsKind::ALL.len() as i32; let gap = self.px(spacing::SPACE_8); - let rest = self.px(spacing::SPACE_12) + row + gap + field_h + row + gap + n * kind_h + self.px(spacing::SPACE_10) + self.dialog_button_h() + self.px(spacing::SPACE_12); + let name_w = (w - 2 * pad - label).max(1); + let text = &mut self.text; + let name_lines = crate::connect::wrap(&a.name_line(), name_w as f32, |s| text.measure(s)); + let rule_rows = gannet_core::disks::FsKind::ALL.iter().map(|k| crate::connect::wrap(k.label_rule(), name_w as f32, |s| text.measure(s)).len()).max().unwrap_or(1).max(name_lines.len()) as i32; + let rest = self.px(spacing::SPACE_12) + row + gap + field_h + row * rule_rows + gap + n * kind_h + self.px(spacing::SPACE_10) + self.dialog_button_h() + self.px(spacing::SPACE_12); // In a short window, the warning's lines that don't fit go, the last kept ending in "…". // A screen reader still has it all. let room = ((self.h - self.px(spacing::DIALOG_MARGIN * 2.0) - rest) / row.max(1)).max(0) as usize; @@ -4209,11 +4227,11 @@ impl App { let rect = Rect::new((self.w - w) / 2, (self.h - h) / 2, w, h); let y = rect.y + self.px(spacing::SPACE_12) + row * (1 + lines.len() as i32) + gap; let name = Rect::new(rect.x + pad + label, y, w - 2 * pad - label, field_h); - let name_line = Rect::new(name.x, name.bottom(), name.w, row); + let name_line = Rect::new(name.x, name.bottom(), name.w, row * rule_rows); let top = name_line.bottom() + gap; let kinds: Vec = (0..n).map(|i| Rect::new(name.x, top + i * kind_h, name.w, kind_h)).collect(); let kinds_label = Rect::new(rect.x + pad, top, label, kind_h); - FormatLayout { rect, lines, name, name_line, kinds_label, kinds } + FormatLayout { rect, lines, name, name_line, name_lines, kinds_label, kinds } } // ---- Network shares ---- @@ -12646,7 +12664,7 @@ mod tests { let v = stick(&r, Some("PHOTOS"), None, false); r.app.on_msg(Msg::Volumes(vec![v.clone()])); r.app.system_bus = Some("unix:path=/nonexistent".into()); - let target = FormatTarget { drive: v.drive.clone(), identity: v.identity.clone(), whole: "/b/whole".into(), model: "SanDisk Ultra".into(), size: 16_000_000_000, parts: vec![Part { label: Some("PHOTOS".into()), size: 8_000_000_000, stored: None, locked: false }], missing: vec![] }; + let target = FormatTarget { drive: v.drive.clone(), identity: v.identity.clone(), whole: "/b/whole".into(), model: "SanDisk Ultra".into(), size: 16_000_000_000, parts: vec![Part { label: Some("PHOTOS".into()), size: 8_000_000_000, stored: None, locked: false }], missing: vec![], mkfs_args: true }; r.app.on_msg(Msg::FormatLooked { volume: v.clone(), result: Ok(target.clone()) }); let focus = |r: &Rig| match &r.app.dialog { Some(Dialog::Format(a)) => Some(a.focus), @@ -12666,6 +12684,14 @@ mod tests { assert!(r.app.drives_busy.contains(&v.drive) && !r.app.drive_act(v.clone(), Doing::Mount)); let id = r.app.jobs[0].job.id; r.app.on_msg(Msg::FormatDone { job: id, target, kind: FsKind::Exfat, result: Ok(None) }); + // A no at the password prompt, with all of it mounted again, says nothing; left + // unmounted, it says so. + let target = FormatTarget { drive: v.drive.clone(), identity: v.identity.clone(), whole: "/b/whole".into(), model: "SanDisk Ultra".into(), size: 16_000_000_000, parts: vec![], missing: vec![], mkfs_args: true }; + let before = r.app.notices.len(); + r.app.on_msg(Msg::FormatDone { job: 999, target: target.clone(), kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: false }) }); + assert_eq!(r.app.notices.len(), before); + r.app.on_msg(Msg::FormatDone { job: 999, target, kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: true }) }); + assert_eq!(r.app.notices.last().map(String::as_str), Some("Didn't format “SanDisk Ultra, 16.0 GB”. Nothing was erased, but it was left unmounted")); assert!(r.app.jobs.is_empty() && r.app.drives_busy.is_empty()); assert!(r.app.notices.contains(&"Formatted “SanDisk Ultra, 16.0 GB” as exFAT".to_string()), "{:?}", r.app.notices); } diff --git a/crates/app/src/drives.rs b/crates/app/src/drives.rs index dab61b3..37a51e6 100644 --- a/crates/app/src/drives.rs +++ b/crates/app/src/drives.rs @@ -131,7 +131,10 @@ pub fn format(hub: Hub, address: String, target: FormatTarget, kind: FsKind, lab hub.send(Msg::Op(gannet_core::ops::Event::Progress(job.id))); !(job.is_cancelled() && s <= FormatStep::Erasing) }; - let result = Udisks::connect(&address).and_then(|udisks| udisks.format(&target, kind, &label, &mut step)); + let result = match Udisks::connect(&address) { + Ok(udisks) => udisks.format(&target, kind, &label, &mut step), + Err(error) => Err(disks::FormatFailed { error, erased: false, left_unmounted: false }), + }; hub.send(Msg::FormatDone { job: job.id, target, kind, result }); }); } diff --git a/crates/app/src/format_drive.rs b/crates/app/src/format_drive.rs index 1f361fc..0778a5c 100644 --- a/crates/app/src/format_drive.rs +++ b/crates/app/src/format_drive.rs @@ -54,7 +54,7 @@ impl FormatAsk { [Cow::Borrowed("Erase and Format"), Cow::Borrowed("Cancel")] } - /// The package `kind` needs, if it can't be made here. + /// Why `kind` can't be made here, if it can't, like "needs the exfatprogs package". pub fn missing(&self, kind: FsKind) -> Option<&str> { self.target.missing.iter().find(|(k, _)| *k == kind).map(|(_, p)| p.as_str()) } @@ -62,7 +62,7 @@ impl FormatAsk { /// What a format's choice says under its name: what it's for, or what it needs. pub fn note(&self, kind: FsKind) -> String { match self.missing(kind) { - Some(package) => format!("Unavailable: needs the {package} package"), + Some(why) => format!("Unavailable: {why}"), None => kind_note(kind).to_string(), } } @@ -158,7 +158,7 @@ mod tests { use gannet_core::disks::{Identity, Part}; fn target(parts: Vec, missing: Vec<(FsKind, String)>) -> FormatTarget { - FormatTarget { drive: "/d".into(), identity: Identity { id: "x".into(), size: 1, media_detected: 1 }, whole: "/b".into(), model: "SanDisk Ultra".into(), size: 116_000_000_000, parts, missing } + FormatTarget { drive: "/d".into(), identity: Identity { id: "x".into(), size: 1, media_detected: 1 }, whole: "/b".into(), model: "SanDisk Ultra".into(), size: 116_000_000_000, parts, missing, mkfs_args: true } } #[test] @@ -178,7 +178,7 @@ mod tests { fn it_starts_on_cancel_with_the_first_format_that_can_be_made() { let a = FormatAsk::new(target(vec![], vec![])); assert_eq!((a.focus, a.kind), (Stop::Button(CANCEL), FsKind::Exfat)); - let mut a = FormatAsk::new(target(vec![], vec![(FsKind::Exfat, "exfatprogs".into())])); + let mut a = FormatAsk::new(target(vec![], vec![(FsKind::Exfat, "needs the exfatprogs package".into())])); assert_eq!(a.kind, FsKind::Fat32); assert_eq!(a.note(FsKind::Exfat), "Unavailable: needs the exfatprogs package"); assert!(!a.pick(FsKind::Exfat), "can't be picked"); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 8f100b3..da69c91 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -890,7 +890,7 @@ mod bench { Edit::NewFolder(f) => format!("newfolder:{}", f.text), }; format!( - "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"format\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", + "{{\"dir\":{},\"loading\":{},\"count\":{},\"names\":{},\"cursor\":{},\"cursor_shown\":{},\"selected\":{},\"filter\":{},\"edit\":{},\"name_error\":{},\"hidden\":{},\"sort\":{},\"desc\":{},\"scroll\":{},\"notices\":{},\"menu\":{},\"menu_items\":{},\"menu_off\":{},\"error\":{},\"base\":{},\"can_back\":{},\"can_forward\":{},\"jobs\":{},\"visible_jobs\":{},\"dialog\":{},\"undo\":{},\"redo\":{},\"panel\":{},\"preview\":{},\"previewing\":{},\"drag\":{},\"places\":{},\"headings\":{},\"side_scroll\":{},\"side_max\":{},\"chooser\":{},\"searching\":{},\"found\":{},\"locations\":{},\"status\":{},\"thumbs\":{},\"side_focus\":{},\"server\":{},\"format\":{},\"suggest\":{},\"message\":{},\"targets\":{}}}\n", esc(&a.dir.to_string_lossy()), a.loading, a.rows.len(), @@ -908,6 +908,7 @@ mod bench { list(a.notices.iter().cloned()), a.menu.is_some(), list(a.menu.iter().flat_map(|m| m.items.iter().map(|i| i.label.to_string()))), + list(a.menu.iter().flat_map(|m| m.items.iter().filter(|i| !i.enabled).map(|i| i.label.to_string()))), a.load_error.as_ref().map_or_else(|| "null".to_string(), |e| esc(e)), a.colors.base, a.history.can_go_back(), @@ -1048,7 +1049,7 @@ mod bench { s.push_str("|off"); } if let Some(v) = &p.volume { - for (on, word) in [(v.mount.is_some(), "mounted"), (v.locked, "locked"), (v.removable, "eject"), (a.drives_busy.contains(&v.block), "busy")] { + for (on, word) in [(v.mount.is_some(), "mounted"), (v.locked, "locked"), (v.removable, "eject"), (a.drive_busy(v), "busy")] { if on { s.push('|'); s.push_str(word); diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 72a5946..9be5d4b 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -473,7 +473,7 @@ impl App { let tx = (r.x + self.px(size::PLACE_NAME_INSET)) as f32; // A drive that's busy, or not mounted yet, is quieter than the rest, as is a share // being disconnected. - let waiting = p.volume.as_ref().is_some_and(|v| v.mount.is_none() || self.drives_busy.contains(&v.block)) || (p.kind == PlaceKind::Network && self.shares_busy.contains(&p.path)); + let waiting = p.volume.as_ref().is_some_and(|v| v.mount.is_none() || self.drive_busy(v)) || (p.kind == PlaceKind::Network && self.shares_busy.contains(&p.path)); let color = if here { co.on_selection } else if off { co.border } else if waiting { co.muted } else { co.foreground }; let eject = ejects[i]; let right = eject.map_or(r.right() - self.px(spacing::SPACE_6), |e| e.x); @@ -897,7 +897,9 @@ impl App { self.text.draw_fitted(c, "Name", x, self.baseline(l.name.y, l.name.h), label_max, co.muted); self.paint_field(c, l.name, &a.name, a.focus == FormatStop::Name); let line_color = if a.name.error.is_some() { co.danger } else { co.muted }; - self.text.draw_fitted(c, &a.name_line(), l.name_line.x as f32, self.baseline(l.name_line.y, l.name_line.h), l.name_line.w as f32, line_color); + for (i, line) in l.name_lines.iter().enumerate() { + self.text.draw_fitted(c, line, l.name_line.x as f32, self.baseline(l.name_line.y + row * i as i32, row), l.name_line.w as f32, line_color); + } let half = |r: Rect| r.h / 2; self.text.draw_fitted(c, "Format", x, self.baseline(l.kinds_label.y, half(l.kinds_label)), label_max, co.muted); let ring = self.px(size::RADIO); diff --git a/crates/core/examples/udisks-standin.rs b/crates/core/examples/udisks-standin.rs index 5d239ad..492c688 100644 --- a/crates/core/examples/udisks-standin.rs +++ b/crates/core/examples/udisks-standin.rs @@ -16,6 +16,14 @@ //! system NAME udisks2 marks the block as the system's (HintSystem) //! lacks TYPE UTILITY Manager.CanFormat says TYPE needs UTILITY, which isn't installed //! refuse the next Format is refused, as when polkit's prompt is dismissed +//! slow NAME MS unmounting NAME takes MS milliseconds, during which other commands +//! are taken +//! swap DRIVE another card or stick of the same make in its place: the time its +//! media went in changes +//! uuid NAME UUID the filesystem's UUID (each block's device is /dev/NAME) +//! loop NAME FILE a loop device made from FILE +//! container NAME DRIVE an MBR extended partition on it, holding the logical ones +//! version V what Manager.Version says (2.12.0 to start with) //! asked each Format and CreatePartitionAndFormat asked for, a line each //! starting `asked `, before the `ok` //! @@ -41,6 +49,7 @@ const ROOT: &str = "/org/freedesktop/UDisks2"; #[derive(Clone, Default)] struct DriveState { id: String, + media_detected: u64, vendor: String, model: String, removable: bool, @@ -58,6 +67,11 @@ struct BlockState { /// For a partition: its disk's block. partition_of: Option, system: bool, + container: bool, + uuid: String, + loop_file: Option, + /// Unmounting takes this long. + slow: Option, /// `Some` for a filesystem: where it's mounted, if it is. mounted: Option>, /// `Some` for an encrypted volume: its passphrase, the label inside, and its contents' path. @@ -73,6 +87,7 @@ struct State { /// Filesystem types CanFormat says can't be made, and the program each needs. lacks: HashMap, refuse: bool, + version: String, /// The formatting calls made, as `asked` lists them. asked: Vec, } @@ -157,7 +172,7 @@ impl DriveIface { } #[zbus(property)] fn time_media_detected(&self) -> u64 { - 1_700_000_000_000_000 + 1_700_000_000_000_000 + self.state.lock().unwrap().drives.get(&self.at).map_or(0, |d| d.media_detected) } fn power_off(&self, _options: HashMap, #[zbus(connection)] conn: &Connection) -> Result<(), UdError> { @@ -216,6 +231,14 @@ impl BlockIface { fn crypto_backing_device(&self) -> OwnedObjectPath { object(&self.get(|b| b.backing.clone())) } + #[zbus(property, name = "IdUUID")] + fn id_uuid(&self) -> String { + self.get(|b| b.uuid.clone()) + } + #[zbus(property)] + fn device(&self) -> Vec { + [format!("/dev/{}", self.at.rsplit('/').next().unwrap_or("")).as_bytes(), b"\0"].concat() + } /// A new, empty partition table on a whole disk, in this stand-in's state alone. async fn format(&self, kind: String, options: HashMap, #[zbus(connection)] conn: &Connection) -> Result<(), UdError> { @@ -289,6 +312,10 @@ impl FilesystemIface { return Err(UdError::DeviceBusy("Error unmounting: target is busy".into())); } b.mounted = Some(None); + if let Some(d) = b.slow { + drop(state); + std::thread::sleep(d); + } } changed(conn, &self.at, "Filesystem").await; Ok(()) @@ -354,6 +381,7 @@ fn written(options: &HashMap) -> String { let mut v: Vec = options.iter().map(|(k, val)| format!("{k}={}", match &**val { Variant::Str(s) => s.to_string(), Variant::Bool(b) => b.to_string(), + Variant::Array(a) => a.iter().map(|x| if let Variant::Str(s) = x { s.to_string() } else { format!("{x:?}") }).collect::>().join(","), other => format!("{other:?}"), })).collect(); v.sort(); @@ -372,6 +400,24 @@ impl PartitionIface { let s = self.state.lock().unwrap(); object(s.blocks.get(&self.at).and_then(|b| b.partition_of.clone()).as_deref().unwrap_or("/")) } + #[zbus(property)] + fn is_container(&self) -> bool { + self.state.lock().unwrap().blocks.get(&self.at).is_some_and(|b| b.container) + } +} + +struct LoopIface { + at: String, + state: Shared, +} + +#[zbus::interface(name = "org.freedesktop.UDisks2.Loop")] +impl LoopIface { + #[zbus(property)] + fn backing_file(&self) -> Vec { + let s = self.state.lock().unwrap(); + [s.blocks.get(&self.at).and_then(|b| b.loop_file.clone()).unwrap_or_default().as_bytes(), b"\0"].concat() + } } struct TableIface { @@ -418,6 +464,11 @@ struct ManagerIface { #[zbus::interface(name = "org.freedesktop.UDisks2.Manager")] impl ManagerIface { + #[zbus(property)] + fn version(&self) -> String { + self.state.lock().unwrap().version.clone() + } + fn can_format(&self, kind: String) -> (bool, String) { match self.state.lock().unwrap().lacks.get(&kind) { Some(utility) => (false, utility.clone()), @@ -428,10 +479,10 @@ impl ManagerIface { /// Serves a block's interfaces, as its state says it has. fn serve_block(conn: &Connection, state: &Shared, at: &str) { - let (fs, luks, table, partition) = { + let (fs, luks, table, partition, looped) = { let s = state.lock().unwrap(); let b = &s.blocks[at]; - (b.mounted.is_some(), b.luks.is_some(), b.table, b.partition_of.is_some()) + (b.mounted.is_some(), b.luks.is_some(), b.table, b.partition_of.is_some(), b.loop_file.is_some()) }; let server = conn.object_server(); block_on(server.at(at, BlockIface { at: at.into(), state: state.clone() })).unwrap(); @@ -447,6 +498,9 @@ fn serve_block(conn: &Connection, state: &Shared, at: &str) { if table { block_on(server.at(at, TableIface { at: at.into(), state: state.clone() })).unwrap(); } + if looped { + block_on(server.at(at, LoopIface { at: at.into(), state: state.clone() })).unwrap(); + } } fn remove(conn: &Connection, at: &str) { @@ -515,6 +569,20 @@ fn command(conn: &Connection, state: &Shared, line: &str) -> Result<(), String> state.lock().unwrap().lacks.insert(kind.to_string(), utility.to_string()); } ["refuse"] => state.lock().unwrap().refuse = true, + ["slow", name, ms] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.slow = Some(std::time::Duration::from_millis(ms.parse().map_err(|_| "not a number")?)), + ["swap", drive] => state.lock().unwrap().drives.get_mut(&path("drives", drive)).ok_or("no such drive")?.media_detected += 1, + ["uuid", name, uuid] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.uuid = uuid.to_string(), + ["version", v] => state.lock().unwrap().version = v.to_string(), + ["loop", name, file] => { + let at = path("block_devices", name); + state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: "/".into(), usage: "filesystem".into(), backing: "/".into(), loop_file: Some(file.to_string()), ..BlockState::default() }); + serve_block(conn, state, &at); + } + ["container", name, drive] => { + let at = path("block_devices", name); + state.lock().unwrap().blocks.insert(at.clone(), BlockState { drive: path("drives", drive), backing: "/".into(), partition_of: Some(path("block_devices", drive)), container: true, ..BlockState::default() }); + serve_block(conn, state, &at); + } ["asked"] => { for a in &state.lock().unwrap().asked { println!("asked {a}"); @@ -551,7 +619,7 @@ fn main() { let bus = Bus::connect(address).expect("the bus"); let conn = bus.connection().clone(); block_on(conn.object_server().at(ROOT, zbus::fdo::ObjectManager)).expect("the object manager"); - let state: Shared = Arc::new(Mutex::new(State { root: PathBuf::from(root), ..State::default() })); + let state: Shared = Arc::new(Mutex::new(State { root: PathBuf::from(root), version: "2.12.0".into(), ..State::default() })); block_on(conn.object_server().at(format!("{ROOT}/Manager"), ManagerIface { state: state.clone() })).expect("the manager"); assert!(bus.own_name("org.freedesktop.UDisks2").expect("the name"), "someone else is udisks2 on this bus"); println!("ok"); diff --git a/crates/core/src/disks.rs b/crates/core/src/disks.rs index 71751fe..6b1d548 100644 --- a/crates/core/src/disks.rs +++ b/crates/core/src/disks.rs @@ -78,6 +78,16 @@ pub struct Block { pub partition_of: String, /// It's swap, in use. pub swap: bool, + /// An MBR extended partition, which only holds logical partitions. + pub container: bool, + /// Its filesystem's UUID, its partition's UUID and name, and its device, like `/dev/sda1`, + /// for matching the boot device the kernel was given. + pub uuid: String, + pub part_uuid: String, + pub part_name: String, + pub device: Option, + /// For a loop device, the file it's made from. + pub loop_file: Option, } /// Everything udisks2 knows about drives and the blocks on them, at one moment. @@ -85,6 +95,9 @@ pub struct Block { pub struct Snapshot { pub drives: BTreeMap, pub blocks: BTreeMap, + /// The devices the kernel's command line says the system booted from, as written there: + /// `UUID=…`, `LABEL=…`, `PARTUUID=…`, `PARTLABEL=…` or a path. See [`boot_devices`]. + pub boot: Vec, } /// What makes a drive the one that was picked, more than its path does. @@ -144,6 +157,12 @@ fn bytes(v: &Variant) -> Option> { Some(out) } +/// One path, as udisks2 gives it: a byte string, empty for none. +fn path_of(p: &Properties, key: &str) -> Option { + use std::os::unix::ffi::OsStringExt; + p.get(key).and_then(|v| bytes(v)).filter(|b| !b.is_empty()).map(|b| PathBuf::from(std::ffi::OsString::from_vec(b))) +} + fn paths_of(p: &Properties, key: &str) -> Vec { use std::os::unix::ffi::OsStringExt; let Some(Variant::Array(a)) = p.get(key).map(|v| &**v) else { return Vec::new() }; @@ -194,6 +213,12 @@ impl Snapshot { table: iface("PartitionTable").is_some(), partition_of: iface("Partition").map(|p| string_of(p, "Table")).filter(|t| t != NONE).unwrap_or_default(), swap: iface("Swapspace").is_some_and(|w| bool_of(w, "Active")), + container: iface("Partition").is_some_and(|p| bool_of(p, "IsContainer")), + uuid: string_of(b, "IdUUID"), + part_uuid: iface("Partition").map(|p| string_of(p, "UUID")).unwrap_or_default(), + part_name: iface("Partition").map(|p| string_of(p, "Name")).unwrap_or_default(), + device: path_of(b, "Device"), + loop_file: iface("Loop").and_then(|l| path_of(l, "BackingFile")), }, ); } @@ -264,8 +289,8 @@ impl Snapshot { /// Why the drive at `drive` can't be formatted, if it can't. Only a drive meant to come /// out can be: removable, or on USB or a card slot. Never one udisks2 says is the system's, - /// one with the system mounted from it or swap in use on it, or one that's part of a RAID or - /// LVM set. + /// one with the system mounted from it or swap in use on it, one that's part of a RAID or + /// LVM set, or the stick a live or installer system is running from (`started_from`). pub fn format_refusal(&self, drive: &str) -> Option<&'static str> { let Some(d) = self.drives.get(drive) else { return Some("it's been taken out") }; if !(d.removable || ["usb", "sdio", "ieee1394"].contains(&d.connection.as_str())) { @@ -276,6 +301,9 @@ impl Snapshot { if blocks.iter().any(|b| b.hint_system || b.swap || system_mount(b)) { return Some("the system uses it"); } + if self.started_from(&blocks) { + return Some("the running system started from it"); + } if blocks.iter().any(|b| b.id_usage == "raid" || b.id_type == "LVM2_member") { return Some("it's part of a RAID or LVM set"); } @@ -285,12 +313,32 @@ impl Snapshot { None } + /// Whether a live or installer system is running from any of `blocks`: one is mounted + /// where live systems mount their medium, one holds the file a loop device is made from (a + /// live system's squashfs), or one is the device the kernel's command line booted from. + fn started_from(&self, blocks: &[&Block]) -> bool { + const LIVE: [&str; 5] = ["/run/archiso", "/run/initramfs", "/run/live", "/cdrom", "/lib/live/mount"]; + let mounts: Vec<&PathBuf> = blocks.iter().filter_map(|b| b.mount_points.as_ref()).flatten().collect(); + let live = mounts.iter().any(|m| LIVE.iter().any(|l| m.starts_with(l))); + let looped = self.blocks.values().filter_map(|b| b.loop_file.as_ref()).any(|f| mounts.iter().any(|m| f.starts_with(m))); + let booted = blocks.iter().any(|b| { + self.boot.iter().any(|r| match r.split_once('=') { + Some(("UUID", u)) => !u.is_empty() && b.uuid.eq_ignore_ascii_case(u), + Some(("LABEL", l)) => !l.is_empty() && b.label == l, + Some(("PARTUUID", u)) => !u.is_empty() && b.part_uuid.eq_ignore_ascii_case(u), + Some(("PARTLABEL", l)) => !l.is_empty() && b.part_name == l, + _ => b.device.as_ref().is_some_and(|d| std::path::Path::new(r) == d), + }) + }); + live || looped || booted + } + /// What's on a drive, for the warning before it's formatted: each partition, or the whole /// disk's own filesystem when it has no partitions. An unlocked partition is told by what's - /// inside it. + /// inside it. An MBR extended partition is left out, as its logical partitions are each told. fn parts(&self, drive: &str) -> Vec<(&Block, Option<&Block>)> { let Some(whole) = self.whole_disk(drive) else { return Vec::new() }; - let mut parts: Vec<&Block> = self.blocks.values().filter(|b| b.partition_of == whole.path).collect(); + let mut parts: Vec<&Block> = self.blocks.values().filter(|b| b.partition_of == whole.path && !b.container).collect(); if parts.is_empty() && !whole.id_usage.is_empty() { parts.push(whole); } @@ -298,8 +346,36 @@ impl Snapshot { } } +/// The devices the kernel was told to boot from, from its command line: `root=`, and the +/// `archisodevice=` and `archisolabel=` of an Arch live or installer system, each as `UUID=…`, +/// `LABEL=…`, `PARTUUID=…`, `PARTLABEL=…` or a path. A `/dev/disk/by-*/` path becomes the same. +pub fn boot_devices(cmdline: &str) -> Vec { + let mut out = Vec::new(); + for word in cmdline.split_whitespace() { + let Some((key, value)) = word.split_once('=') else { continue }; + let value = value.trim_matches('"'); + let r = match key { + "root" | "archisodevice" => match value.strip_prefix("/dev/disk/by-") { + Some(by) => match by.split_once('/') { + Some(("uuid", v)) => format!("UUID={v}"), + Some(("label", v)) => format!("LABEL={v}"), + Some(("partuuid", v)) => format!("PARTUUID={v}"), + Some(("partlabel", v)) => format!("PARTLABEL={v}"), + _ => value.to_string(), + }, + None => value.to_string(), + }, + "archisolabel" => format!("LABEL={value}"), + _ => continue, + }; + out.push(r); + } + out +} + /// Where the running system's own filesystems are mounted. A drive with one of them mounted from -/// it is never formatted. +/// it is never formatted. Anything under `/var/` counts, which also refuses a stick mounted at +/// `/var/mnt/…` (as Fedora Atomic can): rare for a stick, and the safe side to be on. fn is_system_path(p: &std::path::Path) -> bool { const AT: [&str; 11] = ["/", "/boot", "/efi", "/home", "/usr", "/var", "/opt", "/srv", "/nix", "/root", "/etc"]; AT.iter().any(|a| p == std::path::Path::new(a)) || ["/boot/", "/efi/", "/usr/", "/var/"].iter().any(|a| p.to_str().is_some_and(|p| p.starts_with(a))) @@ -347,19 +423,24 @@ impl FsKind { /// What its names can be, in a few words, for under the name field. pub fn label_rule(self) -> &'static str { match self { - FsKind::Exfat => "Up to 15 characters.", - FsKind::Fat32 => "Up to 11 letters and numbers, in capitals.", - FsKind::Ext4 => "Up to 16 bytes: accented letters take 2 or more.", + FsKind::Exfat => "Up to 15 characters, with no space at either end.", + FsKind::Fat32 => "Up to 11 of A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~, with no space at either end. Kept in capitals.", + FsKind::Ext4 => "Up to 16 bytes, with no space at either end. Accented letters take 2 or more.", } } - /// The name as it'll be written, or why it can't be. FAT32 keeps names in capitals, and its - /// names are plain ASCII without the characters FAT reserves. None can have a slash, as the - /// name becomes the folder it's mounted at. An empty name is allowed: the drive then has none. + /// The name as it'll be written, or why it can't be. FAT32 keeps names in capitals, and takes + /// only the characters its rule lists (`FAT_SYMBOLS`). None can have a slash, as the name + /// becomes the folder it's mounted at, or start or end with a space, which shows as nothing + /// and some systems drop; so a name of spaces alone can't be used either. An empty name is + /// allowed: the drive then has none. pub fn label(self, typed: &str) -> Result { if let Some(c) = typed.chars().find(|c| c.is_control() || *c == '/') { return Err(if c == '/' { "Names can't have “/” in them.".to_string() } else { "Names can't have control characters.".to_string() }); } + if typed.starts_with(' ') || typed.ends_with(' ') { + return Err("Names can't start or end with a space.".to_string()); + } match self { FsKind::Exfat => { let n = typed.encode_utf16().count(); @@ -369,8 +450,8 @@ impl FsKind { Ok(typed.to_string()) } FsKind::Fat32 => { - if let Some(c) = typed.chars().find(|c| !c.is_ascii() || "\"*+,./:;<=>?[\\]|".contains(*c)) { - return Err(format!("FAT32 names can't have “{c}”. Use A–Z, 0–9 and spaces.")); + if let Some(c) = typed.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == ' ' || FAT_SYMBOLS.contains(*c))) { + return Err(format!("FAT32 names can't have “{c}”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` {{ }} ~")); } let n = typed.len(); if n > 11 { @@ -389,6 +470,10 @@ impl FsKind { } } +/// The symbols a FAT32 name can have, besides A–Z, 0–9 and spaces: those FAT allows in a +/// volume label that every system reads alike. +const FAT_SYMBOLS: &str = "!#$%&'()-@^_`{}~"; + /// The package that has a program udisks2 needs to make a filesystem, as Arch names it, or the /// program itself when it's one this doesn't know. pub fn package_for(utility: &str) -> String { @@ -423,10 +508,33 @@ pub struct FormatTarget { pub model: String, pub size: u64, pub parts: Vec, - /// The formats that can't be made here, each with the package it needs. + /// The formats that can't be made here, each with why, like "needs the exfatprogs package". pub missing: Vec<(FsKind, String)>, + /// udisks2 passes `mkfs-args` on to mkfs (2.10 and newer), so FAT32 can be asked for as + /// such. Without it, mkfs.fat picks the FAT size itself: FAT32 from 512 MiB. + pub mkfs_args: bool, +} + +/// Why a format didn't finish, and what that left: whether the drive was erased, and whether +/// what was mounted on it before is mounted again. +#[derive(Clone, Debug, PartialEq)] +pub struct FormatFailed { + pub error: DiskError, + pub erased: bool, + /// Something that was mounted or unlocked before is no longer. An encrypted volume can't be + /// unlocked again without its passphrase, so one that was unlocked always counts. + pub left_unmounted: bool, } +impl FormatFailed { + fn before_erasing(error: DiskError) -> Self { + Self { error, erased: false, left_unmounted: false } + } +} + +/// Below this, mkfs.fat picks FAT16 or FAT12 unless told FAT32. +const FAT32_LEAST: u64 = 512 << 20; + /// How far a format has got, in order. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum FormatStep { @@ -500,6 +608,8 @@ fn options() -> HashMap<&'static str, Variant<'static>> { /// udisks2 on one bus connection, for calls that may wait on a person at polkit's prompt. pub struct Udisks { bus: Bus, + /// The kernel's command line, for the device the system booted from. Test seam: another file. + cmdline: PathBuf, } /// Busy filesystems are tried this many times, this far apart: a second in all. @@ -511,7 +621,13 @@ pub const ACTION_LIMIT: Duration = Duration::from_secs(600); impl Udisks { pub fn new(bus: Bus) -> Self { - Self { bus } + Self { bus, cmdline: PathBuf::from("/proc/cmdline") } + } + + /// Test seam: reads the kernel's command line from `file` instead. + pub fn with_cmdline(mut self, file: PathBuf) -> Self { + self.cmdline = file; + self } pub fn connect(address: &str) -> Result { @@ -524,7 +640,9 @@ impl Udisks { pub fn snapshot(&self) -> Result { let objects: Objects = self.bus.call(SERVICE, ROOT, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", &()).map_err(|e| disk_error(e, false))?; - Ok(Snapshot::from_objects(&objects)) + let mut s = Snapshot::from_objects(&objects); + s.boot = boot_devices(&std::fs::read_to_string(&self.cmdline).unwrap_or_default()); + Ok(s) } /// The snapshot, once it's been checked that `volume`'s drive is still the one it was. @@ -672,6 +790,15 @@ impl Udisks { } } + /// Whether udisks2 is 2.10 or newer, which passes `mkfs-args` on to mkfs. Read from its + /// Manager's Version; nothing is formatted to find out. + fn takes_mkfs_args(&self) -> bool { + let Ok(v) = self.bus.call::<_, OwnedVariant>(SERVICE, MANAGER, "org.freedesktop.DBus.Properties", "Get", &(format!("{PREFIX}Manager"), "Version")) else { return false }; + let Variant::Str(v) = &*v else { return false }; + let mut n = v.as_str().split('.').map(|p| p.parse::().unwrap_or(0)); + (n.next().unwrap_or(0), n.next().unwrap_or(0)) >= (2, 10) + } + /// The volume's drive, and what's on it, once it's been checked that it can be formatted. pub fn look_to_format(&self, volume: &Volume) -> Result { let now = self.checked(volume)?; @@ -691,32 +818,67 @@ impl Udisks { }) .collect(); let model = [drive.vendor.as_str(), drive.model.as_str()].into_iter().filter(|s| !s.is_empty()).collect::>().join(" "); - let missing = FsKind::ALL.into_iter().filter_map(|k| self.missing(k).map(|u| (k, package_for(&u)))).collect(); - Ok(FormatTarget { drive: drive.path.clone(), identity: volume.identity.clone(), whole: whole.path.clone(), model, size: drive.size, parts, missing }) + let mut missing: Vec<(FsKind, String)> = FsKind::ALL.into_iter().filter_map(|k| self.missing(k).map(|u| (k, format!("needs the {} package", package_for(&u))))).collect(); + let mkfs_args = self.takes_mkfs_args(); + // Without asking for FAT32, a drive this small would get FAT16. + if !mkfs_args && drive.size < FAT32_LEAST && !missing.iter().any(|(k, _)| *k == FsKind::Fat32) { + missing.push((FsKind::Fat32, "needs udisks2 2.10 or newer on a drive under 512 MiB".into())); + } + Ok(FormatTarget { drive: drive.path.clone(), identity: volume.identity.clone(), whole: whole.path.clone(), model, size: drive.size, parts, missing, mkfs_args }) } /// Erases the whole drive and makes one partition of `kind` filling it, named `label` (as /// `FsKind::label` gives it), then mounts it and says where. It unmounts and locks what's /// on the drive first, writes a new GPT partition table, then makes the partition from 1 MiB /// in. `step` hears each step as it starts, and saying no before the erasing stops it there; - /// after that it can't be stopped. A drive that's changed, or can't be formatted now, is left - /// alone. polkit asks once, at the erasing. - pub fn format(&self, target: &FormatTarget, kind: FsKind, label: &str, step: &mut dyn FnMut(FormatStep) -> bool) -> Result, DiskError> { - let now = self.snapshot()?; - if !now.same_drive(&target.drive, &target.identity) || now.whole_disk(&target.drive).map(|b| b.path.as_str()) != Some(target.whole.as_str()) { - return Err(DiskError::Changed); - } - if let Some(why) = now.format_refusal(&target.drive) { - return Err(DiskError::Other(why.to_string())); - } + /// after that it can't be stopped. polkit asks once, at the erasing, and that wait is inside + /// udisks2's `Block.Format`: nothing on this side can close its prompt. + /// + /// A drive that's changed, or can't be formatted now, is left alone. That's checked before + /// anything is unmounted, and again after, as unmounting can take seconds. "The same drive" + /// is its udisks2 Id, size and when its media went in: two sticks of one make with no serial + /// number can have the same Id, and one swapped for the other while the drive was + /// unmounting, with the same size, would pass. + /// + /// When it stops or fails before the erasing, what was mounted is mounted again, and the + /// failure says whether it all was. + pub fn format(&self, target: &FormatTarget, kind: FsKind, label: &str, step: &mut dyn FnMut(FormatStep) -> bool) -> Result, FormatFailed> { + let check = |now: &Snapshot| -> Result<(), DiskError> { + if !now.same_drive(&target.drive, &target.identity) || now.whole_disk(&target.drive).map(|b| b.path.as_str()) != Some(target.whole.as_str()) { + return Err(DiskError::Changed); + } + match now.format_refusal(&target.drive) { + Some(why) => Err(DiskError::Other(why.to_string())), + None => Ok(()), + } + }; + let now = self.snapshot().map_err(FormatFailed::before_erasing)?; + check(&now).map_err(FormatFailed::before_erasing)?; if !step(FormatStep::Unmounting) { - return Err(DiskError::Cancelled); + return Err(FormatFailed::before_erasing(DiskError::Cancelled)); } - self.release(&now, &target.drive)?; + // What's mounted now, to mount again if it goes no further. Unlocked contents can't be. + let blocks = now.on_drive(&target.drive); + let mounted: Vec = blocks.iter().filter(|b| b.crypto_backing.is_empty() || b.crypto_backing == NONE).filter(|b| b.mount_points.as_ref().is_some_and(|m| !m.is_empty())).map(|b| b.path.clone()).collect(); + let unlocked = blocks.iter().any(|b| matches!(b.encrypted, Some(Some(_)))); + let undo = |error: DiskError| { + let mut all = !unlocked; + for b in &mounted { + all &= self.mount_block(b).is_ok(); + } + FormatFailed { error, erased: false, left_unmounted: !all } + }; + self.release(&now, &target.drive).map_err(undo)?; + // Unmounting can take a while, and the drive can change meanwhile. + let again = self.snapshot().map_err(undo)?; + check(&again).map_err(|e| undo(match e { + DiskError::Other(why) => DiskError::Other(format!("{why}, which changed while it was being unmounted")), + e => e, + }))?; if !step(FormatStep::Erasing) { - return Err(DiskError::Cancelled); + return Err(undo(DiskError::Cancelled)); } - self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false)?; + self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false).map_err(undo)?; step(FormatStep::Making); let mut made = options(); made.insert("label", Variant::from(label.to_string())); @@ -724,7 +886,14 @@ impl Udisks { if kind == FsKind::Ext4 { made.insert("take-ownership", Variant::from(true)); } - let created: OwnedObjectPath = self.call(&target.whole, "PartitionTable", "CreatePartitionAndFormat", &(1u64 << 20, 0u64, kind.partition_type(), "", options(), kind.udisks(), made), false)?; + // FAT32 as such, where udisks2 passes it on; otherwise mkfs.fat's own pick, which is + // FAT32 from 512 MiB (smaller drives aren't offered FAT32 then). + if kind == FsKind::Fat32 && target.mkfs_args { + made.insert("mkfs-args", Variant::from(vec!["-F", "32"])); + } + let created: OwnedObjectPath = self + .call(&target.whole, "PartitionTable", "CreatePartitionAndFormat", &(1u64 << 20, 0u64, kind.partition_type(), "", options(), kind.udisks(), made), false) + .map_err(|error| FormatFailed { error, erased: true, left_unmounted: true })?; step(FormatStep::Opening); // It's formatted. Its filesystem can take a moment to show, and not opening it isn't // worth more than saying it's done. @@ -884,6 +1053,34 @@ mod tests { assert_eq!(Snapshot::from_objects(&o).format_refusal(&stick), Some("it's part of a RAID or LVM set")); } + #[test] + fn an_extended_partition_is_not_told_twice() { + let mut o = machine(false); + object(&mut o, "block_devices/sdb4", vec![("Block", block("sdb4", "Stick", "", "", false)), ("Partition", { let mut p = partition_of("sdb"); p.insert("IsContainer".into(), v(Variant::Bool(true))); p })]); + object(&mut o, "block_devices/sdb5", vec![("Block", block("sdb5", "Stick", "LOGICAL", "filesystem", false)), ("Filesystem", mounts(&[])), ("Partition", partition_of("sdb"))]); + let s = Snapshot::from_objects(&o); + let labels: Vec<&str> = s.parts(&format!("{ROOT}/drives/Stick")).iter().map(|(p, _)| p.label.as_str()).collect(); + assert_eq!(labels, ["PHOTOS", "", "SPARE", "LOGICAL"], "the logical partition, not its container"); + } + + #[test] + fn the_boot_device_is_read_from_the_command_line() { + assert_eq!(boot_devices("BOOT_IMAGE=/vmlinuz root=UUID=abcd rw quiet"), ["UUID=abcd"]); + assert_eq!(boot_devices("archisobasedir=arch archisodevice=UUID=2026-01-01 archisolabel=ARCH_202601"), ["UUID=2026-01-01", "LABEL=ARCH_202601"]); + assert_eq!(boot_devices("root=/dev/disk/by-partuuid/1234-02 root=/dev/sda2 root=PARTLABEL=linux"), ["PARTUUID=1234-02", "/dev/sda2", "PARTLABEL=linux"]); + assert!(boot_devices("rootflags=subvol=@ rootfstype=btrfs").is_empty()); + // Matched against the blocks on a drive. + let mut s = Snapshot::from_objects(&machine(false)); + let stick = format!("{ROOT}/drives/Stick"); + s.blocks.get_mut(&format!("{ROOT}/block_devices/sdb1")).unwrap().uuid = "ABCD-1234".into(); + s.boot = boot_devices("root=UUID=abcd-1234"); + assert_eq!(s.format_refusal(&stick), Some("the running system started from it"), "a UUID in either case"); + s.boot = boot_devices("archisolabel=SPARE"); + assert_eq!(s.format_refusal(&stick), Some("the running system started from it")); + s.boot = boot_devices("root=UUID="); + assert_eq!(s.format_refusal(&stick), None, "an empty one matches nothing"); + } + #[test] fn names_fit_the_format() { assert_eq!(FsKind::Exfat.label("Holiday photos"), Ok("Holiday photos".into())); @@ -891,8 +1088,16 @@ mod tests { assert_eq!(FsKind::Exfat.label("Fotos de féria"), Ok("Fotos de féria".into()), "characters, not bytes"); assert_eq!(FsKind::Fat32.label("photos 2026"), Ok("PHOTOS 2026".into()), "in capitals"); assert_eq!(FsKind::Fat32.label("photos 20266"), Err("FAT32 allows 11 characters. This has 12.".into())); - assert_eq!(FsKind::Fat32.label("fotos.old"), Err("FAT32 names can't have “.”. Use A–Z, 0–9 and spaces.".into())); - assert_eq!(FsKind::Fat32.label("férias"), Err("FAT32 names can't have “é”. Use A–Z, 0–9 and spaces.".into())); + assert_eq!(FsKind::Fat32.label("fotos.old"), Err("FAT32 names can't have “.”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); + assert_eq!(FsKind::Fat32.label("férias"), Err("FAT32 names can't have “é”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); + assert_eq!(FsKind::Fat32.label("a+b"), Err("FAT32 names can't have “+”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); + assert_eq!(FsKind::Fat32.label("my-cam_(2)"), Ok("MY-CAM_(2)".into()), "every symbol the rule lists"); + for kind in FsKind::ALL { + assert_eq!(kind.label(" "), Err("Names can't start or end with a space.".into()), "{kind:?}: spaces alone"); + assert_eq!(kind.label(" a"), Err("Names can't start or end with a space.".into())); + assert_eq!(kind.label("a "), Err("Names can't start or end with a space.".into())); + assert!(kind.label("a b").is_ok()); + } assert_eq!(FsKind::Ext4.label("sixteen-letters!"), Ok("sixteen-letters!".into())); assert_eq!(FsKind::Ext4.label("dezasseis-férias"), Err("ext4 allows 16 bytes. This has 17.".into())); assert_eq!(FsKind::Ext4.label("a/b"), Err("Names can't have “/” in them.".into())); @@ -1048,17 +1253,22 @@ mod tests { assert_eq!(target.whole, format!("{ROOT}/block_devices/Stick")); let parts: Vec<(Option<&str>, bool, bool)> = target.parts.iter().map(|p| (p.label.as_deref(), p.stored.is_some(), p.locked)).collect(); assert_eq!(parts, [(Some("PHOTOS"), true, false), (Some("SECRETS"), true, false)], "what's on it, and how much is stored where it's mounted"); - assert_eq!(target.missing, [(FsKind::Ext4, "e2fsprogs".to_string())]); - // Stopped before the erasing: nothing's asked of udisks2 but the unmounting. + assert_eq!(target.missing, [(FsKind::Ext4, "needs the e2fsprogs package".to_string())]); + assert!(target.mkfs_args, "udisks2 2.12 takes mkfs-args"); + // Stopped before the erasing: nothing's asked of udisks2 but the unmounting, and PHOTOS is + // mounted again. SECRETS can't be unlocked again without its passphrase, which is said. let mut steps = Vec::new(); - assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |s| { steps.push(s); s < FormatStep::Erasing }), Err(DiskError::Cancelled)); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |s| { steps.push(s); s < FormatStep::Erasing }), Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: true })); assert_eq!(steps, [FormatStep::Unmounting, FormatStep::Erasing]); assert!(standin.asked().is_empty()); - // A no at polkit's prompt changes nothing. + let mounted = |u: &Udisks| u.snapshot().unwrap().volumes().iter().filter(|v| v.mount.is_some()).filter_map(|v| v.label.clone()).collect::>(); + assert_eq!(mounted(&udisks), ["PHOTOS"], "mounted again"); + // A no at polkit's prompt changes nothing: it's all mounted again. let target = udisks.look_to_format(&udisks.snapshot().unwrap().volumes()[0]).unwrap(); standin.say("refuse"); - assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |_| true), Err(DiskError::Cancelled)); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |_| true), Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: false })); assert_eq!(udisks.snapshot().unwrap().volumes().len(), 2, "still there"); + assert_eq!(mounted(&udisks), ["PHOTOS"], "mounted again"); // Formatted: everything was unmounted and locked first, the stand-in refusing otherwise, // then a new table and one partition, which is mounted. let mut steps = Vec::new(); @@ -1077,12 +1287,21 @@ mod tests { let target = udisks.look_to_format(&now[0]).unwrap(); udisks.format(&target, FsKind::Ext4, "linux", &mut |_| true).unwrap(); assert!(standin.asked().last().unwrap().ends_with("0fc63daf-8483-4772-8e79-3d69d8477de4 \"\" ext4 auth.no_user_interaction=false label=linux take-ownership=true")); + // FAT32 is asked for as such, where udisks2 passes mkfs-args on. + let target = udisks.look_to_format(&udisks.snapshot().unwrap().volumes()[0]).unwrap(); + udisks.format(&target, FsKind::Fat32, "CAMERA", &mut |_| true).unwrap(); + assert!(standin.asked().last().unwrap().ends_with("ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 \"\" vfat auth.no_user_interaction=false label=CAMERA mkfs-args=-F,32"), "{:?}", standin.asked()); + standin.say("version 2.9.5"); + let target = udisks.look_to_format(&udisks.snapshot().unwrap().volumes()[0]).unwrap(); + assert!(!target.mkfs_args && target.missing.iter().all(|(k, _)| *k != FsKind::Fat32), "an older udisks2 on a 16 GB drive: mkfs.fat picks FAT32 itself"); + udisks.format(&target, FsKind::Fat32, "CAMERA", &mut |_| true).unwrap(); + assert!(standin.asked().last().unwrap().ends_with("vfat auth.no_user_interaction=false label=CAMERA"), "{:?}", standin.asked()); // Another stick in its place is left alone. standin.say("unplug Stick"); std::thread::sleep(Duration::from_millis(100)); standin.say("drive Stick SanDisk-9999"); standin.say("fs sdb1 Stick OTHER"); - assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true), Err(DiskError::Changed)); + assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true).map_err(|f| f.error), Err(DiskError::Changed)); // A drive that isn't removable, or that the system uses, is never formatted. standin.say("internal Disk WD-1"); standin.say("fs sdc1 Disk DATA"); @@ -1092,8 +1311,84 @@ mod tests { let other = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("OTHER")).unwrap(); let target = udisks.look_to_format(&other).unwrap(); standin.say("at sdb1 /boot"); - assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true), Err(DiskError::Other("the system uses it".into()))); - assert_eq!(standin.asked().len(), 5, "nothing more was asked"); + assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true).map_err(|f| f.error), Err(DiskError::Other("the system uses it".into()))); + assert_eq!(standin.asked().len(), 9, "nothing more was asked"); + } + + /// The format in a thread of its own, so the stand-in can be told things while it unmounts. + fn format_meanwhile(address: &str, target: FormatTarget) -> std::thread::JoinHandle, FormatFailed>> { + let address = address.to_string(); + std::thread::spawn(move || Udisks::connect(&address).unwrap().format(&target, FsKind::Exfat, "X", &mut |_| true)) + } + + #[test] + fn a_drive_that_changes_while_it_unmounts_is_left_alone() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + standin.say("drive Stick Kingston-1234"); + standin.say("fs sdb1 Stick PHOTOS"); + standin.say("fs sdb2 Stick OTHER"); + let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let photos = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("PHOTOS")).unwrap(); + udisks.mount(&photos).unwrap(); + // The system mounted from it while it unmounts. + standin.say("slow sdb1 600"); + let target = udisks.look_to_format(&photos).unwrap(); + let formatting = format_meanwhile(&standin.bus.address, target.clone()); + std::thread::sleep(Duration::from_millis(200)); + standin.say("at sdb2 /boot"); + let failed = formatting.join().unwrap().unwrap_err(); + assert_eq!(failed, FormatFailed { error: DiskError::Other("the system uses it, which changed while it was being unmounted".into()), erased: false, left_unmounted: false }); + assert!(standin.asked().is_empty(), "nothing erased"); + assert!(udisks.snapshot().unwrap().volumes().iter().any(|v| v.label.as_deref() == Some("PHOTOS") && v.mount.is_some()), "mounted again"); + // Another stick of the same make put in its place while it unmounts. + standin.say("drive Card SD-1"); + standin.say("fs mmc1 Card CARD"); + let card = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("CARD")).unwrap(); + udisks.mount(&card).unwrap(); + standin.say("slow mmc1 600"); + let target = udisks.look_to_format(&card).unwrap(); + let formatting = format_meanwhile(&standin.bus.address, target); + std::thread::sleep(Duration::from_millis(200)); + standin.say("swap Card"); + assert_eq!(formatting.join().unwrap().unwrap_err().error, DiskError::Changed); + assert!(standin.asked().is_empty(), "nothing erased"); + } + + #[test] + fn a_stick_the_running_system_started_from_is_never_formatted() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + let cmdline = standin.root.path().join("cmdline"); + std::fs::write(&cmdline, "BOOT_IMAGE=/vmlinuz quiet\n").unwrap(); + standin.say("drive Stick Kingston-1234"); + standin.say("fs sdb1 Stick ARCH_202601"); + let udisks = Udisks::connect(&standin.bus.address).unwrap().with_cmdline(cmdline.clone()); + let offered = |u: &Udisks| u.snapshot().unwrap().volumes()[0].formattable; + assert!(offered(&udisks)); + // Mounted where a live system mounts its medium. + standin.say("at sdb1 /run/archiso/bootmnt"); + assert!(!offered(&udisks)); + let v = udisks.snapshot().unwrap().volumes()[0].clone(); + assert_eq!(udisks.look_to_format(&v), Err(DiskError::Other("the running system started from it".into()))); + // Holding the file its root filesystem is a loop device of. + let at = standin.root.path().join("ARCH_202601"); + standin.say(&format!("at sdb1 {}", at.display())); + assert!(offered(&udisks)); + standin.say(&format!("loop loop0 {}/arch/x86_64/airootfs.sfs", at.display())); + assert!(!offered(&udisks)); + // The device the kernel's command line booted from, by UUID, label or path. + standin.say("drive Card SD-1"); + standin.say("fs mmc1 Card LIVE"); + standin.say("uuid mmc1 2026-01-01-10-00-00-00"); + let card = |u: &Udisks| u.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("LIVE")).unwrap().formattable; + assert!(card(&udisks)); + for line in ["archisodevice=UUID=2026-01-01-10-00-00-00", "archisolabel=LIVE", "root=/dev/disk/by-uuid/2026-01-01-10-00-00-00", "root=/dev/mmc1", "root=LABEL=LIVE"] { + std::fs::write(&cmdline, format!("BOOT_IMAGE=/vmlinuz {line} quiet\n")).unwrap(); + assert!(!card(&udisks), "{line}"); + } + std::fs::write(&cmdline, "root=UUID=0000-1111 archisolabel=OTHER\n").unwrap(); + assert!(card(&udisks), "another device"); } #[test] diff --git a/tests/e2e.py b/tests/e2e.py index b45b81e..c846d08 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -1706,11 +1706,13 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): disks.say("internal Disk WD-1", "fs sdc1 Disk DATA") disks.say("drive Card SD-1", "fs mmc1 Card CARDBOOT", "fs mmc2 Card CARDDATA", "at mmc1 /boot") disks.say("drive Sys SYS-1", "fs sys1 Sys SYSDATA", "fs sys2 Sys HIDDEN", "system sys2") + # And the stick a live system is running from. + disks.say("drive Live LIVE-1", "fs live1 Live LIVEDATA", "fs live2 Live LIVEBOOT", "at live2 /run/archiso/bootmnt") env = {"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address} a = App(h, fs, extra_env=env) - s = a.wait(lambda s: all(place_flags(s, l) is not None for l in ("ARCH_202512", "ARCHISO_EF1", "DATA", "CARDDATA", "SYSDATA")), "the drives") + s = a.wait(lambda s: all(place_flags(s, l) is not None for l in ("ARCH_202512", "ARCHISO_EF1", "DATA", "CARDDATA", "SYSDATA", "LIVEDATA")), "the drives") assert s["base"] == 0xfafafa, "light" - for label in ("DATA", "CARDDATA", "SYSDATA"): + for label in ("DATA", "CARDDATA", "SYSDATA", "LIVEDATA"): a.click(60, place_y(s, label), 0x111) items = a.wait(lambda s: s["menu"], f"{label}'s menu")["menu_items"] assert "Format…" not in items, f"{label}: {items}" @@ -1727,6 +1729,7 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): assert f["title"] == "Format “SanDisk Ultra, 16.0 GB”?", f assert re.fullmatch(r"Everything on “SanDisk Ultra, 16.0 GB” will be erased: the “ARCH_202512” partition, with [0-9.]+ [kMGT]?B of files, and the 8\.0 GB “ARCHISO_EF1” partition\. This can't be undone\.", f["warning"]), f["warning"] assert (f["focus"], f["kind"], f["name"], f["ready"]) == ("Button(1)", "exFAT", "", True), f + assert f["line"] == "Up to 15 characters, with no space at either end.", f assert [k[0] for k in f["kinds"]] == ["exFAT", "FAT32", "ext4"] and all(k[1] for k in f["kinds"]), f["kinds"] a.shot("format-dialog-light") # Enter on Cancel cancels. @@ -1792,7 +1795,15 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): # drive first, then it's there again by its new name, mounted. a.key("Tab", "Tab") format_focus(a, "Button(0)") + # Unmounting takes a moment, and meanwhile the drive shows as busy, and can't be ejected. + disks.say("slow sdb1 2500") a.key("space") + s = a.wait(lambda s: "busy" in (place_flags(s, "ARCH_202512") or set()) and "busy" in place_flags(s, "ARCHISO_EF1"), "busy while it's formatted") + a.shot("format-busy-light") + a.click(60, place_y(s, "ARCHISO_EF1"), 0x111) + menu = a.wait(lambda s: s["menu"], "its menu") + a.key("Escape") + assert menu["menu_items"][-2:] == ["Eject", "Format…"] and {"Unmount", "Eject", "Format…"} <= set(menu["menu_off"]), menu s = a.wait(lambda s: place_flags(s, "Holiday") == {"mounted", "eject"} and s["jobs"] == 0, "formatted and mounted", timeout=10) assert place_flags(s, "ARCH_202512") is None and place_flags(s, "ARCHISO_EF1") is None, s["places"] assert not s["dir"].startswith(str(media / "ARCH_202512")), "the window left the drive" @@ -1809,7 +1820,8 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): a.wait(lambda s: s["format"]["kind"] == "FAT32" and s["format"]["ready"], "FAT32") a.key("Tab", "space") s = a.wait(lambda s: place_flags(s, "CAMERA") == {"mounted", "eject"} and s["jobs"] == 0, "formatted as FAT32", timeout=10) - assert disks.asked()[-1] == 'CreatePartitionAndFormat Stick1 1048576 0 ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 "" vfat auth.no_user_interaction=false label=CAMERA' or disks.asked()[-1].endswith('"" vfat auth.no_user_interaction=false label=CAMERA'), disks.asked() + # Asked for as FAT32, as the stand-in's udisks2 (2.12) passes mkfs-args on. + assert disks.asked()[-1] == 'CreatePartitionAndFormat Stick 1048576 0 ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 "" vfat auth.no_user_interaction=false label=CAMERA mkfs-args=-F,32', disks.asked() # ext4, whose top folder is made the user's. open_format_dialog(a, "CAMERA") @@ -1897,7 +1909,7 @@ def a_screen_reader_hears_the_format_warning(h): assert alert["description"] == warning and warning.startswith("Everything on “SanDisk Ultra, 16.0 GB” will be erased"), alert assert "modal" in alert["states"], alert name = a11y_find(alert, "Name", "entry") - assert name and name["description"] == "Up to 15 characters." and "invalid" not in name["states"], name + assert name and name["description"] == "Up to 15 characters, with no space at either end." and "invalid" not in name["states"], name radios = [a11y_find(alert, k, "radio button") for k in ("exFAT", "FAT32", "ext4")] assert all(radios), alert assert "checked" in radios[0]["states"] and "enabled" in radios[0]["states"], radios[0] From 53334efc5cbc32841a93d18adbe9ed1e598cc32e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:19:00 -0700 Subject: [PATCH 3/4] ALI-2601: Second round of review fixes for formatting a drive - A Block.Format failure other than a refusal before it begins (polkit, or the drive busy) may have erased the drive. Say so, and don't mount anything again. - Refuse a drive with a device-mapper, loop or md device built on one of its blocks (read from /sys/dev/block/*/holders), other than the unlocked contents udisks2 reports for an encrypted partition. That covers Ventoy. - Read the boot device as the kernel splits its command line (with quotes), with archisosearchuuid=, a device in archisosearchfilename=, dracut's live: prefix, \x20 escapes, and by-id and by-path links followed. - After the drive changes mid-format, mount nothing again unless it's still the same drive with the same blocks, and say it was swapped. - A loop device's file on the stick is refused as "a file on it is in use (as a loop device)". - Tell a failed partition table write from a partition whose filesystem couldn't be made. - Compare the FAT32 512 MiB threshold with the partition's size. - Refuse "NO NAME" as a FAT32 name. --- README.md | 4 +- crates/app/src/app.rs | 16 +- crates/app/src/drives.rs | 2 +- crates/core/examples/udisks-standin.rs | 49 +++- crates/core/src/disks.rs | 360 ++++++++++++++++++++++--- 5 files changed, 377 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 3c70d51..c05822b 100644 --- a/README.md +++ b/README.md @@ -482,7 +482,9 @@ partition, which is mounted when it's done. Cancelling at the password prompt, o job before the erasing starts, leaves everything as it was and mounts again what was mounted; an unlocked encrypted partition stays locked, and Gannet says so. Format is only offered for drives that can come out, never for one udisks2 marks as the system's, one the system is -mounted from or swaps to, or the stick a live or installer system is running from. +mounted from or swaps to, or the stick a live or installer system is running from (including +one, like Ventoy's, that it maps without mounting). If erasing fails partway, as when the drive +is pulled out, Gannet says it may have been erased. ## Network shares diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index b1ce79d..49501a7 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -4117,9 +4117,11 @@ impl App { } /// A format has finished. The drive shows under Devices by its new name as udisks2 says so. - /// What's said depends on what it left: nothing erased and all mounted again, nothing erased - /// but some of it left unmounted (or locked), or erased with no partition made. + /// What's said depends on what it left (`Left`): nothing erased and all mounted again, + /// nothing erased but some of it left unmounted (or locked), maybe erased, erased with no + /// partition, or partitioned with no filesystem. fn format_done(&mut self, id: u64, target: FormatTarget, kind: FsKind, result: Result, FormatFailed>) { + use gannet_core::disks::Left; self.drives_busy.retain(|b| *b != target.drive); let view = self.jobs.iter().position(|j| j.job.id == id).map(|i| self.jobs.remove(i)); let stopped = view.as_ref().is_some_and(|v| v.job.is_cancelled()); @@ -4130,7 +4132,11 @@ impl App { let name = FormatAsk::new(target).drive_name(); match result { Ok(_) => self.note(format!("Formatted “{name}” as {}", kind.name())), - Err(FormatFailed { error, erased: true, .. }) => self.notice(format!("Couldn't format “{name}”: {error}. It was erased, and has no partition now")), + Err(FormatFailed { error, left: Left::MaybeErased, .. }) => self.notice(format!("Formatting “{name}” stopped partway, and it may have been erased: {error}")), + Err(FormatFailed { error, left: Left::Erased, .. }) => self.notice(format!("Couldn't format “{name}”: {error}. It was erased, and has no partition now")), + Err(FormatFailed { error, left: Left::Unformatted, .. }) => self.notice(format!("“{name}” was erased and partitioned, but the new partition couldn't be formatted: {error}")), + // Swapped or taken out: what was on it isn't this app's to mount again. + Err(FormatFailed { error: DiskError::Changed, .. }) => self.notice(format!("Didn't format “{name}”: {}. Nothing was erased", DiskError::Changed)), // Stopped before anything was erased. Err(FormatFailed { error: DiskError::Cancelled, left_unmounted: false, .. }) if stopped => self.note(format!("Stopped formatting “{name}”. Nothing was erased")), // The user said no at polkit's prompt, knows, and it's as it was. @@ -12688,9 +12694,9 @@ mod tests { // unmounted, it says so. let target = FormatTarget { drive: v.drive.clone(), identity: v.identity.clone(), whole: "/b/whole".into(), model: "SanDisk Ultra".into(), size: 16_000_000_000, parts: vec![], missing: vec![], mkfs_args: true }; let before = r.app.notices.len(); - r.app.on_msg(Msg::FormatDone { job: 999, target: target.clone(), kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: false }) }); + r.app.on_msg(Msg::FormatDone { job: 999, target: target.clone(), kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, left: gannet_core::disks::Left::Untouched, left_unmounted: false }) }); assert_eq!(r.app.notices.len(), before); - r.app.on_msg(Msg::FormatDone { job: 999, target, kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: true }) }); + r.app.on_msg(Msg::FormatDone { job: 999, target, kind: FsKind::Exfat, result: Err(FormatFailed { error: DiskError::Cancelled, left: gannet_core::disks::Left::Untouched, left_unmounted: true }) }); assert_eq!(r.app.notices.last().map(String::as_str), Some("Didn't format “SanDisk Ultra, 16.0 GB”. Nothing was erased, but it was left unmounted")); assert!(r.app.jobs.is_empty() && r.app.drives_busy.is_empty()); assert!(r.app.notices.contains(&"Formatted “SanDisk Ultra, 16.0 GB” as exFAT".to_string()), "{:?}", r.app.notices); diff --git a/crates/app/src/drives.rs b/crates/app/src/drives.rs index 37a51e6..72e45e0 100644 --- a/crates/app/src/drives.rs +++ b/crates/app/src/drives.rs @@ -133,7 +133,7 @@ pub fn format(hub: Hub, address: String, target: FormatTarget, kind: FsKind, lab }; let result = match Udisks::connect(&address) { Ok(udisks) => udisks.format(&target, kind, &label, &mut step), - Err(error) => Err(disks::FormatFailed { error, erased: false, left_unmounted: false }), + Err(error) => Err(disks::FormatFailed::before_erasing(error)), }; hub.send(Msg::FormatDone { job: job.id, target, kind, result }); }); diff --git a/crates/core/examples/udisks-standin.rs b/crates/core/examples/udisks-standin.rs index 492c688..484a6a3 100644 --- a/crates/core/examples/udisks-standin.rs +++ b/crates/core/examples/udisks-standin.rs @@ -24,6 +24,14 @@ //! loop NAME FILE a loop device made from FILE //! container NAME DRIVE an MBR extended partition on it, holding the logical ones //! version V what Manager.Version says (2.12.0 to start with) +//! fail MESSAGE... the next Format fails with MESSAGE, as udisks2's own errors do, or +//! with udisks2's DeviceBusy for `fail busy` +//! hang MS the next Format takes MS milliseconds, then fails +//! size DRIVE BYTES the drive's size (16 GB to start with) +//! nomkfs the next CreatePartitionAndFormat makes the partition, then fails to +//! make its filesystem, as with mkfs missing +//! +//! Each block's device number is made from its path, for a check's own /sys to name. //! asked each Format and CreatePartitionAndFormat asked for, a line each //! starting `asked `, before the `ok` //! @@ -49,6 +57,7 @@ const ROOT: &str = "/org/freedesktop/UDisks2"; #[derive(Clone, Default)] struct DriveState { id: String, + size: Option, media_detected: u64, vendor: String, model: String, @@ -88,6 +97,9 @@ struct State { lacks: HashMap, refuse: bool, version: String, + fail: Option, + hang: Option, + nomkfs: bool, /// The formatting calls made, as `asked` lists them. asked: Vec, } @@ -117,6 +129,13 @@ fn held_open(dir: &Path) -> bool { }) } +/// A device number for a block, from its path: major 8, as SCSI disks have, and a minor from +/// the path's bytes. +fn devnum(at: &str) -> u64 { + let minor = at.bytes().fold(7u32, |h, b| h.wrapping_mul(31).wrapping_add(b.into())) % 1_000_000; + rustix::fs::makedev(8, minor) +} + fn path(kind: &str, name: &str) -> String { format!("{ROOT}/{kind}/{name}") } @@ -144,7 +163,7 @@ impl DriveIface { } #[zbus(property)] fn size(&self) -> u64 { - 16_000_000_000 + self.state.lock().unwrap().drives.get(&self.at).and_then(|d| d.size).unwrap_or(16_000_000_000) } #[zbus(property)] fn vendor(&self) -> String { @@ -236,6 +255,10 @@ impl BlockIface { self.get(|b| b.uuid.clone()) } #[zbus(property)] + fn device_number(&self) -> u64 { + devnum(&self.at) + } + #[zbus(property)] fn device(&self) -> Vec { [format!("/dev/{}", self.at.rsplit('/').next().unwrap_or("")).as_bytes(), b"\0"].concat() } @@ -248,6 +271,14 @@ impl BlockIface { if std::mem::take(&mut s.refuse) { return Err(UdError::NotAuthorizedDismissed("Not authorized to perform operation".into())); } + if let Some(why) = s.fail.take() { + return Err(if why == "busy" { UdError::DeviceBusy("Error wiping device: Device or resource busy".into()) } else { UdError::Failed(why) }); + } + if let Some(d) = s.hang.take() { + drop(s); + std::thread::sleep(d); + return Err(UdError::Failed("took too long".into())); + } let Some(drive) = s.blocks.get(&self.at).filter(|b| b.table).map(|b| b.drive.clone()) else { return Err(UdError::Failed("not a whole disk".into())) }; // As with the kernel: nothing on it can be in use. let on: Vec = s.blocks.iter().filter(|(p, b)| b.drive == drive && **p != self.at).map(|(p, _)| p.clone()).collect(); @@ -447,10 +478,18 @@ impl TableIface { _ => String::new(), }; let made = format!("{}1", self.at); - s.blocks.insert(made.clone(), BlockState { drive: whole.drive, label, usage: "filesystem".into(), id_type: format_type, backing: "/".into(), partition_of: Some(self.at.clone()), mounted: Some(None), ..BlockState::default() }); - made + let nomkfs = std::mem::take(&mut s.nomkfs); + let (usage, id_type, mounted) = if nomkfs { (String::new(), String::new(), None) } else { ("filesystem".into(), format_type, Some(None)) }; + s.blocks.insert(made.clone(), BlockState { drive: whole.drive, label, usage, id_type, backing: "/".into(), partition_of: Some(self.at.clone()), mounted, ..BlockState::default() }); + (made, nomkfs) }; + let (made, nomkfs) = made; let server = conn.object_server(); + if nomkfs { + server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; + server.at(made.as_str(), PartitionIface { at: made.clone(), state: self.state.clone() }).await?; + return Err(UdError::Failed("Error creating file system 'vfat': Executable mkfs.vfat not found".into())); + } server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; server.at(made.as_str(), FilesystemIface { at: made.clone(), state: self.state.clone() }).await?; server.at(made.as_str(), PartitionIface { at: made.clone(), state: self.state.clone() }).await?; @@ -569,6 +608,10 @@ fn command(conn: &Connection, state: &Shared, line: &str) -> Result<(), String> state.lock().unwrap().lacks.insert(kind.to_string(), utility.to_string()); } ["refuse"] => state.lock().unwrap().refuse = true, + ["fail", why @ ..] if !why.is_empty() => state.lock().unwrap().fail = Some(why.join(" ")), + ["hang", ms] => state.lock().unwrap().hang = Some(std::time::Duration::from_millis(ms.parse().map_err(|_| "not a number")?)), + ["nomkfs"] => state.lock().unwrap().nomkfs = true, + ["size", drive, bytes] => state.lock().unwrap().drives.get_mut(&path("drives", drive)).ok_or("no such drive")?.size = Some(bytes.parse().map_err(|_| "not a number")?), ["slow", name, ms] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.slow = Some(std::time::Duration::from_millis(ms.parse().map_err(|_| "not a number")?)), ["swap", drive] => state.lock().unwrap().drives.get_mut(&path("drives", drive)).ok_or("no such drive")?.media_detected += 1, ["uuid", name, uuid] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.uuid = uuid.to_string(), diff --git a/crates/core/src/disks.rs b/crates/core/src/disks.rs index 6b1d548..71138fe 100644 --- a/crates/core/src/disks.rs +++ b/crates/core/src/disks.rs @@ -88,6 +88,8 @@ pub struct Block { pub device: Option, /// For a loop device, the file it's made from. pub loop_file: Option, + /// Its device number, for finding it in /sys. + pub devnum: u64, } /// Everything udisks2 knows about drives and the blocks on them, at one moment. @@ -98,6 +100,9 @@ pub struct Snapshot { /// The devices the kernel's command line says the system booted from, as written there: /// `UUID=…`, `LABEL=…`, `PARTUUID=…`, `PARTLABEL=…` or a path. See [`boot_devices`]. pub boot: Vec, + /// For each block on a drive, the kernel devices built on it (its holders in /sys), like + /// `dm-0`, `loop3` or `md127`. See [`holders_of`]. + pub holders: BTreeMap>, } /// What makes a drive the one that was picked, more than its path does. @@ -219,6 +224,7 @@ impl Snapshot { part_name: iface("Partition").map(|p| string_of(p, "Name")).unwrap_or_default(), device: path_of(b, "Device"), loop_file: iface("Loop").and_then(|l| path_of(l, "BackingFile")), + devnum: u64_of(b, "DeviceNumber"), }, ); } @@ -301,8 +307,11 @@ impl Snapshot { if blocks.iter().any(|b| b.hint_system || b.swap || system_mount(b)) { return Some("the system uses it"); } - if self.started_from(&blocks) { - return Some("the running system started from it"); + if let Some(why) = self.started_from(&blocks) { + return Some(why); + } + if let Some(why) = self.built_on(&blocks) { + return Some(why); } if blocks.iter().any(|b| b.id_usage == "raid" || b.id_type == "LVM2_member") { return Some("it's part of a RAID or LVM set"); @@ -313,14 +322,14 @@ impl Snapshot { None } - /// Whether a live or installer system is running from any of `blocks`: one is mounted - /// where live systems mount their medium, one holds the file a loop device is made from (a - /// live system's squashfs), or one is the device the kernel's command line booted from. - fn started_from(&self, blocks: &[&Block]) -> bool { + /// Why `blocks` look like what a live or installer system is running from, if they do: one is + /// mounted where live systems mount their medium, one is the device the kernel's command + /// line booted from, or one holds the file a loop device is made from (as a live system's + /// squashfs is). The last can be any file in use as a loop device, which is refused too. + fn started_from(&self, blocks: &[&Block]) -> Option<&'static str> { const LIVE: [&str; 5] = ["/run/archiso", "/run/initramfs", "/run/live", "/cdrom", "/lib/live/mount"]; let mounts: Vec<&PathBuf> = blocks.iter().filter_map(|b| b.mount_points.as_ref()).flatten().collect(); let live = mounts.iter().any(|m| LIVE.iter().any(|l| m.starts_with(l))); - let looped = self.blocks.values().filter_map(|b| b.loop_file.as_ref()).any(|f| mounts.iter().any(|m| f.starts_with(m))); let booted = blocks.iter().any(|b| { self.boot.iter().any(|r| match r.split_once('=') { Some(("UUID", u)) => !u.is_empty() && b.uuid.eq_ignore_ascii_case(u), @@ -330,7 +339,30 @@ impl Snapshot { _ => b.device.as_ref().is_some_and(|d| std::path::Path::new(r) == d), }) }); - live || looped || booted + if live || booted { + return Some("the running system started from it"); + } + let looped = self.blocks.values().filter_map(|b| b.loop_file.as_ref()).any(|f| mounts.iter().any(|m| f.starts_with(m))); + looped.then_some("a file on it is in use (as a loop device)") + } + + /// Why another kernel device built on one of `blocks` stops it being formatted, if one does: + /// a RAID set, or a device-mapper or loop device, as a live system like Ventoy runs from + /// without mounting the stick. The unlocked contents of an encrypted partition, as udisks2 + /// reports them, are fine: they're locked first. + fn built_on(&self, blocks: &[&Block]) -> Option<&'static str> { + for b in blocks { + let cleartext = b.encrypted.clone().flatten().and_then(|c| self.blocks.get(&c)).and_then(|c| c.device.as_ref()).and_then(|d| d.file_name()).map(|n| n.to_string_lossy().into_owned()); + for h in self.holders.get(&b.path).into_iter().flatten() { + if h.starts_with("md") { + return Some("it's part of a RAID or LVM set"); + } + if (h.starts_with("dm-") || h.starts_with("loop")) && cleartext.as_deref() != Some(h.as_str()) { + return Some("another device is built on it, as a live system's can be"); + } + } + } + None } /// What's on a drive, for the warning before it's formatted: each partition, or the whole @@ -346,26 +378,80 @@ impl Snapshot { } } +/// The kernel's command line split into its parameters as the kernel splits it: at spaces, +/// except inside double quotes, which are dropped, so `"root=LABEL=my usb"` and +/// `root="LABEL=my usb"` are both one parameter. +fn kernel_params(cmdline: &str) -> Vec { + let (mut out, mut word, mut quoted, mut any) = (Vec::new(), String::new(), false, false); + for c in cmdline.chars() { + match c { + '"' => { + quoted = !quoted; + any = true; + } + c if c.is_whitespace() && !quoted => { + if any || !word.is_empty() { + out.push(std::mem::take(&mut word)); + } + any = false; + } + c => word.push(c), + } + } + if any || !word.is_empty() { + out.push(word); + } + out +} + +/// A label as /dev/disk/by-label and some command lines write it, with `\x20` for a space and +/// other bytes the same way. +fn unescape(s: &str) -> String { + let mut out = Vec::new(); + let b = s.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i] == b'\\' && b.get(i + 1) == Some(&b'x') && let Some(n) = s.get(i + 2..i + 4).and_then(|h| u8::from_str_radix(h, 16).ok()) { + out.push(n); + i += 4; + } else { + out.push(b[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + /// The devices the kernel was told to boot from, from its command line: `root=`, and the -/// `archisodevice=` and `archisolabel=` of an Arch live or installer system, each as `UUID=…`, -/// `LABEL=…`, `PARTUUID=…`, `PARTLABEL=…` or a path. A `/dev/disk/by-*/` path becomes the same. -pub fn boot_devices(cmdline: &str) -> Vec { +/// `archisodevice=`, `archisolabel=`, `archisosearchuuid=` and (when it names a device) +/// `archisosearchfilename=` of an Arch live or installer system, each as `UUID=…`, `LABEL=…`, +/// `PARTUUID=…`, `PARTLABEL=…` or a path. A dracut `live:` prefix (`root=live:CDLABEL=…`) is +/// read through. A `/dev/disk/by-*/` link becomes the same, by its name for UUIDs and labels; +/// `resolve` follows by-id, by-path and other links to the device they point at. +pub fn boot_devices(cmdline: &str, resolve: impl Fn(&std::path::Path) -> Option) -> Vec { let mut out = Vec::new(); - for word in cmdline.split_whitespace() { + for word in kernel_params(cmdline) { let Some((key, value)) = word.split_once('=') else { continue }; - let value = value.trim_matches('"'); + let value = value.strip_prefix("live:").unwrap_or(value); let r = match key { - "root" | "archisodevice" => match value.strip_prefix("/dev/disk/by-") { - Some(by) => match by.split_once('/') { + "root" | "archisodevice" => match value.split_once('=') { + Some(("CDLABEL" | "LABEL", l)) => format!("LABEL={}", unescape(l)), + Some((k @ ("UUID" | "PARTUUID" | "PARTLABEL"), v)) => format!("{k}={}", unescape(v)), + _ => match value.strip_prefix("/dev/disk/by-").and_then(|by| by.split_once('/')) { Some(("uuid", v)) => format!("UUID={v}"), - Some(("label", v)) => format!("LABEL={v}"), + Some(("label", v)) => format!("LABEL={}", unescape(v)), Some(("partuuid", v)) => format!("PARTUUID={v}"), - Some(("partlabel", v)) => format!("PARTLABEL={v}"), - _ => value.to_string(), + Some(("partlabel", v)) => format!("PARTLABEL={}", unescape(v)), + Some(_) => match resolve(std::path::Path::new(value)) { + Some(to) => to.to_string_lossy().into_owned(), + None => value.to_string(), + }, + None => value.to_string(), }, - None => value.to_string(), }, - "archisolabel" => format!("LABEL={value}"), + "archisolabel" => format!("LABEL={}", unescape(value)), + "archisosearchuuid" => format!("UUID={value}"), + "archisosearchfilename" if value.starts_with("/dev/") => value.to_string(), _ => continue, }; out.push(r); @@ -373,6 +459,15 @@ pub fn boot_devices(cmdline: &str) -> Vec { out } +/// The kernel devices built on the block device `devnum`, by name, from `sysfs`'s +/// `dev/block/MAJ:MIN/holders`. Nothing if it can't be read. +pub fn holders_of(sysfs: &std::path::Path, devnum: u64) -> Vec { + let dir = sysfs.join(format!("dev/block/{}:{}/holders", rustix::fs::major(devnum), rustix::fs::minor(devnum))); + let mut out: Vec = std::fs::read_dir(dir).map(|d| d.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + out.sort(); + out +} + /// Where the running system's own filesystems are mounted. A drive with one of them mounted from /// it is never formatted. Anything under `/var/` counts, which also refuses a stick mounted at /// `/var/mnt/…` (as Fedora Atomic can): rare for a stick, and the safe side to be on. @@ -457,6 +552,10 @@ impl FsKind { if n > 11 { return Err(format!("FAT32 allows 11 characters. This has {n}.")); } + // mkfs.fat writes no name at all for this one, as it's what FAT calls a drive with none. + if typed.eq_ignore_ascii_case("NO NAME") { + return Err("“NO NAME” means no name on FAT32. Leave the name empty, or choose another.".to_string()); + } Ok(typed.to_ascii_uppercase()) } FsKind::Ext4 => { @@ -515,25 +614,43 @@ pub struct FormatTarget { pub mkfs_args: bool, } -/// Why a format didn't finish, and what that left: whether the drive was erased, and whether -/// what was mounted on it before is mounted again. +/// How far a format that didn't finish got, which is what the drive was left as. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Left { + /// Nothing was erased: it stopped before the erasing, or udisks2 refused it before it began + /// (a no at polkit's prompt, or the drive busy). + Untouched, + /// The erasing failed some other way, like timing out or the drive going: it may have been + /// erased. What was mounted isn't mounted again. + MaybeErased, + /// Erased, with a new, empty partition table. + Erased, + /// Erased and partitioned, but the new partition couldn't be formatted. + Unformatted, +} + +/// Why a format didn't finish, and what that left: how far it got, and whether what was mounted +/// on it before is mounted again. #[derive(Clone, Debug, PartialEq)] pub struct FormatFailed { pub error: DiskError, - pub erased: bool, + pub left: Left, /// Something that was mounted or unlocked before is no longer. An encrypted volume can't be /// unlocked again without its passphrase, so one that was unlocked always counts. pub left_unmounted: bool, } impl FormatFailed { - fn before_erasing(error: DiskError) -> Self { - Self { error, erased: false, left_unmounted: false } + pub fn before_erasing(error: DiskError) -> Self { + Self { error, left: Left::Untouched, left_unmounted: false } } } /// Below this, mkfs.fat picks FAT16 or FAT12 unless told FAT32. const FAT32_LEAST: u64 = 512 << 20; +/// How much smaller the partition made is than the drive: 1 MiB before it, and about as much +/// after it for the GPT's backup and alignment. +const PARTITION_SLACK: u64 = 2 << 20; /// How far a format has got, in order. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -610,6 +727,8 @@ pub struct Udisks { bus: Bus, /// The kernel's command line, for the device the system booted from. Test seam: another file. cmdline: PathBuf, + /// Where sysfs is, for what's built on each block. Test seam: a folder made to look like it. + sysfs: PathBuf, } /// Busy filesystems are tried this many times, this far apart: a second in all. @@ -621,7 +740,13 @@ pub const ACTION_LIMIT: Duration = Duration::from_secs(600); impl Udisks { pub fn new(bus: Bus) -> Self { - Self { bus, cmdline: PathBuf::from("/proc/cmdline") } + Self { bus, cmdline: PathBuf::from("/proc/cmdline"), sysfs: PathBuf::from("/sys") } + } + + /// Test seam: reads what's built on each block from `root`, laid out as /sys, instead. + pub fn with_sysfs(mut self, root: PathBuf) -> Self { + self.sysfs = root; + self } /// Test seam: reads the kernel's command line from `file` instead. @@ -631,7 +756,12 @@ impl Udisks { } pub fn connect(address: &str) -> Result { - Bus::connect_with_limit(address, ACTION_LIMIT).map(Self::new).map_err(|e| disk_error(e, false)) + Self::connect_with_limit(address, ACTION_LIMIT) + } + + /// Test seam: calls that take longer than `limit` fail, as a hung udisks2's would. + pub fn connect_with_limit(address: &str, limit: Duration) -> Result { + Bus::connect_with_limit(address, limit).map(Self::new).map_err(|e| disk_error(e, false)) } pub fn bus(&self) -> &Bus { @@ -641,7 +771,9 @@ impl Udisks { pub fn snapshot(&self) -> Result { let objects: Objects = self.bus.call(SERVICE, ROOT, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", &()).map_err(|e| disk_error(e, false))?; let mut s = Snapshot::from_objects(&objects); - s.boot = boot_devices(&std::fs::read_to_string(&self.cmdline).unwrap_or_default()); + s.boot = boot_devices(&std::fs::read_to_string(&self.cmdline).unwrap_or_default(), |p| std::fs::canonicalize(p).ok()); + // Only blocks on a drive, a handful, and only when udisks2 says something changed. + s.holders = s.blocks.values().filter(|b| b.drive != NONE && !b.drive.is_empty() && b.devnum != 0).map(|b| (b.path.clone(), holders_of(&self.sysfs, b.devnum))).filter(|(_, h)| !h.is_empty()).collect(); Ok(s) } @@ -821,7 +953,9 @@ impl Udisks { let mut missing: Vec<(FsKind, String)> = FsKind::ALL.into_iter().filter_map(|k| self.missing(k).map(|u| (k, format!("needs the {} package", package_for(&u))))).collect(); let mkfs_args = self.takes_mkfs_args(); // Without asking for FAT32, a drive this small would get FAT16. - if !mkfs_args && drive.size < FAT32_LEAST && !missing.iter().any(|(k, _)| *k == FsKind::Fat32) { + // The partition it makes: from 1 MiB in, short of the GPT's backup at the end. + let partition = drive.size.saturating_sub(PARTITION_SLACK); + if !mkfs_args && partition < FAT32_LEAST && !missing.iter().any(|(k, _)| *k == FsKind::Fat32) { missing.push((FsKind::Fat32, "needs udisks2 2.10 or newer on a drive under 512 MiB".into())); } Ok(FormatTarget { drive: drive.path.clone(), identity: volume.identity.clone(), whole: whole.path.clone(), model, size: drive.size, parts, missing, mkfs_args }) @@ -861,12 +995,16 @@ impl Udisks { let blocks = now.on_drive(&target.drive); let mounted: Vec = blocks.iter().filter(|b| b.crypto_backing.is_empty() || b.crypto_backing == NONE).filter(|b| b.mount_points.as_ref().is_some_and(|m| !m.is_empty())).map(|b| b.path.clone()).collect(); let unlocked = blocks.iter().any(|b| matches!(b.encrypted, Some(Some(_)))); + // Mounted again only if it's still the same drive and the same blocks on it: after a + // stick's been swapped, a block's path can be another stick's. let undo = |error: DiskError| { + let same = self.snapshot().ok().filter(|s| s.same_drive(&target.drive, &target.identity)); let mut all = !unlocked; for b in &mounted { - all &= self.mount_block(b).is_ok(); + let there = same.as_ref().is_some_and(|s| s.blocks.get(b).is_some_and(|x| x.drive == target.drive)); + all &= there && self.mount_block(b).is_ok(); } - FormatFailed { error, erased: false, left_unmounted: !all } + FormatFailed { error, left: Left::Untouched, left_unmounted: !all } }; self.release(&now, &target.drive).map_err(undo)?; // Unmounting can take a while, and the drive can change meanwhile. @@ -878,7 +1016,12 @@ impl Udisks { if !step(FormatStep::Erasing) { return Err(undo(DiskError::Cancelled)); } - self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false).map_err(undo)?; + // Only a refusal before it begins (polkit, or the drive busy) leaves it untouched. Any + // other failure, like a timeout or the drive going, can come partway through. + self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false).map_err(|e| match e { + DiskError::Cancelled | DiskError::NotAuthorized | DiskError::Busy => undo(e), + error => FormatFailed { error, left: Left::MaybeErased, left_unmounted: true }, + })?; step(FormatStep::Making); let mut made = options(); made.insert("label", Variant::from(label.to_string())); @@ -893,7 +1036,11 @@ impl Udisks { } let created: OwnedObjectPath = self .call(&target.whole, "PartitionTable", "CreatePartitionAndFormat", &(1u64 << 20, 0u64, kind.partition_type(), "", options(), kind.udisks(), made), false) - .map_err(|error| FormatFailed { error, erased: true, left_unmounted: true })?; + .map_err(|error| { + // The partition can be made and its filesystem then fail, as when mkfs is missing. + let partitioned = self.snapshot().is_ok_and(|s| s.blocks.values().any(|b| b.partition_of == target.whole)); + FormatFailed { error, left: if partitioned { Left::Unformatted } else { Left::Erased }, left_unmounted: true } + })?; step(FormatStep::Opening); // It's formatted. Its filesystem can take a moment to show, and not opening it isn't // worth more than saying it's done. @@ -1065,22 +1212,70 @@ mod tests { #[test] fn the_boot_device_is_read_from_the_command_line() { - assert_eq!(boot_devices("BOOT_IMAGE=/vmlinuz root=UUID=abcd rw quiet"), ["UUID=abcd"]); - assert_eq!(boot_devices("archisobasedir=arch archisodevice=UUID=2026-01-01 archisolabel=ARCH_202601"), ["UUID=2026-01-01", "LABEL=ARCH_202601"]); - assert_eq!(boot_devices("root=/dev/disk/by-partuuid/1234-02 root=/dev/sda2 root=PARTLABEL=linux"), ["PARTUUID=1234-02", "/dev/sda2", "PARTLABEL=linux"]); - assert!(boot_devices("rootflags=subvol=@ rootfstype=btrfs").is_empty()); + let none = |_: &std::path::Path| None; + let boot = |c: &str| boot_devices(c, none); + assert_eq!(boot("BOOT_IMAGE=/vmlinuz root=UUID=abcd rw quiet"), ["UUID=abcd"]); + assert_eq!(boot("archisobasedir=arch archisodevice=UUID=2026-01-01 archisolabel=ARCH_202601"), ["UUID=2026-01-01", "LABEL=ARCH_202601"]); + assert_eq!(boot("root=/dev/disk/by-partuuid/1234-02 root=/dev/sda2 root=PARTLABEL=linux"), ["PARTUUID=1234-02", "/dev/sda2", "PARTLABEL=linux"]); + assert!(boot("rootflags=subvol=@ rootfstype=btrfs").is_empty()); + // Arch's search by UUID, and a search file only when it names a device. + assert_eq!(boot("archisosearchuuid=2026-01-01-10-00 archisosearchfilename=/boot/x.uuid archisosearchfilename=/dev/sdc1"), ["UUID=2026-01-01-10-00", "/dev/sdc1"]); + // Quotes round the whole parameter, or round a value with spaces, as the kernel reads them. + assert_eq!(boot("quiet \"root=UUID=x\" splash"), ["UUID=x"]); + assert_eq!(boot("root=\"LABEL=my usb\" quiet"), ["LABEL=my usb"]); + assert_eq!(kernel_params("a=\"b c\" \"d e\" f"), ["a=b c", "d e", "f"]); + // dracut's live: prefix, and escaped labels. + assert_eq!(boot("root=live:CDLABEL=Fedora-WS-Live-41 rd.live.image"), ["LABEL=Fedora-WS-Live-41"]); + assert_eq!(boot("root=live:UUID=abcd"), ["UUID=abcd"]); + assert_eq!(boot("root=live:LABEL=my\\x20usb root=/dev/disk/by-label/my\\x20usb"), ["LABEL=my usb", "LABEL=my usb"]); + // by-id and by-path links are followed to their device. + let resolve = |p: &std::path::Path| (p == std::path::Path::new("/dev/disk/by-id/usb-SanDisk_Ultra-0:0-part1")).then(|| PathBuf::from("/dev/sdb1")); + assert_eq!(boot_devices("root=/dev/disk/by-id/usb-SanDisk_Ultra-0:0-part1 archisodevice=/dev/disk/by-path/x", resolve), ["/dev/sdb1", "/dev/disk/by-path/x"]); // Matched against the blocks on a drive. let mut s = Snapshot::from_objects(&machine(false)); let stick = format!("{ROOT}/drives/Stick"); s.blocks.get_mut(&format!("{ROOT}/block_devices/sdb1")).unwrap().uuid = "ABCD-1234".into(); - s.boot = boot_devices("root=UUID=abcd-1234"); + s.boot = boot("root=UUID=abcd-1234"); assert_eq!(s.format_refusal(&stick), Some("the running system started from it"), "a UUID in either case"); - s.boot = boot_devices("archisolabel=SPARE"); + s.boot = boot("archisolabel=SPARE"); assert_eq!(s.format_refusal(&stick), Some("the running system started from it")); - s.boot = boot_devices("root=UUID="); + s.blocks.get_mut(&format!("{ROOT}/block_devices/sdb3")).unwrap().device = Some("/dev/sdb3".into()); + s.boot = boot_devices("root=/dev/disk/by-id/usb-SanDisk_Ultra-0:0-part3", |_| Some(PathBuf::from("/dev/sdb3"))); + assert_eq!(s.format_refusal(&stick), Some("the running system started from it"), "a by-id link to it"); + s.boot = boot("root=UUID="); assert_eq!(s.format_refusal(&stick), None, "an empty one matches nothing"); } + #[test] + fn a_device_built_on_the_stick_keeps_it_from_being_formatted() { + // What's built on each block, read from a sysfs of its own. + let sys = crate::testutil::Scratch::new(); + let dev = rustix::fs::makedev(8, 17); + std::fs::create_dir_all(sys.path().join("dev/block/8:17/holders/dm-3")).unwrap(); + std::fs::create_dir_all(sys.path().join("dev/block/8:17/holders/loop0")).unwrap(); + assert_eq!(holders_of(sys.path(), dev), ["dm-3", "loop0"]); + assert!(holders_of(sys.path(), rustix::fs::makedev(8, 18)).is_empty(), "none"); + let stick = format!("{ROOT}/drives/Stick"); + let sdb1 = format!("{ROOT}/block_devices/sdb1"); + let refusal = |unlocked: bool, holder: &str, on: &str| { + let mut s = Snapshot::from_objects(&machine(unlocked)); + if unlocked { + s.blocks.get_mut(&format!("{ROOT}/block_devices/dm_2d1")).unwrap().device = Some("/dev/dm-0".into()); + } + s.holders.insert(on.to_string(), vec![holder.to_string()]); + s.format_refusal(&stick) + }; + // Ventoy's device-mapper device over a partition that isn't mounted. + assert_eq!(refusal(false, "dm-3", &format!("{ROOT}/block_devices/sdb3")), Some("another device is built on it, as a live system's can be")); + assert_eq!(refusal(false, "loop0", &sdb1), Some("another device is built on it, as a live system's can be")); + assert_eq!(refusal(false, "md127", &sdb1), Some("it's part of a RAID or LVM set")); + // The whole disk mapped, too. + assert_eq!(refusal(false, "dm-1", &format!("{ROOT}/block_devices/sdb")), Some("another device is built on it, as a live system's can be")); + // An unlocked encrypted partition's own contents are fine: they're locked first. + assert_eq!(refusal(true, "dm-0", &format!("{ROOT}/block_devices/sdb2")), None); + assert_eq!(refusal(true, "dm-5", &format!("{ROOT}/block_devices/sdb2")), Some("another device is built on it, as a live system's can be"), "another one isn't"); + } + #[test] fn names_fit_the_format() { assert_eq!(FsKind::Exfat.label("Holiday photos"), Ok("Holiday photos".into())); @@ -1092,6 +1287,8 @@ mod tests { assert_eq!(FsKind::Fat32.label("férias"), Err("FAT32 names can't have “é”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); assert_eq!(FsKind::Fat32.label("a+b"), Err("FAT32 names can't have “+”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); assert_eq!(FsKind::Fat32.label("my-cam_(2)"), Ok("MY-CAM_(2)".into()), "every symbol the rule lists"); + assert_eq!(FsKind::Fat32.label("no name"), Err("“NO NAME” means no name on FAT32. Leave the name empty, or choose another.".into())); + assert_eq!(FsKind::Exfat.label("NO NAME"), Ok("NO NAME".into()), "only FAT32 reads it so"); for kind in FsKind::ALL { assert_eq!(kind.label(" "), Err("Names can't start or end with a space.".into()), "{kind:?}: spaces alone"); assert_eq!(kind.label(" a"), Err("Names can't start or end with a space.".into())); @@ -1258,7 +1455,7 @@ mod tests { // Stopped before the erasing: nothing's asked of udisks2 but the unmounting, and PHOTOS is // mounted again. SECRETS can't be unlocked again without its passphrase, which is said. let mut steps = Vec::new(); - assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |s| { steps.push(s); s < FormatStep::Erasing }), Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: true })); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |s| { steps.push(s); s < FormatStep::Erasing }), Err(FormatFailed { error: DiskError::Cancelled, left: Left::Untouched, left_unmounted: true })); assert_eq!(steps, [FormatStep::Unmounting, FormatStep::Erasing]); assert!(standin.asked().is_empty()); let mounted = |u: &Udisks| u.snapshot().unwrap().volumes().iter().filter(|v| v.mount.is_some()).filter_map(|v| v.label.clone()).collect::>(); @@ -1266,7 +1463,7 @@ mod tests { // A no at polkit's prompt changes nothing: it's all mounted again. let target = udisks.look_to_format(&udisks.snapshot().unwrap().volumes()[0]).unwrap(); standin.say("refuse"); - assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |_| true), Err(FormatFailed { error: DiskError::Cancelled, erased: false, left_unmounted: false })); + assert_eq!(udisks.format(&target, FsKind::Exfat, "NEW", &mut |_| true), Err(FormatFailed { error: DiskError::Cancelled, left: Left::Untouched, left_unmounted: false })); assert_eq!(udisks.snapshot().unwrap().volumes().len(), 2, "still there"); assert_eq!(mounted(&udisks), ["PHOTOS"], "mounted again"); // Formatted: everything was unmounted and locked first, the stand-in refusing otherwise, @@ -1338,7 +1535,7 @@ mod tests { std::thread::sleep(Duration::from_millis(200)); standin.say("at sdb2 /boot"); let failed = formatting.join().unwrap().unwrap_err(); - assert_eq!(failed, FormatFailed { error: DiskError::Other("the system uses it, which changed while it was being unmounted".into()), erased: false, left_unmounted: false }); + assert_eq!(failed, FormatFailed { error: DiskError::Other("the system uses it, which changed while it was being unmounted".into()), left: Left::Untouched, left_unmounted: false }); assert!(standin.asked().is_empty(), "nothing erased"); assert!(udisks.snapshot().unwrap().volumes().iter().any(|v| v.label.as_deref() == Some("PHOTOS") && v.mount.is_some()), "mounted again"); // Another stick of the same make put in its place while it unmounts. @@ -1351,8 +1548,9 @@ mod tests { let formatting = format_meanwhile(&standin.bus.address, target); std::thread::sleep(Duration::from_millis(200)); standin.say("swap Card"); - assert_eq!(formatting.join().unwrap().unwrap_err().error, DiskError::Changed); + assert_eq!(formatting.join().unwrap().unwrap_err(), FormatFailed { error: DiskError::Changed, left: Left::Untouched, left_unmounted: true }); assert!(standin.asked().is_empty(), "nothing erased"); + assert!(udisks.snapshot().unwrap().volumes().iter().any(|v| v.label.as_deref() == Some("CARD") && v.mount.is_none()), "another card's partition isn't mounted for it"); } #[test] @@ -1377,6 +1575,8 @@ mod tests { assert!(offered(&udisks)); standin.say(&format!("loop loop0 {}/arch/x86_64/airootfs.sfs", at.display())); assert!(!offered(&udisks)); + let v = udisks.snapshot().unwrap().volumes()[0].clone(); + assert_eq!(udisks.look_to_format(&v), Err(DiskError::Other("a file on it is in use (as a loop device)".into()))); // The device the kernel's command line booted from, by UUID, label or path. standin.say("drive Card SD-1"); standin.say("fs mmc1 Card LIVE"); @@ -1391,6 +1591,78 @@ mod tests { assert!(card(&udisks), "another device"); } + #[test] + fn an_erase_that_fails_partway_may_have_erased_it() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + standin.say("drive Stick Kingston-1234"); + standin.say("fs sdb1 Stick PHOTOS"); + let udisks = Udisks::connect_with_limit(&standin.bus.address, Duration::from_millis(1500)).unwrap(); + let photos = udisks.snapshot().unwrap().volumes()[0].clone(); + let mounted = |u: &Udisks| u.snapshot().unwrap().volumes()[0].mount.is_some(); + // A plain failure, and one that times out: maybe erased, and not mounted again. + for (say, timeout) in [("fail Error wiping device: Input/output error", false), ("hang 3000", true)] { + udisks.mount(&photos).unwrap(); + standin.say(say); + let target = udisks.look_to_format(&photos).unwrap(); + let failed = udisks.format(&target, FsKind::Exfat, "X", &mut |_| true).unwrap_err(); + assert_eq!((failed.left, failed.left_unmounted), (Left::MaybeErased, true), "{say}: {failed:?}"); + if timeout { + // The stand-in is still busy with it for a moment. + std::thread::sleep(Duration::from_millis(2000)); + } else { + assert_eq!(failed.error, DiskError::Other("Error wiping device: Input/output error".into())); + } + assert!(!mounted(&udisks), "{say}: not mounted again"); + } + // Busy, as udisks2 says before it begins: nothing was erased, and it's mounted again. + udisks.mount(&photos).unwrap(); + standin.say("fail busy"); + let target = udisks.look_to_format(&photos).unwrap(); + assert_eq!(udisks.format(&target, FsKind::Exfat, "X", &mut |_| true), Err(FormatFailed { error: DiskError::Busy, left: Left::Untouched, left_unmounted: false })); + assert!(mounted(&udisks), "mounted again"); + // Partitioned, then its filesystem couldn't be made. + standin.say("nomkfs"); + let target = udisks.look_to_format(&photos).unwrap(); + let failed = udisks.format(&target, FsKind::Fat32, "X", &mut |_| true).unwrap_err(); + assert_eq!(failed.left, Left::Unformatted, "{failed:?}"); + assert_eq!(standin.asked().iter().filter(|a| a.starts_with("Format")).count(), 4); + } + + #[test] + fn fat32_is_offered_on_an_older_udisks_from_512_mib_of_partition() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + standin.say("drive Stick Kingston-1234"); + standin.say("fs sdb1 Stick SMALL"); + standin.say("version 2.9.5"); + let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let fat32 = |u: &Udisks| { let v = u.snapshot().unwrap().volumes()[0].clone(); u.look_to_format(&v).unwrap().missing.into_iter().find(|(k, _)| *k == FsKind::Fat32).map(|(_, why)| why) }; + // A 514 MiB drive makes a 512 MiB partition; a 513 MiB one, less. + standin.say(&format!("size Stick {}", 514u64 << 20)); + assert_eq!(fat32(&udisks), None); + standin.say(&format!("size Stick {}", 513u64 << 20)); + assert_eq!(fat32(&udisks).as_deref(), Some("needs udisks2 2.10 or newer on a drive under 512 MiB")); + standin.say("version 2.10.1"); + assert_eq!(fat32(&udisks), None, "asked for as FAT32"); + } + + #[test] + fn a_ventoy_style_stick_is_never_formatted() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + let mut standin = StandIn::start(); + standin.say("drive Stick Ventoy-1234"); + standin.say("fs sdb1 Stick Ventoy"); + let sys = crate::testutil::Scratch::new(); + let udisks = Udisks::connect(&standin.bus.address).unwrap().with_sysfs(sys.path().to_path_buf()); + let v = udisks.snapshot().unwrap().volumes()[0].clone(); + assert!(v.formattable); + let dev = udisks.snapshot().unwrap().blocks[&v.block].devnum; + std::fs::create_dir_all(sys.path().join(format!("dev/block/{}:{}/holders/dm-0", rustix::fs::major(dev), rustix::fs::minor(dev)))).unwrap(); + assert!(!udisks.snapshot().unwrap().volumes()[0].formattable); + assert_eq!(udisks.look_to_format(&v), Err(DiskError::Other("another device is built on it, as a live system's can be".into()))); + } + #[test] fn something_else_mounting_it_first_still_says_where_it_is() { assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); From da199521f0de45f98e49a7c1a25ae431995c44e9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Thu, 3 Dec 2026 22:36:33 -0700 Subject: [PATCH 4/4] ALI-2601: Third round of review fixes for formatting a drive - exFAT names are up to 11 UTF-16 code units, as mkfs.exfat 1.4.5 takes (12 fail). Checked on scratch image files against mkfs.exfat, mkfs.fat and mkfs.ext4, in a unit test that's skipped when a tool is missing. - Only udisks2's NotAuthorized* and DeviceBusy error names leave a failed Block.Format untouched. A Failed whose message says busy may have erased the drive. - Fail closed on /sys: a block on the drive with no device number, or whose holders can't be read, refuses it. Any holder but an unlocked partition's own contents refuses it, including bcache and nbd. - Read /proc/cmdline once, as bytes. Ignore by-* names with `..`, and follow links only to devices under /dev. - A disabled Erase and Format looks disabled with the keyboard on it. - A format thread that never runs or panics still clears the drive's busy state. The progress reaches four of four when it's done. - A format lookup that finishes while another dialog is open waits for that dialog to close. - The udisks2 stand-in keeps a /sys of its own; the e2e checks point Gannet at it with GANNET_SYSFS (bench builds only). --- crates/app/src/app.rs | 27 ++- crates/app/src/drives.rs | 59 ++++++- crates/app/src/format_drive.rs | 4 +- crates/app/src/paint.rs | 6 +- crates/core/examples/udisks-standin.rs | 23 ++- crates/core/src/disks.rs | 235 +++++++++++++++++++------ tests/e2e.py | 34 ++-- tests/orca_tour.py | 2 +- 8 files changed, 306 insertions(+), 84 deletions(-) diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 49501a7..1d77be7 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -739,6 +739,9 @@ pub struct App { eject_pressed: Option, /// Drives with something under way, so a second click doesn't start it again. pub drives_busy: Vec, + /// A drive looked at to format while another dialog was open: its dialog opens once that's + /// answered, if the drive's still there. + pending_format: Option, /// The drive being opened, and the folder the window was on then. The window only goes to /// the drive if it's still there, as the user may have gone elsewhere meanwhile. opening: Option<(String, PathBuf)>, @@ -972,6 +975,7 @@ impl App { pin_drag: None, eject_pressed: None, drives_busy: Vec::new(), + pending_format: None, opening: None, edit: Edit::None, menu: None, @@ -3455,6 +3459,12 @@ impl App { if !self.pending_questions.is_empty() { let q = self.pending_questions.remove(0); self.show_asked(q); + } else if self.dialog.is_none() + && let Some(t) = self.pending_format.take() + && self.volumes.iter().any(|v| v.drive == t.drive && v.identity == t.identity) + && !self.drives_busy.contains(&t.drive) + { + self.open_format(t); } } @@ -4084,17 +4094,22 @@ impl App { /// Opens the format dialog, keyboard on Cancel, unless another question is open meanwhile. fn format_looked(&mut self, volume: Volume, result: Result) { match result { - Ok(target) if self.dialog.is_none() && !self.drives_busy.contains(&target.drive) => { - // A paste asked for before mustn't land in its name. - self.edit_gen += 1; - self.dialog = Some(Dialog::Format(Box::new(FormatAsk::new(target)))); - } - Ok(_) | Err(DiskError::Cancelled) => {} + Ok(target) if self.drives_busy.contains(&target.drive) => {} + // Another question came first: this one waits for it. + Ok(target) if self.dialog.is_some() => self.pending_format = Some(target), + Ok(target) => self.open_format(target), + Err(DiskError::Cancelled) => {} Err(e) => self.notice(format!("Couldn't format “{}”: {e}", Self::drive_name(&volume))), } self.invalidate_all(); } + fn open_format(&mut self, target: FormatTarget) { + // A paste asked for before mustn't land in its name. + self.edit_gen += 1; + self.dialog = Some(Dialog::Format(Box::new(FormatAsk::new(target)))); + } + /// Formats the drive, as a job: the window lets go of every folder on it first, and nothing /// else is done to it until it's finished. fn start_format(&mut self, a: FormatAsk, kind: FsKind, label: String) { diff --git a/crates/app/src/drives.rs b/crates/app/src/drives.rs index 72e45e0..98f0219 100644 --- a/crates/app/src/drives.rs +++ b/crates/app/src/drives.rs @@ -51,6 +51,20 @@ impl Doing { } } +/// udisks2 on its own connection. In a bench build, the end-to-end checks can point it at a +/// /sys of their own (`GANNET_SYSFS`), as their stand-in udisks2's devices aren't in the real one. +fn connect(address: &str) -> Result { + Udisks::connect(address).map(seams) +} + +fn seams(u: Udisks) -> Udisks { + #[cfg(feature = "bench")] + if let Some(sys) = std::env::var_os("GANNET_SYSFS") { + return u.with_sysfs(sys.into()); + } + u +} + /// Follows udisks2 on the system bus at `address`, sending `Msg::Volumes` with what's there now, /// and again whenever it changes. Without a system bus it gives up quietly. Without udisks2, its /// drives leave the sidebar, though anything mounted still shows as a mount. @@ -64,7 +78,7 @@ pub fn watch(hub: Hub, address: String) { let tx2 = tx.clone(); let Ok(_following) = bus.follow(rule, move |_| tx.send(()).is_ok()) else { return }; let Ok(_starting) = bus.follow(started, move |_| tx2.send(()).is_ok()) else { return }; - let udisks = Udisks::new(bus); + let udisks = seams(Udisks::new(bus)); let mut sent: Option> = None; loop { match udisks.snapshot() { @@ -97,7 +111,7 @@ pub fn watch(hub: Hub, address: String) { /// an unlock. pub fn act(hub: Hub, address: String, volume: Volume, doing: Doing) { let _ = std::thread::Builder::new().name("gannet-drive".into()).spawn(move || { - let result = Udisks::connect(&address).and_then(|udisks| -> Result, DiskError> { + let result = connect(&address).and_then(|udisks| -> Result, DiskError> { match &doing { Doing::Mount => udisks.mount(&volume).map(Some), Doing::Unlock(passphrase) => udisks.unlock(&volume, passphrase).map(Some), @@ -115,14 +129,42 @@ pub fn act(hub: Hub, address: String, volume: Volume, doing: Doing) { /// can be made. Sends `Msg::FormatLooked`. pub fn look_to_format(hub: Hub, address: String, volume: Volume) { let _ = std::thread::Builder::new().name("gannet-drive".into()).spawn(move || { - let result = Udisks::connect(&address).and_then(|udisks| udisks.look_to_format(&volume)); + let result = connect(&address).and_then(|udisks| udisks.look_to_format(&volume)); hub.send(Msg::FormatLooked { volume, result }); }); } -/// Formats the drive as `kind`, named `label`, keeping `job`'s progress: one step of four as -/// each starts. A stop asked for before the erasing begins stops it. Sends `Msg::FormatDone`. +/// Says a format is over even if its thread never ran or panicked, so the drive isn't left +/// marked busy. It may have got as far as erasing, so that's what's said. +struct FormatDoneGuard { + hub: Hub, + job: u64, + target: Option, + kind: FsKind, +} + +impl FormatDoneGuard { + fn done(mut self, result: Result, disks::FormatFailed>) { + if let Some(target) = self.target.take() { + self.hub.send(Msg::FormatDone { job: self.job, target, kind: self.kind, result }); + } + } +} + +impl Drop for FormatDoneGuard { + fn drop(&mut self) { + if let Some(target) = self.target.take() { + let error = DiskError::Other("formatting stopped unexpectedly".into()); + self.hub.send(Msg::FormatDone { job: self.job, target, kind: self.kind, result: Err(disks::FormatFailed { error, left: disks::Left::MaybeErased, left_unmounted: true }) }); + } + } +} + +/// Formats the drive as `kind`, named `label`, keeping `job`'s progress as steps finished, of +/// four: each step's start means the ones before it are done, and the end, all four. A stop +/// asked for before the erasing begins stops it. Sends `Msg::FormatDone`, always. pub fn format(hub: Hub, address: String, target: FormatTarget, kind: FsKind, label: String, job: Job) { + let guard = FormatDoneGuard { hub: hub.clone(), job: job.id, target: Some(target.clone()), kind }; let _ = std::thread::Builder::new().name("gannet-format".into()).spawn(move || { let p = job.progress.clone(); p.total_items.store(4, Ordering::Relaxed); @@ -131,10 +173,13 @@ pub fn format(hub: Hub, address: String, target: FormatTarget, kind: FsKind, lab hub.send(Msg::Op(gannet_core::ops::Event::Progress(job.id))); !(job.is_cancelled() && s <= FormatStep::Erasing) }; - let result = match Udisks::connect(&address) { + let result = match connect(&address) { Ok(udisks) => udisks.format(&target, kind, &label, &mut step), Err(error) => Err(disks::FormatFailed::before_erasing(error)), }; - hub.send(Msg::FormatDone { job: job.id, target, kind, result }); + if result.is_ok() { + p.done_items.store(4, Ordering::Relaxed); + } + guard.done(result); }); } diff --git a/crates/app/src/format_drive.rs b/crates/app/src/format_drive.rs index 0778a5c..98f453f 100644 --- a/crates/app/src/format_drive.rs +++ b/crates/app/src/format_drive.rs @@ -193,7 +193,9 @@ mod tests { let mut a = FormatAsk::new(target(vec![], vec![])); a.name = Field::new("Holiday photos"); a.check(); - assert_eq!(a.ready(), Some((FsKind::Exfat, "Holiday photos".into()))); + assert_eq!(a.name.error.as_deref(), Some("exFAT allows 11 characters. This has 14.")); + a.pick(FsKind::Ext4); + assert_eq!(a.ready(), Some((FsKind::Ext4, "Holiday photos".into())), "fits ext4's 16 bytes"); a.pick(FsKind::Fat32); assert_eq!(a.name.error.as_deref(), Some("FAT32 allows 11 characters. This has 14.")); assert_eq!(a.ready(), None); diff --git a/crates/app/src/paint.rs b/crates/app/src/paint.rs index 9be5d4b..bb89dcd 100644 --- a/crates/app/src/paint.rs +++ b/crates/app/src/paint.rs @@ -791,7 +791,7 @@ impl App { self.paint_format_dialog(c, a); // Only a button with the keyboard shows as focused: Enter presses none otherwise. let at = if let FormatStop::Button(i) = a.focus { i } else { usize::MAX }; - self.paint_dialog_buttons(c, &d, at, a.ready().is_none() && at != crate::format_drive::ERASE); + self.paint_dialog_buttons(c, &d, at, a.ready().is_none()); self.dialog = Some(d); return; } @@ -973,6 +973,10 @@ impl App { let w = self.text.measure(&b.label); let by = self.baseline(br.y, br.h); self.text.draw_str(c, &b.label, br.x as f32 + (br.w as f32 - w) / 2.0, by, fg); + // One that can't be pressed still shows it has the keyboard, with the outline alone. + if off && i == at { + c.frame(*br, self.px(size::FOCUS_OUTLINE).max(1), co.accent_mark); + } } } diff --git a/crates/core/examples/udisks-standin.rs b/crates/core/examples/udisks-standin.rs index 484a6a3..56b1cf6 100644 --- a/crates/core/examples/udisks-standin.rs +++ b/crates/core/examples/udisks-standin.rs @@ -31,7 +31,10 @@ //! nomkfs the next CreatePartitionAndFormat makes the partition, then fails to //! make its filesystem, as with mkfs missing //! -//! Each block's device number is made from its path, for a check's own /sys to name. +//! holder NAME HOLDER a kernel device, like dm-0, built on NAME, as /sys says +//! +//! Each block's device number is made from its path. A /sys of the stand-in's own, at ROOT/.sys, +//! has `dev/block/MAJ:MIN/holders` for each block it serves, for the checks to point Gannet at. //! asked each Format and CreatePartitionAndFormat asked for, a line each //! starting `asked `, before the `ok` //! @@ -136,6 +139,14 @@ fn devnum(at: &str) -> u64 { rustix::fs::makedev(8, minor) } +/// The block's holders folder in the stand-in's own /sys, made if it isn't there. +fn holders_dir(root: &Path, at: &str) -> PathBuf { + let n = devnum(at); + let dir = root.join(format!(".sys/dev/block/{}:{}/holders", rustix::fs::major(n), rustix::fs::minor(n))); + let _ = std::fs::create_dir_all(&dir); + dir +} + fn path(kind: &str, name: &str) -> String { format!("{ROOT}/{kind}/{name}") } @@ -385,6 +396,7 @@ impl EncryptedIface { inside }; let server = conn.object_server(); + holders_dir(&self.state.lock().unwrap().root.clone(), &inside); server.at(inside.as_str(), BlockIface { at: inside.clone(), state: self.state.clone() }).await?; server.at(inside.as_str(), FilesystemIface { at: inside.clone(), state: self.state.clone() }).await?; changed(conn, &self.at, "Encrypted").await; @@ -486,10 +498,12 @@ impl TableIface { let (made, nomkfs) = made; let server = conn.object_server(); if nomkfs { - server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; + holders_dir(&self.state.lock().unwrap().root.clone(), &made); + server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; server.at(made.as_str(), PartitionIface { at: made.clone(), state: self.state.clone() }).await?; return Err(UdError::Failed("Error creating file system 'vfat': Executable mkfs.vfat not found".into())); } + holders_dir(&self.state.lock().unwrap().root.clone(), &made); server.at(made.as_str(), BlockIface { at: made.clone(), state: self.state.clone() }).await?; server.at(made.as_str(), FilesystemIface { at: made.clone(), state: self.state.clone() }).await?; server.at(made.as_str(), PartitionIface { at: made.clone(), state: self.state.clone() }).await?; @@ -518,6 +532,7 @@ impl ManagerIface { /// Serves a block's interfaces, as its state says it has. fn serve_block(conn: &Connection, state: &Shared, at: &str) { + holders_dir(&state.lock().unwrap().root, at); let (fs, luks, table, partition, looped) = { let s = state.lock().unwrap(); let b = &s.blocks[at]; @@ -611,6 +626,10 @@ fn command(conn: &Connection, state: &Shared, line: &str) -> Result<(), String> ["fail", why @ ..] if !why.is_empty() => state.lock().unwrap().fail = Some(why.join(" ")), ["hang", ms] => state.lock().unwrap().hang = Some(std::time::Duration::from_millis(ms.parse().map_err(|_| "not a number")?)), ["nomkfs"] => state.lock().unwrap().nomkfs = true, + ["holder", name, holder] => { + let root = state.lock().unwrap().root.clone(); + std::fs::create_dir_all(holders_dir(&root, &path("block_devices", name)).join(holder)).map_err(|e| e.to_string())?; + } ["size", drive, bytes] => state.lock().unwrap().drives.get_mut(&path("drives", drive)).ok_or("no such drive")?.size = Some(bytes.parse().map_err(|_| "not a number")?), ["slow", name, ms] => state.lock().unwrap().blocks.get_mut(&path("block_devices", name)).ok_or("no such block")?.slow = Some(std::time::Duration::from_millis(ms.parse().map_err(|_| "not a number")?)), ["swap", drive] => state.lock().unwrap().drives.get_mut(&path("drives", drive)).ok_or("no such drive")?.media_detected += 1, diff --git a/crates/core/src/disks.rs b/crates/core/src/disks.rs index 71138fe..08d159e 100644 --- a/crates/core/src/disks.rs +++ b/crates/core/src/disks.rs @@ -101,8 +101,9 @@ pub struct Snapshot { /// `UUID=…`, `LABEL=…`, `PARTUUID=…`, `PARTLABEL=…` or a path. See [`boot_devices`]. pub boot: Vec, /// For each block on a drive, the kernel devices built on it (its holders in /sys), like - /// `dm-0`, `loop3` or `md127`. See [`holders_of`]. - pub holders: BTreeMap>, + /// `dm-0`, `loop3` or `md127`, or `None` where that couldn't be read. The whole map is `None` + /// until /sys has been asked (`Udisks::snapshot` does). See [`holders_of`]. + pub holders: Option>>>, } /// What makes a drive the one that was picked, more than its path does. @@ -347,19 +348,18 @@ impl Snapshot { } /// Why another kernel device built on one of `blocks` stops it being formatted, if one does: - /// a RAID set, or a device-mapper or loop device, as a live system like Ventoy runs from - /// without mounting the stick. The unlocked contents of an encrypted partition, as udisks2 - /// reports them, are fine: they're locked first. + /// a RAID set, or anything else, like a device-mapper, loop, bcache or nbd device, as a live + /// system like Ventoy runs from without mounting the stick. The unlocked contents of an + /// encrypted partition, as udisks2 reports them, are fine: they're locked first. Once /sys + /// has been asked, a block on the drive it couldn't say about (or with no device number) + /// refuses it too: it fails closed. fn built_on(&self, blocks: &[&Block]) -> Option<&'static str> { - for b in blocks { + let held = self.holders.as_ref()?; + for b in blocks.iter().filter(|b| self.drives.contains_key(&b.drive)) { + let Some(Some(holders)) = held.get(&b.path) else { return Some("can't tell what's built on it") }; let cleartext = b.encrypted.clone().flatten().and_then(|c| self.blocks.get(&c)).and_then(|c| c.device.as_ref()).and_then(|d| d.file_name()).map(|n| n.to_string_lossy().into_owned()); - for h in self.holders.get(&b.path).into_iter().flatten() { - if h.starts_with("md") { - return Some("it's part of a RAID or LVM set"); - } - if (h.starts_with("dm-") || h.starts_with("loop")) && cleartext.as_deref() != Some(h.as_str()) { - return Some("another device is built on it, as a live system's can be"); - } + if let Some(h) = holders.iter().find(|h| cleartext.as_deref() != Some(h.as_str())) { + return Some(if h.starts_with("md") { "it's part of a RAID or LVM set" } else { "another device is built on it, as a live system's can be" }); } } None @@ -437,6 +437,8 @@ pub fn boot_devices(cmdline: &str, resolve: impl Fn(&std::path::Path) -> Option< "root" | "archisodevice" => match value.split_once('=') { Some(("CDLABEL" | "LABEL", l)) => format!("LABEL={}", unescape(l)), Some((k @ ("UUID" | "PARTUUID" | "PARTLABEL"), v)) => format!("{k}={}", unescape(v)), + // A link name with `..` in it could lead anywhere: it names nothing. + _ if value.split('/').any(|c| c == "..") => continue, _ => match value.strip_prefix("/dev/disk/by-").and_then(|by| by.split_once('/')) { Some(("uuid", v)) => format!("UUID={v}"), Some(("label", v)) => format!("LABEL={}", unescape(v)), @@ -460,12 +462,29 @@ pub fn boot_devices(cmdline: &str, resolve: impl Fn(&std::path::Path) -> Option< } /// The kernel devices built on the block device `devnum`, by name, from `sysfs`'s -/// `dev/block/MAJ:MIN/holders`. Nothing if it can't be read. -pub fn holders_of(sysfs: &std::path::Path, devnum: u64) -> Vec { +/// `dev/block/MAJ:MIN/holders`, or `None` if that can't be read or there's no device number. +pub fn holders_of(sysfs: &std::path::Path, devnum: u64) -> Option> { + if devnum == 0 { + return None; + } let dir = sysfs.join(format!("dev/block/{}:{}/holders", rustix::fs::major(devnum), rustix::fs::minor(devnum))); - let mut out: Vec = std::fs::read_dir(dir).map(|d| d.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + let mut out = Vec::new(); + for e in std::fs::read_dir(dir).ok()? { + out.push(e.ok()?.file_name().to_string_lossy().into_owned()); + } out.sort(); - out + Some(out) +} + +/// The kernel's command line, read once: it doesn't change while the system runs. +fn proc_cmdline() -> &'static str { + static CMDLINE: std::sync::OnceLock = std::sync::OnceLock::new(); + CMDLINE.get_or_init(|| String::from_utf8_lossy(&std::fs::read("/proc/cmdline").unwrap_or_default()).into_owned()) +} + +/// Where a `/dev/disk/by-*` link leads, when that's a device under /dev. +fn resolve_dev(p: &std::path::Path) -> Option { + std::fs::canonicalize(p).ok().filter(|to| to.starts_with("/dev/")) } /// Where the running system's own filesystems are mounted. A drive with one of them mounted from @@ -518,7 +537,7 @@ impl FsKind { /// What its names can be, in a few words, for under the name field. pub fn label_rule(self) -> &'static str { match self { - FsKind::Exfat => "Up to 15 characters, with no space at either end.", + FsKind::Exfat => "Up to 11 characters (emoji count as 2), with no space at either end.", FsKind::Fat32 => "Up to 11 of A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~, with no space at either end. Kept in capitals.", FsKind::Ext4 => "Up to 16 bytes, with no space at either end. Accented letters take 2 or more.", } @@ -538,9 +557,10 @@ impl FsKind { } match self { FsKind::Exfat => { + // mkfs.exfat takes 11 UTF-16 code units, as the volume label's entry holds. let n = typed.encode_utf16().count(); - if n > 15 { - return Err(format!("exFAT allows 15 characters. This has {n}.")); + if n > 11 { + return Err(format!("exFAT allows 11 characters. This has {n}.")); } Ok(typed.to_string()) } @@ -717,6 +737,14 @@ fn disk_error(e: zbus::Error, unlocking: bool) -> DiskError { } } +/// Whether udisks2 refused a call before doing anything: polkit said no, or the device was busy. +/// Told by the error's name only, never its message. +fn refused_before_starting(e: &zbus::Error) -> bool { + let zbus::Error::MethodError(name, ..) = e else { return false }; + let name = name.as_str(); + name.starts_with("org.freedesktop.UDisks2.Error.NotAuthorized") || name == "org.freedesktop.UDisks2.Error.DeviceBusy" +} + /// Options for each call: polkit may ask the user, rather than just saying no. fn options() -> HashMap<&'static str, Variant<'static>> { HashMap::from([("auth.no_user_interaction", Variant::from(false))]) @@ -771,9 +799,13 @@ impl Udisks { pub fn snapshot(&self) -> Result { let objects: Objects = self.bus.call(SERVICE, ROOT, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", &()).map_err(|e| disk_error(e, false))?; let mut s = Snapshot::from_objects(&objects); - s.boot = boot_devices(&std::fs::read_to_string(&self.cmdline).unwrap_or_default(), |p| std::fs::canonicalize(p).ok()); + let cmdline = match self.cmdline.as_path() { + p if p == std::path::Path::new("/proc/cmdline") => proc_cmdline().to_string(), + p => String::from_utf8_lossy(&std::fs::read(p).unwrap_or_default()).into_owned(), + }; + s.boot = boot_devices(&cmdline, resolve_dev); // Only blocks on a drive, a handful, and only when udisks2 says something changed. - s.holders = s.blocks.values().filter(|b| b.drive != NONE && !b.drive.is_empty() && b.devnum != 0).map(|b| (b.path.clone(), holders_of(&self.sysfs, b.devnum))).filter(|(_, h)| !h.is_empty()).collect(); + s.holders = Some(s.blocks.values().filter(|b| s.drives.contains_key(&b.drive)).map(|b| (b.path.clone(), holders_of(&self.sysfs, b.devnum))).collect()); Ok(s) } @@ -1016,12 +1048,14 @@ impl Udisks { if !step(FormatStep::Erasing) { return Err(undo(DiskError::Cancelled)); } - // Only a refusal before it begins (polkit, or the drive busy) leaves it untouched. Any - // other failure, like a timeout or the drive going, can come partway through. - self.call::<()>(&target.whole, "Block", "Format", &("gpt", options()), false).map_err(|e| match e { - DiskError::Cancelled | DiskError::NotAuthorized | DiskError::Busy => undo(e), - error => FormatFailed { error, left: Left::MaybeErased, left_unmounted: true }, - })?; + // Only udisks2's own refusals before it begins, by their error names (polkit's + // NotAuthorized*, or DeviceBusy), leave it untouched. Any other failure, like a timeout, + // the drive going, or a plain Failed whatever its message says, can come partway through. + if let Err(e) = self.bus.call::<_, ()>(SERVICE, &target.whole, &format!("{PREFIX}Block"), "Format", &("gpt", options())) { + let untouched = refused_before_starting(&e); + let error = disk_error(e, false); + return Err(if untouched { undo(error) } else { FormatFailed { error, left: Left::MaybeErased, left_unmounted: true } }); + } step(FormatStep::Making); let mut made = options(); made.insert("label", Variant::from(label.to_string())); @@ -1231,6 +1265,14 @@ mod tests { // by-id and by-path links are followed to their device. let resolve = |p: &std::path::Path| (p == std::path::Path::new("/dev/disk/by-id/usb-SanDisk_Ultra-0:0-part1")).then(|| PathBuf::from("/dev/sdb1")); assert_eq!(boot_devices("root=/dev/disk/by-id/usb-SanDisk_Ultra-0:0-part1 archisodevice=/dev/disk/by-path/x", resolve), ["/dev/sdb1", "/dev/disk/by-path/x"]); + // A link name with `..` names nothing, and a link is only taken to a device under /dev. + let anywhere = |_: &std::path::Path| Some(PathBuf::from("/dev/sdb1")); + assert!(boot_devices("root=/dev/disk/by-id/../../sdb1 archisodevice=/dev/disk/by-label/x/..", anywhere).is_empty()); + let scratch = crate::testutil::Scratch::new(); + std::os::unix::fs::symlink("/dev/null", scratch.path().join("to-dev")).unwrap(); + std::os::unix::fs::symlink(scratch.path(), scratch.path().join("elsewhere")).unwrap(); + assert_eq!(resolve_dev(&scratch.path().join("to-dev")), Some(PathBuf::from("/dev/null"))); + assert_eq!(resolve_dev(&scratch.path().join("elsewhere")), None); // Matched against the blocks on a drive. let mut s = Snapshot::from_objects(&machine(false)); let stick = format!("{ROOT}/drives/Stick"); @@ -1253,8 +1295,11 @@ mod tests { let dev = rustix::fs::makedev(8, 17); std::fs::create_dir_all(sys.path().join("dev/block/8:17/holders/dm-3")).unwrap(); std::fs::create_dir_all(sys.path().join("dev/block/8:17/holders/loop0")).unwrap(); - assert_eq!(holders_of(sys.path(), dev), ["dm-3", "loop0"]); - assert!(holders_of(sys.path(), rustix::fs::makedev(8, 18)).is_empty(), "none"); + std::fs::create_dir_all(sys.path().join("dev/block/8:18/holders")).unwrap(); + assert_eq!(holders_of(sys.path(), dev), Some(vec!["dm-3".to_string(), "loop0".to_string()])); + assert_eq!(holders_of(sys.path(), rustix::fs::makedev(8, 18)), Some(vec![]), "none"); + assert_eq!(holders_of(sys.path(), rustix::fs::makedev(8, 19)), None, "can't be read"); + assert_eq!(holders_of(sys.path(), 0), None, "no device number"); let stick = format!("{ROOT}/drives/Stick"); let sdb1 = format!("{ROOT}/block_devices/sdb1"); let refusal = |unlocked: bool, holder: &str, on: &str| { @@ -1262,9 +1307,26 @@ mod tests { if unlocked { s.blocks.get_mut(&format!("{ROOT}/block_devices/dm_2d1")).unwrap().device = Some("/dev/dm-0".into()); } - s.holders.insert(on.to_string(), vec![holder.to_string()]); + // Every block on the stick read, with nothing built on it but `holder` on `on`. + let mut held: BTreeMap>> = s.blocks.values().filter(|b| b.drive == stick).map(|b| (b.path.clone(), Some(vec![]))).collect(); + if !holder.is_empty() { + held.insert(on.to_string(), Some(vec![holder.to_string()])); + } + s.holders = Some(held); s.format_refusal(&stick) }; + assert_eq!(refusal(false, "", ""), None, "nothing built on it"); + assert_eq!(refusal(false, "bcache0", &sdb1), Some("another device is built on it, as a live system's can be")); + assert_eq!(refusal(false, "nbd0", &sdb1), Some("another device is built on it, as a live system's can be")); + // Fails closed: a block on the stick /sys couldn't say about refuses it. + let mut s = Snapshot::from_objects(&machine(false)); + let mut held: BTreeMap>> = s.blocks.values().filter(|b| b.drive == stick).map(|b| (b.path.clone(), Some(vec![]))).collect(); + held.insert(sdb1.clone(), None); + s.holders = Some(held.clone()); + assert_eq!(s.format_refusal(&stick), Some("can't tell what's built on it")); + held.remove(&sdb1); + s.holders = Some(held); + assert_eq!(s.format_refusal(&stick), Some("can't tell what's built on it"), "nor one it wasn't asked about"); // Ventoy's device-mapper device over a partition that isn't mounted. assert_eq!(refusal(false, "dm-3", &format!("{ROOT}/block_devices/sdb3")), Some("another device is built on it, as a live system's can be")); assert_eq!(refusal(false, "loop0", &sdb1), Some("another device is built on it, as a live system's can be")); @@ -1276,11 +1338,65 @@ mod tests { assert_eq!(refusal(true, "dm-5", &format!("{ROOT}/block_devices/sdb2")), Some("another device is built on it, as a live system's can be"), "another one isn't"); } + /// The longest names `FsKind::label` takes are what the real mkfs tools take, and one more + /// is refused by both, checked on image files in a scratch folder, never a device. A tool + /// that isn't installed is skipped. + #[test] + fn name_limits_are_what_mkfs_takes() { + assert!(std::env::var_os("GANNET_TEST_SANDBOX").is_some(), "run tests with scripts/test.sh"); + use std::process::Command; + let scratch = crate::testutil::Scratch::new(); + let image = |name: &str, size: u64| { + let p = scratch.path().join(name); + std::fs::File::create(&p).unwrap().set_len(size).unwrap(); + p + }; + let ok = |tool: &str, args: &[&str], img: &std::path::Path| Command::new(tool).args(args).arg(img).output().is_ok_and(|o| o.status.success()); + let read = |tool: &str, img: &std::path::Path| Command::new(tool).arg(img).output().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_default(); + if std::path::Path::new("/usr/bin/mkfs.exfat").exists() { + let img = image("exfat.img", 64 << 20); + for (fits, longer) in [("ABCDEFGHIJK", "ABCDEFGHIJKL"), ("ÉÉÉÉÉÉÉÉÉÉÉ", "ÉÉÉÉÉÉÉÉÉÉÉÉ"), ("😀😀😀😀😀", "😀😀😀😀😀😀")] { + let name = FsKind::Exfat.label(fits).unwrap(); + assert!(ok("/usr/bin/mkfs.exfat", &["-L", &name], &img), "{fits}"); + assert!(read("/usr/bin/exfatlabel", &img).ends_with(&name), "{fits}: {}", read("/usr/bin/exfatlabel", &img)); + assert!(FsKind::Exfat.label(longer).is_err() && !ok("/usr/bin/mkfs.exfat", &["-L", longer], &img), "{longer}"); + } + } + if std::path::Path::new("/usr/bin/mkfs.fat").exists() { + let img = image("fat.img", 600 << 20); + for fits in ["ABCDEFGHIJK", "my-cam_(2)!", "A#$%&'@^`{}", "A ~ B"] { + let name = FsKind::Fat32.label(fits).unwrap(); + assert!(ok("/usr/bin/mkfs.fat", &["-F", "32", "-n", &name], &img), "{fits}"); + assert_eq!(read("/usr/bin/fatlabel", &img), name); + } + for longer in ["ABCDEFGHIJKL", "A.B", "A+B", "é"] { + assert!(FsKind::Fat32.label(longer).is_err() && !ok("/usr/bin/mkfs.fat", &["-F", "32", "-n", longer], &img), "{longer}"); + } + // mkfs.fat takes NO NAME, but writes it as no name at all. + assert!(FsKind::Fat32.label("NO NAME").is_err() && ok("/usr/bin/mkfs.fat", &["-F", "32", "-n", "NO NAME"], &img)); + assert_eq!(read("/usr/bin/fatlabel", &img), ""); + } + if std::path::Path::new("/usr/bin/mkfs.ext4").exists() { + let img = image("ext4.img", 64 << 20); + for (fits, longer) in [("ABCDEFGHIJKLMNOP", "ABCDEFGHIJKLMNOPQ"), ("éééééééé", "éééééééééa")] { + let name = FsKind::Ext4.label(fits).unwrap(); + assert!(ok("/usr/bin/mkfs.ext4", &["-q", "-F", "-L", &name], &img), "{fits}"); + assert_eq!(read("/usr/bin/e2label", &img), name); + // mkfs.ext4 cuts a longer one short rather than failing: refused here instead. + assert!(FsKind::Ext4.label(longer).is_err(), "{longer}"); + assert!(ok("/usr/bin/mkfs.ext4", &["-q", "-F", "-L", longer], &img)); + assert_ne!(read("/usr/bin/e2label", &img), longer, "cut short"); + } + } + } + #[test] fn names_fit_the_format() { - assert_eq!(FsKind::Exfat.label("Holiday photos"), Ok("Holiday photos".into())); - assert_eq!(FsKind::Exfat.label("Fotos de férias!"), Err("exFAT allows 15 characters. This has 16.".into())); - assert_eq!(FsKind::Exfat.label("Fotos de féria"), Ok("Fotos de féria".into()), "characters, not bytes"); + assert_eq!(FsKind::Exfat.label("Holiday 26"), Ok("Holiday 26".into())); + assert_eq!(FsKind::Exfat.label("Holiday photos"), Err("exFAT allows 11 characters. This has 14.".into())); + assert_eq!(FsKind::Exfat.label("😀😀😀😀😀😀"), Err("exFAT allows 11 characters. This has 12.".into()), "emoji count as 2"); + assert_eq!(FsKind::Exfat.label("Fotos férias"), Err("exFAT allows 11 characters. This has 12.".into())); + assert_eq!(FsKind::Exfat.label("Fotos féria"), Ok("Fotos féria".into()), "characters, not bytes"); assert_eq!(FsKind::Fat32.label("photos 2026"), Ok("PHOTOS 2026".into()), "in capitals"); assert_eq!(FsKind::Fat32.label("photos 20266"), Err("FAT32 allows 11 characters. This has 12.".into())); assert_eq!(FsKind::Fat32.label("fotos.old"), Err("FAT32 names can't have “.”. Use A–Z, 0–9, spaces and ! # $ % & ' ( ) - @ ^ _ ` { } ~".into())); @@ -1352,6 +1468,11 @@ mod tests { assert_eq!(line.trim(), "ok", "{command}"); } + /// udisks2 through it, reading the stand-in's own /sys. + fn udisks(&self) -> Udisks { + Udisks::connect(&self.bus.address).unwrap().with_sysfs(self.root.path().join(".sys")) + } + /// The formatting calls it was asked to make. fn asked(&mut self) -> Vec { use std::io::{BufRead, Write}; @@ -1383,7 +1504,7 @@ mod tests { standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick PHOTOS"); standin.say("luks sdb2 Stick hunter2 SECRETS"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); let volumes = udisks.snapshot().unwrap().volumes(); let labels: Vec<(Option<&str>, bool)> = volumes.iter().map(|v| (v.label.as_deref(), v.locked)).collect(); assert_eq!(labels, [(Some("PHOTOS"), false), (None, true)]); @@ -1438,7 +1559,7 @@ mod tests { standin.say("model Stick SanDisk Ultra"); standin.say("fs sdb1 Stick PHOTOS"); standin.say("luks sdb2 Stick hunter2 SECRETS"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); let photos = udisks.snapshot().unwrap().volumes()[0].clone(); assert!(photos.formattable); udisks.mount(&photos).unwrap(); @@ -1513,9 +1634,9 @@ mod tests { } /// The format in a thread of its own, so the stand-in can be told things while it unmounts. - fn format_meanwhile(address: &str, target: FormatTarget) -> std::thread::JoinHandle, FormatFailed>> { - let address = address.to_string(); - std::thread::spawn(move || Udisks::connect(&address).unwrap().format(&target, FsKind::Exfat, "X", &mut |_| true)) + fn format_meanwhile(standin: &StandIn, target: FormatTarget) -> std::thread::JoinHandle, FormatFailed>> { + let (address, sys) = (standin.bus.address.clone(), standin.root.path().join(".sys")); + std::thread::spawn(move || Udisks::connect(&address).unwrap().with_sysfs(sys).format(&target, FsKind::Exfat, "X", &mut |_| true)) } #[test] @@ -1525,13 +1646,13 @@ mod tests { standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick PHOTOS"); standin.say("fs sdb2 Stick OTHER"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); let photos = udisks.snapshot().unwrap().volumes().into_iter().find(|v| v.label.as_deref() == Some("PHOTOS")).unwrap(); udisks.mount(&photos).unwrap(); // The system mounted from it while it unmounts. standin.say("slow sdb1 600"); let target = udisks.look_to_format(&photos).unwrap(); - let formatting = format_meanwhile(&standin.bus.address, target.clone()); + let formatting = format_meanwhile(&standin, target.clone()); std::thread::sleep(Duration::from_millis(200)); standin.say("at sdb2 /boot"); let failed = formatting.join().unwrap().unwrap_err(); @@ -1545,7 +1666,7 @@ mod tests { udisks.mount(&card).unwrap(); standin.say("slow mmc1 600"); let target = udisks.look_to_format(&card).unwrap(); - let formatting = format_meanwhile(&standin.bus.address, target); + let formatting = format_meanwhile(&standin, target); std::thread::sleep(Duration::from_millis(200)); standin.say("swap Card"); assert_eq!(formatting.join().unwrap().unwrap_err(), FormatFailed { error: DiskError::Changed, left: Left::Untouched, left_unmounted: true }); @@ -1561,7 +1682,7 @@ mod tests { std::fs::write(&cmdline, "BOOT_IMAGE=/vmlinuz quiet\n").unwrap(); standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick ARCH_202601"); - let udisks = Udisks::connect(&standin.bus.address).unwrap().with_cmdline(cmdline.clone()); + let udisks = standin.udisks().with_cmdline(cmdline.clone()); let offered = |u: &Udisks| u.snapshot().unwrap().volumes()[0].formattable; assert!(offered(&udisks)); // Mounted where a live system mounts its medium. @@ -1597,7 +1718,7 @@ mod tests { let mut standin = StandIn::start(); standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick PHOTOS"); - let udisks = Udisks::connect_with_limit(&standin.bus.address, Duration::from_millis(1500)).unwrap(); + let udisks = Udisks::connect_with_limit(&standin.bus.address, Duration::from_millis(1500)).unwrap().with_sysfs(standin.root.path().join(".sys")); let photos = udisks.snapshot().unwrap().volumes()[0].clone(); let mounted = |u: &Udisks| u.snapshot().unwrap().volumes()[0].mount.is_some(); // A plain failure, and one that times out: maybe erased, and not mounted again. @@ -1615,7 +1736,14 @@ mod tests { } assert!(!mounted(&udisks), "{say}: not mounted again"); } - // Busy, as udisks2 says before it begins: nothing was erased, and it's mounted again. + // Failed, saying it's busy: told by the message only, so it may have been erased. + udisks.mount(&photos).unwrap(); + standin.say("fail Error wiping device: device is busy"); + let target = udisks.look_to_format(&photos).unwrap(); + let failed = udisks.format(&target, FsKind::Exfat, "X", &mut |_| true).unwrap_err(); + assert_eq!((failed.error.clone(), failed.left, failed.left_unmounted), (DiskError::Busy, Left::MaybeErased, true), "{failed:?}"); + assert!(!mounted(&udisks), "not mounted again"); + // DeviceBusy, udisks2's own refusal before it begins: nothing erased, mounted again. udisks.mount(&photos).unwrap(); standin.say("fail busy"); let target = udisks.look_to_format(&photos).unwrap(); @@ -1626,7 +1754,7 @@ mod tests { let target = udisks.look_to_format(&photos).unwrap(); let failed = udisks.format(&target, FsKind::Fat32, "X", &mut |_| true).unwrap_err(); assert_eq!(failed.left, Left::Unformatted, "{failed:?}"); - assert_eq!(standin.asked().iter().filter(|a| a.starts_with("Format")).count(), 4); + assert_eq!(standin.asked().iter().filter(|a| a.starts_with("Format")).count(), 5); } #[test] @@ -1636,7 +1764,7 @@ mod tests { standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick SMALL"); standin.say("version 2.9.5"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); let fat32 = |u: &Udisks| { let v = u.snapshot().unwrap().volumes()[0].clone(); u.look_to_format(&v).unwrap().missing.into_iter().find(|(k, _)| *k == FsKind::Fat32).map(|(_, why)| why) }; // A 514 MiB drive makes a 512 MiB partition; a 513 MiB one, less. standin.say(&format!("size Stick {}", 514u64 << 20)); @@ -1653,14 +1781,15 @@ mod tests { let mut standin = StandIn::start(); standin.say("drive Stick Ventoy-1234"); standin.say("fs sdb1 Stick Ventoy"); - let sys = crate::testutil::Scratch::new(); - let udisks = Udisks::connect(&standin.bus.address).unwrap().with_sysfs(sys.path().to_path_buf()); + let udisks = standin.udisks(); let v = udisks.snapshot().unwrap().volumes()[0].clone(); assert!(v.formattable); - let dev = udisks.snapshot().unwrap().blocks[&v.block].devnum; - std::fs::create_dir_all(sys.path().join(format!("dev/block/{}:{}/holders/dm-0", rustix::fs::major(dev), rustix::fs::minor(dev)))).unwrap(); + standin.say("holder sdb1 dm-0"); assert!(!udisks.snapshot().unwrap().volumes()[0].formattable); assert_eq!(udisks.look_to_format(&v), Err(DiskError::Other("another device is built on it, as a live system's can be".into()))); + // With a /sys that doesn't know the stick's devices, it's refused rather than guessed at. + let blind = Udisks::connect(&standin.bus.address).unwrap().with_sysfs(standin.root.path().join("nowhere")); + assert!(!blind.snapshot().unwrap().volumes()[0].formattable); } #[test] @@ -1669,7 +1798,7 @@ mod tests { let mut standin = StandIn::start(); standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick PHOTOS"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); // An automounter gets there between the look and the mount. standin.say("mount sdb1"); let at = udisks.mount_block(&format!("{ROOT}/block_devices/sdb1")).unwrap(); @@ -1682,7 +1811,7 @@ mod tests { let mut standin = StandIn::start(); standin.say("drive Stick Kingston-1234"); standin.say("fs sdb1 Stick PHOTOS"); - let udisks = Udisks::connect(&standin.bus.address).unwrap(); + let udisks = standin.udisks(); let picked = udisks.snapshot().unwrap().volumes()[0].clone(); standin.say("unplug Stick"); std::thread::sleep(Duration::from_millis(100)); diff --git a/tests/e2e.py b/tests/e2e.py index c846d08..ba4dab1 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -1561,6 +1561,11 @@ def say(self, *lines): answer = self.proc.stdout.readline().strip() assert answer == "ok", f"{line}: {answer}" + @property + def env(self): + """The app's environment for it: its bus, and its own /sys for what's built on its drives.""" + return {"DBUS_SYSTEM_BUS_ADDRESS": self.bus.address, "GANNET_SYSFS": str(self.root / ".sys")} + def asked(self): """The formatting calls the stand-in was asked to make, oldest first.""" self.proc.stdin.write("asked\n") @@ -1616,7 +1621,7 @@ def drives_mount_unlock_and_eject_from_the_sidebar(h): disks = StandIn(media) try: disks.say("drive Stick Kingston-1234", "fs sdb1 Stick PHOTOS", "luks sdb2 Stick hunter2 SECRETS") - a = App(h, fs, extra_env={"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address}) + a = App(h, fs, extra_env={**disks.env}) s = a.wait(lambda s: place_flags(s, "PHOTOS") == {"eject"} and place_flags(s, "8.0 GB Volume") == {"locked", "eject"}, "both volumes, not mounted yet") a.shot("drives-sidebar") # A click mounts it and opens it. @@ -1708,11 +1713,13 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): disks.say("drive Sys SYS-1", "fs sys1 Sys SYSDATA", "fs sys2 Sys HIDDEN", "system sys2") # And the stick a live system is running from. disks.say("drive Live LIVE-1", "fs live1 Live LIVEDATA", "fs live2 Live LIVEBOOT", "at live2 /run/archiso/bootmnt") - env = {"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address} + # And one a device-mapper device is built on, as Ventoy's is. + disks.say("drive Vent VENT-1", "fs vent1 Vent VENTOY", "holder vent1 dm-0") + env = {**disks.env} a = App(h, fs, extra_env=env) - s = a.wait(lambda s: all(place_flags(s, l) is not None for l in ("ARCH_202512", "ARCHISO_EF1", "DATA", "CARDDATA", "SYSDATA", "LIVEDATA")), "the drives") + s = a.wait(lambda s: all(place_flags(s, l) is not None for l in ("ARCH_202512", "ARCHISO_EF1", "DATA", "CARDDATA", "SYSDATA", "LIVEDATA", "VENTOY")), "the drives") assert s["base"] == 0xfafafa, "light" - for label in ("DATA", "CARDDATA", "SYSDATA", "LIVEDATA"): + for label in ("DATA", "CARDDATA", "SYSDATA", "LIVEDATA", "VENTOY"): a.click(60, place_y(s, label), 0x111) items = a.wait(lambda s: s["menu"], f"{label}'s menu")["menu_items"] assert "Format…" not in items, f"{label}: {items}" @@ -1729,7 +1736,7 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): assert f["title"] == "Format “SanDisk Ultra, 16.0 GB”?", f assert re.fullmatch(r"Everything on “SanDisk Ultra, 16.0 GB” will be erased: the “ARCH_202512” partition, with [0-9.]+ [kMGT]?B of files, and the 8\.0 GB “ARCHISO_EF1” partition\. This can't be undone\.", f["warning"]), f["warning"] assert (f["focus"], f["kind"], f["name"], f["ready"]) == ("Button(1)", "exFAT", "", True), f - assert f["line"] == "Up to 15 characters, with no space at either end.", f + assert f["line"] == "Up to 11 characters (emoji count as 2), with no space at either end.", f assert [k[0] for k in f["kinds"]] == ["exFAT", "FAT32", "ext4"] and all(k[1] for k in f["kinds"]), f["kinds"] a.shot("format-dialog-light") # Enter on Cancel cancels. @@ -1782,12 +1789,13 @@ def a_removable_drive_is_formatted_from_the_sidebar(h): s = a.wait(lambda s: s["format"]["kind"] == "ext4" and not s["format"]["error"], "fits ext4") assert s["format"]["line"].startswith("Up to 16 bytes"), s["format"] a.key("Down") - a.wait(lambda s: s["format"]["kind"] == "exFAT" and s["format"]["ready"], "fits exFAT, round past ext4") + s = a.wait(lambda s: s["format"]["kind"] == "exFAT" and s["format"]["error"], "too long for exFAT, round past ext4") + assert s["format"]["line"] == "exFAT allows 11 characters. This has 14.", s["format"] a.key("ISO_Left_Tab", mods=["shift"]) format_focus(a, "Name") a.type(" 2026") s = a.wait(lambda s: s["format"]["error"], "too long for exFAT") - assert s["format"]["line"] == "exFAT allows 15 characters. This has 19.", s["format"] + assert s["format"]["line"] == "exFAT allows 11 characters. This has 19.", s["format"] a.key("a", mods=["ctrl"]) a.type("Holiday") @@ -1896,7 +1904,7 @@ def a_screen_reader_hears_the_format_warning(h): sr = ScreenReader() try: disks.say("drive Stick SanDisk-1234", "model Stick SanDisk Ultra", "fs sdb1 Stick PHOTOS", "lacks ext4 mkfs.ext4") - a = App(h, fs, extra_env={"DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address, "DBUS_SESSION_BUS_ADDRESS": sr.session.address}) + a = App(h, fs, extra_env={**disks.env, "DBUS_SESSION_BUS_ADDRESS": sr.session.address}) a.wait(lambda s: place_flags(s, "PHOTOS") is not None, "the stick") sr.screen_reader(True) sr.until("apps", lambda x: x == ["Gannet"], "registered once a screen reader is on") @@ -1909,7 +1917,7 @@ def a_screen_reader_hears_the_format_warning(h): assert alert["description"] == warning and warning.startswith("Everything on “SanDisk Ultra, 16.0 GB” will be erased"), alert assert "modal" in alert["states"], alert name = a11y_find(alert, "Name", "entry") - assert name and name["description"] == "Up to 15 characters, with no space at either end." and "invalid" not in name["states"], name + assert name and name["description"] == "Up to 11 characters (emoji count as 2), with no space at either end." and "invalid" not in name["states"], name radios = [a11y_find(alert, k, "radio button") for k in ("exFAT", "FAT32", "ext4")] assert all(radios), alert assert "checked" in radios[0]["states"] and "enabled" in radios[0]["states"], radios[0] @@ -1922,7 +1930,7 @@ def a_screen_reader_hears_the_format_warning(h): a.type("Sixteen letters!") w = sr.until(f"dump {win}", lambda w: "invalid" in (a11y_find(w, "Name", "entry") or {"states": []})["states"], "the name marked as invalid") name = a11y_find(w, "Name", "entry") - assert name["description"] == "exFAT allows 15 characters. This has 16.", name + assert name["description"] == "exFAT allows 11 characters. This has 16.", name assert "enabled" not in a11y_find(w, "Erase and Format", "button")["states"], "can't go ahead" assert "default" not in a11y_find(w, "Cancel", "button")["states"], "Enter presses nothing from the name" # A format picked with the screen reader, and Cancel pressed with it. @@ -2549,7 +2557,7 @@ def a_screen_reader_reads_columns_the_path_and_drives_and_hears_the_news(h): sr = ScreenReader() try: disks.say("drive Stick Kingston-1234", "fs sdb1 Stick PHOTOS") - a = App(h, fs / "docs", extra_env={"DBUS_SESSION_BUS_ADDRESS": sr.session.address, "DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address}) + a = App(h, fs / "docs", extra_env={"DBUS_SESSION_BUS_ADDRESS": sr.session.address, **disks.env}) a.wait(lambda s: s["names"] == ["dest", "sub", "a.txt", "bb.txt"] and place_flags(s, "PHOTOS") == {"eject"}, "listed, with the drive") time.sleep(0.5) assert sr.ask("apps") == [], "registered with no screen reader on" @@ -3090,7 +3098,7 @@ def a_screen_reader_can_use_menus_and_dialogs(h): sr = ScreenReader() try: disks.say("drive Stick Kingston-1234", "luks sdb2 Stick hunter2 SECRETS") - a = App(h, fs / "docs", extra_env={"DBUS_SESSION_BUS_ADDRESS": sr.session.address, "DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address}) + a = App(h, fs / "docs", extra_env={"DBUS_SESSION_BUS_ADDRESS": sr.session.address, **disks.env}) a.wait(lambda s: s["names"] == ["a.txt", "b.txt"], "listed") sr.screen_reader(True) sr.until("apps", lambda x: x == ["Gannet"], "registered") @@ -3271,7 +3279,7 @@ def pin_and_drive_menus_open_from_the_keyboard_and_a_screen_reader(h): sr = ScreenReader() try: disks.say("drive Stick Kingston-1234", "fs sdb1 Stick PHOTOS") - env = {"DBUS_SESSION_BUS_ADDRESS": sr.session.address, "DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address} + env = {"DBUS_SESSION_BUS_ADDRESS": sr.session.address, **disks.env} conf = bookmarks_file(App(h, fs / "docs", launch=False, extra_env=env)) conf.parent.mkdir(parents=True, exist_ok=True) conf.write_text("".join((fs / "pins" / n).as_uri() + "\n" for n in ["Projects", "Notes"])) diff --git a/tests/orca_tour.py b/tests/orca_tour.py index 24ddb3a..be47ce6 100644 --- a/tests/orca_tour.py +++ b/tests/orca_tour.py @@ -181,7 +181,7 @@ def main_window(h, sr, tour, disks): (fs / "slow").mkdir() with open(fs / "slow/big.bin", "wb") as f: f.truncate(384 << 20) - env = {"DBUS_SESSION_BUS_ADDRESS": sr.session.address, "DBUS_SYSTEM_BUS_ADDRESS": disks.bus.address, "GANNET_SLOW_COPY_MS": "500"} + env = {"DBUS_SESSION_BUS_ADDRESS": sr.session.address, **disks.env, "GANNET_SLOW_COPY_MS": "500"} probe = App(h, docs, launch=False, extra_env=env) data = Path(probe.env["XDG_DATA_HOME"]) data.mkdir(parents=True, exist_ok=True)