diff --git a/crates/downpour-app/src/ui/hotkeys.rs b/crates/downpour-app/src/ui/hotkeys.rs index 4017670..6b76b84 100644 --- a/crates/downpour-app/src/ui/hotkeys.rs +++ b/crates/downpour-app/src/ui/hotkeys.rs @@ -11,11 +11,15 @@ use eframe::egui::{self, Key, Modifiers}; -/// Whether a shortcut is a bare key or needs Ctrl (⌘ on macOS). +use super::selection::Pick; + +/// Whether a shortcut is a bare key or needs Ctrl (⌘ on macOS) or Shift. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Chord { Plain, Command, + /// Shift alone; in the list it extends the selection, as in Explorer. + Shift, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -43,12 +47,21 @@ impl Hotkey { } } + const fn shift(key: Key, name: &'static str) -> Self { + Self { + key, + chord: Chord::Shift, + name, + } + } + /// The keys as written on screen, e.g. "N" or "Ctrl+F". pub fn keys(self) -> String { match self.chord { Chord::Plain => self.name.to_owned(), Chord::Command if cfg!(target_os = "macos") => format!("⌘{}", self.name), Chord::Command => format!("Ctrl+{}", self.name), + Chord::Shift => format!("Shift+{}", self.name), } } @@ -61,6 +74,9 @@ impl Hotkey { let chord_held = match self.chord { Chord::Plain => modifiers.is_none(), Chord::Command => modifiers.command_only(), + Chord::Shift => { + modifiers.shift && !modifiers.ctrl && !modifiers.alt && !modifiers.command + } }; self.key == key && chord_held } @@ -70,6 +86,7 @@ impl Hotkey { let modifiers = match self.chord { Chord::Plain => Modifiers::NONE, Chord::Command => Modifiers::COMMAND, + Chord::Shift => Modifiers::SHIFT, }; ctx.input_mut(|input| input.consume_key(modifiers, self.key)) } @@ -98,6 +115,15 @@ pub const RENAME: Hotkey = Hotkey::plain(Key::F2, "F2"); pub const NEXT: Hotkey = Hotkey::plain(Key::ArrowDown, "↓"); pub const PREVIOUS: Hotkey = Hotkey::plain(Key::ArrowUp, "↑"); pub const DESELECT: Hotkey = Hotkey::plain(Key::Escape, "Esc"); +pub const SELECT_ALL: Hotkey = Hotkey::command(Key::A, "A"); +/// Shift with an arrow, Home, or End picks the run from the last click to +/// the row the key moves to. +pub const EXTEND_NEXT: Hotkey = Hotkey::shift(Key::ArrowDown, "↓"); +pub const EXTEND_PREVIOUS: Hotkey = Hotkey::shift(Key::ArrowUp, "↑"); +pub const FIRST: Hotkey = Hotkey::plain(Key::Home, "Home"); +pub const LAST: Hotkey = Hotkey::plain(Key::End, "End"); +pub const EXTEND_FIRST: Hotkey = Hotkey::shift(Key::Home, "Home"); +pub const EXTEND_LAST: Hotkey = Hotkey::shift(Key::End, "End"); /// Move the selected download one place earlier or later in its queue. pub const MOVE_UP: Hotkey = Hotkey::command(Key::ArrowUp, "↑"); pub const MOVE_DOWN: Hotkey = Hotkey::command(Key::ArrowDown, "↓"); @@ -131,14 +157,24 @@ pub enum Command { CopyAddress, Remove, Rename, - Next, - Previous, Deselect, + SelectAll, + /// Go to a row: alone, or with the run from the anchor (Shift). + Go(Row, Pick), MoveUp, MoveDown, } -const BINDINGS: [(Hotkey, Command); 19] = [ +/// The row a key goes to in the list. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Row { + Next, + Previous, + First, + Last, +} + +const BINDINGS: [(Hotkey, Command); 26] = [ (ADD_URL, Command::AddUrl), (ADD_LINKS, Command::AddLinks), (PAUSE_ALL, Command::PauseAll), @@ -153,9 +189,16 @@ const BINDINGS: [(Hotkey, Command); 19] = [ (COPY_ADDRESS, Command::CopyAddress), (REMOVE, Command::Remove), (RENAME, Command::Rename), - (NEXT, Command::Next), - (PREVIOUS, Command::Previous), + (NEXT, Command::Go(Row::Next, Pick::Only)), + (PREVIOUS, Command::Go(Row::Previous, Pick::Only)), (DESELECT, Command::Deselect), + (SELECT_ALL, Command::SelectAll), + (EXTEND_NEXT, Command::Go(Row::Next, Pick::Range)), + (EXTEND_PREVIOUS, Command::Go(Row::Previous, Pick::Range)), + (FIRST, Command::Go(Row::First, Pick::Only)), + (LAST, Command::Go(Row::Last, Pick::Only)), + (EXTEND_FIRST, Command::Go(Row::First, Pick::Range)), + (EXTEND_LAST, Command::Go(Row::Last, Pick::Range)), (MOVE_UP, Command::MoveUp), (MOVE_DOWN, Command::MoveDown), ]; @@ -166,10 +209,41 @@ pub fn main_window_has_keyboard(ctx: &egui::Context, dialog_open: bool) -> bool !dialog_open && !ctx.wants_keyboard_input() && !ctx.memory(|memory| memory.any_popup_open()) } +/// Whether text in a label is selected, as by dragging across an address +/// in the details panel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LabelText { + Selected, + NotSelected, +} + +/// What the copy event (Ctrl+C, Ctrl+Insert) does: selected label text owns +/// it, as everywhere else; otherwise it copies the picked addresses. +fn copy_command(label_text: LabelText) -> Option { + match label_text { + LabelText::Selected => None, + LabelText::NotSelected => Some(Command::CopyAddress), + } +} + /// Removes this frame's shortcut presses from `raw` and returns them. -pub fn take_pressed(raw: &mut egui::RawInput) -> Vec { +pub fn take_pressed(ctx: &egui::Context, raw: &mut egui::RawInput) -> Vec { + let label_text = if egui::text_selection::LabelSelectionState::load(ctx).has_selection() { + LabelText::Selected + } else { + LabelText::NotSelected + }; let mut commands = Vec::new(); raw.events.retain(|event| { + // The window turns Ctrl+C into a copy event instead of a key press, + // so the copy shortcut is that event. + if matches!(event, egui::Event::Copy) { + let Some(command) = copy_command(label_text) else { + return true; + }; + commands.push(command); + return false; + } let egui::Event::Key { key, pressed: true, @@ -179,12 +253,9 @@ pub fn take_pressed(raw: &mut egui::RawInput) -> Vec { else { return true; }; - match BINDINGS - .iter() - .find(|(hotkey, _)| hotkey.matches(*key, *modifiers)) - { - Some((_, command)) => { - commands.push(*command); + match command_for(*key, *modifiers) { + Some(command) => { + commands.push(command); false } None => true, @@ -193,6 +264,14 @@ pub fn take_pressed(raw: &mut egui::RawInput) -> Vec { commands } +/// The command a key press with these modifiers is bound to. +fn command_for(key: Key, modifiers: Modifiers) -> Option { + BINDINGS + .iter() + .find(|(hotkey, _)| hotkey.matches(key, modifiers)) + .map(|(_, command)| *command) +} + const FOCUS_SEARCH: &str = "downpour-focus-search"; /// Asks the search field to take focus on its next frame. @@ -218,6 +297,55 @@ mod tests { assert!(search == "Ctrl+F" || search == "⌘F"); } + #[test] + fn shift_and_ctrl_pick_their_own_commands() { + let shift = Modifiers::SHIFT; + let go = |row, pick| Some(Command::Go(row, pick)); + assert_eq!( + command_for(Key::ArrowDown, Modifiers::NONE), + go(Row::Next, Pick::Only) + ); + assert_eq!( + command_for(Key::ArrowDown, shift), + go(Row::Next, Pick::Range) + ); + assert_eq!( + command_for(Key::ArrowDown, Modifiers::COMMAND), + Some(Command::MoveDown) + ); + assert_eq!(command_for(Key::End, shift), go(Row::Last, Pick::Range)); + assert_eq!( + command_for(Key::A, Modifiers::COMMAND), + Some(Command::SelectAll) + ); + // Ctrl+Shift is no binding of its own. + assert_eq!( + command_for(Key::ArrowDown, Modifiers::COMMAND | shift), + None + ); + assert_eq!(EXTEND_LAST.keys(), "Shift+End"); + } + + #[test] + fn the_copy_event_copies_the_address() { + let mut raw = egui::RawInput { + events: vec![egui::Event::Copy], + ..Default::default() + }; + let ctx = egui::Context::default(); + assert_eq!(take_pressed(&ctx, &mut raw), [Command::CopyAddress]); + assert!(raw.events.is_empty()); + } + + #[test] + fn selected_label_text_keeps_the_copy_event() { + assert_eq!(copy_command(LabelText::Selected), None); + assert_eq!( + copy_command(LabelText::NotSelected), + Some(Command::CopyAddress) + ); + } + #[test] fn each_main_window_key_does_one_thing() { for (index, (hotkey, _)) in BINDINGS.iter().enumerate() { diff --git a/crates/downpour-app/src/ui/list.rs b/crates/downpour-app/src/ui/list.rs index a972987..da0eb60 100644 --- a/crates/downpour-app/src/ui/list.rs +++ b/crates/downpour-app/src/ui/list.rs @@ -60,6 +60,8 @@ pub struct ListState<'a> { /// The downloads shown for this view and search, in list order; the /// app works them out once a frame. pub visible: &'a [&'a DownloadView], + /// A row a key just moved to, scrolled into view this frame. + pub reveal: Option, } pub fn show(ui: &mut Ui, state: ListState<'_>, actions: &mut Vec) { @@ -128,6 +130,7 @@ fn download_rows<'a>( visible, selection: state.selection, shown: &shown, + reveal: state.reveal, }; // A queue view shows the start order, so its rows can be dragged and // moved; other views are filtered lists. @@ -152,6 +155,20 @@ fn download_rows<'a>( dragged_badge(ui.ctx(), in_queue); } +/// Copies the shown picks' addresses: one, or each on its own line. +pub fn copy_addresses(shown: &Shown<'_>) -> Option { + match shown { + Shown::Nothing => None, + Shown::One(download) => Some(Action::CopyText(download.url.to_string())), + Shown::Group(group) => Some(Action::CopyAddresses( + group + .iter() + .map(|download| download.url.to_string()) + .collect(), + )), + } +} + /// What a dragged row carries: the downloads it moves, in list order. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DraggedDownloads(pub Vec); @@ -960,6 +977,7 @@ struct RowList<'a> { selection: &'a Selection, /// The picks among `visible`. shown: &'a Shown<'a>, + reveal: Option, } impl<'a> RowList<'a> { @@ -1099,6 +1117,9 @@ fn row<'a>( vec2(ui.available_width(), geometry.slot_height()), Sense::click_and_drag(), ); + if list.reveal == Some(download.id) { + response.scroll_to_me(None); + } if !ui.is_rect_visible(slot) { return; } @@ -1586,16 +1607,12 @@ fn group_menu( ui.separator(); single_file_item(ui, "Open download page"); single_file_item(ui, "Refresh download address…"); - let addresses = group - .iter() - .map(|download| download.url.to_string()) - .collect(); group_item( ui, actions, GroupItem { - label: "Copy addresses", - does: vec![Action::CopyAddresses(addresses)], + label: &hotkeys::COPY_ADDRESS.label("Copy addresses"), + does: copy_addresses(list.shown).into_iter().collect(), off_because: None, }, ); diff --git a/crates/downpour-app/src/ui/mod.rs b/crates/downpour-app/src/ui/mod.rs index 7e63153..366c27e 100644 --- a/crates/downpour-app/src/ui/mod.rs +++ b/crates/downpour-app/src/ui/mod.rs @@ -154,6 +154,8 @@ pub enum Action { Select(Option), /// A click on a row; the keys held decide how the selection changes. Pick(DownloadId, Pick), + /// Pick every row the list shows (Ctrl+A). + SelectAll, SetFilter(Filter), ShowStatistics, RefreshStatistics, @@ -214,6 +216,8 @@ pub struct App { /// The rows the list shows this frame, in order: a Shift+click runs /// through these. shown_rows: Vec, + /// A row a key moved to, for the list to scroll into view. + reveal: Option, dialog: Option, pending_browser: VecDeque, /// The next link the browser sends replaces this download's address. @@ -325,6 +329,7 @@ impl App { search: String::new(), selection: Selection::default(), shown_rows: Vec::new(), + reveal: None, dialog: None, pending_browser: VecDeque::new(), awaiting_refresh: None, @@ -470,6 +475,10 @@ impl App { self.selection.pick(id, pick, &self.shown_rows); Ok(()) } + Action::SelectAll => { + self.selection.select_all(&self.shown_rows); + Ok(()) + } Action::SetFilter(filter) => { self.filter = filter; self.page = Page::Downloads; @@ -1144,7 +1153,7 @@ impl App { }; let completed = |download: &&DownloadView| download.status == DownloadStatus::Completed; - commands + let actions: Vec = commands .into_iter() .filter_map(|command| match command { Command::AddUrl => Some(Action::OpenAddUrl), @@ -1167,15 +1176,21 @@ impl App { Command::ClearCompleted => { (on_list && visible.iter().any(completed)).then_some(Action::ClearCompleted) } - Command::Next | Command::Previous if on_list => { - let step = match command { - Command::Next => list::Step::Next, - _ => list::Step::Previous, - }; - list::neighbor(visible, self.selection.focus(), step) - .map(|download| Action::Select(Some(download.id))) + Command::Go(row, pick) if on_list => { + let target = match row { + hotkeys::Row::Next => { + list::neighbor(visible, self.selection.focus(), list::Step::Next) + } + hotkeys::Row::Previous => { + list::neighbor(visible, self.selection.focus(), list::Step::Previous) + } + hotkeys::Row::First => visible.first().copied(), + hotkeys::Row::Last => visible.last().copied(), + }?; + Some(Action::Pick(target.id, pick)) } - Command::Next | Command::Previous => None, + Command::SelectAll if on_list => (!visible.is_empty()).then_some(Action::SelectAll), + Command::Go(..) | Command::SelectAll => None, Command::Deselect => (!self.selection.is_empty()).then_some(Action::Select(None)), Command::Primary => selected .and_then(list::primary_row_action) @@ -1186,9 +1201,8 @@ impl App { Command::ShowInFolder => { selected.map(|download| Action::Reveal(list::location(download))) } - Command::CopyAddress => { - selected.map(|download| Action::CopyText(download.url.to_string())) - } + Command::CopyAddress if on_list => list::copy_addresses(&shown), + Command::CopyAddress => None, Command::Remove => (!picked.is_empty()).then(|| Action::AskRemove(picked.clone())), Command::Rename => selected.map(|download| Action::AskRename(download.id)), Command::MoveUp | Command::MoveDown => { @@ -1205,7 +1219,13 @@ impl App { .map(|place| Action::MoveInQueue(vec![download.id], place)) } }) - .collect() + .collect(); + // A key that moved to a row scrolls it into view. + self.reveal = actions.iter().rev().find_map(|action| match action { + Action::Pick(id, _) => Some(*id), + _ => None, + }); + actions } /// The saved look, or the one being tried in Settings so the window @@ -1329,7 +1349,7 @@ impl eframe::App for App { #[cfg(debug_assertions)] raw_input.events.append(&mut self.injected_input); if hotkeys::main_window_has_keyboard(ctx, self.dialog.is_some()) { - self.pending_hotkeys = hotkeys::take_pressed(raw_input); + self.pending_hotkeys = hotkeys::take_pressed(ctx, raw_input); } } @@ -1459,6 +1479,7 @@ impl eframe::App for App { stats::show(ui, &statistics, &live, intro, &mut actions) } None => { + let reveal = self.reveal.take(); let state = list::ListState { downloads: &downloads, catalog: &catalog, @@ -1467,6 +1488,7 @@ impl eframe::App for App { selection: &self.selection, order: self.settings.list_order, visible: &visible, + reveal, }; list::show(ui, state, &mut actions); } diff --git a/crates/downpour-app/src/ui/selection.rs b/crates/downpour-app/src/ui/selection.rs index 676aceb..906f968 100644 --- a/crates/downpour-app/src/ui/selection.rs +++ b/crates/downpour-app/src/ui/selection.rs @@ -1,6 +1,6 @@ //! Which downloads are picked in the list. A plain click picks one, -//! Shift+click picks the run from the last plain or Ctrl click, and -//! Ctrl+click adds or drops one, as in a file browser. +//! Shift+click picks the run from the last plain or Ctrl click, Ctrl+click +//! adds or drops one, and Ctrl+Shift+click adds a run, as in a file browser. use std::collections::HashSet; @@ -15,17 +15,18 @@ pub enum Pick { Range, /// Add this download, or drop it if it was picked (Ctrl). Toggle, + /// Add the run from the anchor to this one, keeping the rest (Ctrl+Shift). + AddRange, } impl Pick { - /// The pick a click with these keys held makes. Shift wins over Ctrl. + /// The pick a click with these keys held makes. pub fn from_modifiers(modifiers: eframe::egui::Modifiers) -> Pick { - if modifiers.shift { - Pick::Range - } else if modifiers.command { - Pick::Toggle - } else { - Pick::Only + match (modifiers.shift, modifiers.command) { + (true, true) => Pick::AddRange, + (true, false) => Pick::Range, + (false, true) => Pick::Toggle, + (false, false) => Pick::Only, } } } @@ -94,24 +95,55 @@ impl Selection { self.anchor = Some(id); self.focus = Some(id); } - Pick::Range => { - let from = self - .anchor - .and_then(|anchor| visible.iter().position(|shown| *shown == anchor)); - let to = visible.iter().position(|shown| *shown == id); - // With no anchor in view there is no run to pick: start one here. - let (Some(from), Some(to)) = (from, to) else { - *self = Selection::only(id); - return; - }; - let run = if from <= to { from..=to } else { to..=from }; + Pick::Range => match self.run_to(id, visible) { // The anchor stays, so the next Shift+click redraws the run. - self.picked = visible[run].iter().copied().collect(); - self.focus = Some(id); - } + Some(run) => { + self.picked = run.iter().copied().collect(); + self.focus = Some(id); + } + // With no anchor in view there is no run to pick: start one here. + None => *self = Selection::only(id), + }, + Pick::AddRange => match self.run_to(id, visible) { + Some(run) => { + self.picked.extend(run.iter().copied()); + self.focus = Some(id); + } + None => { + self.picked.insert(id); + self.anchor = Some(id); + self.focus = Some(id); + } + }, } } + /// The rows from the anchor to `id` in `visible`, either way; `None` + /// when either is not shown. + fn run_to<'v>(&self, id: DownloadId, visible: &'v [DownloadId]) -> Option<&'v [DownloadId]> { + let from = visible + .iter() + .position(|shown| Some(*shown) == self.anchor)?; + let to = visible.iter().position(|shown| *shown == id)?; + Some(if from <= to { + &visible[from..=to] + } else { + &visible[to..=from] + }) + } + + /// Picks every row in `visible`, as Ctrl+A does. The anchor and focus + /// stay if shown; otherwise both start on the first row. + pub fn select_all(&mut self, visible: &[DownloadId]) { + let in_view = |id: &DownloadId| visible.contains(id); + self.picked = visible.iter().copied().collect(); + self.focus = self + .focus + .filter(in_view) + .or_else(|| visible.first().copied()); + self.anchor = self.anchor.filter(in_view).or(self.focus); + } + pub fn contains(&self, id: DownloadId) -> bool { self.picked.contains(&id) } @@ -229,6 +261,43 @@ mod tests { assert!(matches!(selection.shown(&[&two]), Shown::Nothing)); } + #[test] + fn ctrl_shift_adds_a_run_and_keeps_the_rest() { + let list = ids(&[1, 2, 3, 4, 5, 6]); + let mut selection = Selection::only(DownloadId(1)); + selection.pick(DownloadId(4), Pick::Toggle, &list); + selection.pick(DownloadId(6), Pick::AddRange, &list); + assert_eq!(picked(&selection), [1, 4, 5, 6]); + assert_eq!(selection.focus(), Some(DownloadId(6))); + } + + #[test] + fn select_all_picks_every_shown_row_and_keeps_the_focus() { + let list = ids(&[1, 2, 3]); + let mut selection = Selection::only(DownloadId(2)); + selection.select_all(&list); + assert_eq!(picked(&selection), [1, 2, 3]); + assert_eq!(selection.focus(), Some(DownloadId(2))); + // With nothing picked before, the focus starts on the first row. + let mut fresh = Selection::default(); + fresh.select_all(&list); + assert_eq!(fresh.focus(), Some(DownloadId(1))); + // A Shift range afterwards runs from the focus. + fresh.pick(DownloadId(2), Pick::Range, &list); + assert_eq!(picked(&fresh), [1, 2]); + } + + #[test] + fn select_all_keeps_the_anchor_of_a_shift_run() { + let list = ids(&[1, 2, 3, 4, 5]); + let mut selection = Selection::only(DownloadId(2)); + selection.pick(DownloadId(5), Pick::Range, &list); + selection.select_all(&list); + // Shift+Up from 5 redraws the run from 2, as in Explorer. + selection.pick(DownloadId(4), Pick::Range, &list); + assert_eq!(picked(&selection), [2, 3, 4]); + } + #[test] fn removed_downloads_leave_the_selection() { let list = ids(&[1, 2, 3]); diff --git a/crates/downpour-core/src/manager.rs b/crates/downpour-core/src/manager.rs index f42497c..43732bc 100644 --- a/crates/downpour-core/src/manager.rs +++ b/crates/downpour-core/src/manager.rs @@ -230,6 +230,10 @@ struct Inner { /// snapshot can never land after a newer one: the final save at exit /// would otherwise lose downloads added since a background save began. save_turn: Mutex<()>, + /// Set by `shutdown` after its final save, under `save_turn`. Saves that + /// were still under way then find it set and write nothing, so the final + /// list stays the last word even if another manager opens the same store. + closed: AtomicBool, listener: Mutex>, } @@ -384,6 +388,7 @@ impl DownloadManager { dirty: AtomicBool::new(unsaved), persist_now: Notify::new(), save_turn: Mutex::new(()), + closed: AtomicBool::new(false), listener: Mutex::new(None), }), }; @@ -1039,9 +1044,15 @@ impl DownloadManager { { std::thread::sleep(Duration::from_millis(50)); } - if let Err(error) = self.save_records() { + let _turn = self + .inner + .save_turn + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Err(error) = self.inner.store.save_downloads(&self.records()) { tracing::error!(%error, "final save failed"); } + self.inner.closed.store(true, Ordering::Release); } fn state(&self) -> MutexGuard<'_, State> { @@ -1357,6 +1368,10 @@ impl DownloadManager { .save_turn .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); + // After shutdown its final save is the last word: write nothing. + if self.inner.closed.load(Ordering::Acquire) { + return Ok(()); + } self.inner.store.save_downloads(&self.records()) } diff --git a/crates/downpour-core/tests/downloads.rs b/crates/downpour-core/tests/downloads.rs index 1c21060..5e8101c 100644 --- a/crates/downpour-core/tests/downloads.rs +++ b/crates/downpour-core/tests/downloads.rs @@ -1721,3 +1721,21 @@ async fn moving_to_a_queue_moves_all_or_none() { let queues: Vec<_> = manager.snapshot().iter().map(|view| view.queue).collect(); assert_eq!(queues, [later, later]); } + +/// A manager that shut down writes nothing more: another one may own the +/// list by then, as when the app restarts. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_manager_saves_nothing_after_shutdown() { + let dir = temp_dir("closed"); + let manager = manager_in(&dir, 1); + held_downloads(&manager, &["a.bin"]); + manager.shutdown(Duration::from_secs(5)); + + // Someone else's list now, then a change that would have been saved. + let store = Store::open(dir.join("state")).unwrap(); + store.save_downloads(&[]).unwrap(); + held_downloads(&manager, &["b.bin"]); + tokio::time::sleep(Duration::from_millis(500)).await; + + assert!(store.load_downloads().unwrap().is_empty()); +}