Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Clipboard: every read off the window's thread (follows #418) (#688)

Ahmed Nefzaoui98418eee0c26
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba2242c4..1c43a1db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- The window no longer waits for the program that owns the clipboard. A text box's right-click menu (to offer **Paste**) and **Add URL**, **Add batch download**, **Add torrent** and **Download video** (to fill in a copied link) read the clipboard on the window's own thread, so a program that held the clipboard without answering (on Linux, where a read waited up to 4 seconds each time, and while the right-click menu was open at every frame; on Windows, a program that had stopped responding) held up MDM's window too. They now read it beside the window, as the clipboard monitor has since 0.5.1; a link copied just before still fills the box as the window opens (follows [#418](https://github.com/anefzaoui/misterdownloadmanager/issues/418)).
- Linux: freeze and crash reports show MDM's own functions, files and lines again, and the right ones. When MDM's code began a page after the start of the program in memory (as 0.5.0's did), the report read the whole stack at the wrong place: it showed only system libraries (`freeze in libc.so.6+…`), named other functions of MDM once the release's symbols were fetched, and couldn't find an existing issue for the same problem. A `.dmp` from such a report reads right too ([#661](https://github.com/anefzaoui/misterdownloadmanager/issues/661)).
- Windows: a freeze report whose window thread hardly ran and stopped in the C runtime's memory routines (`VCRUNTIME140.dll`, comparing the first bytes of an icon) now says the computer was too busy to run MDM or slow to load it from disk, with the page faults counted meanwhile, instead of a deadlock; those routines never wait ([#663](https://github.com/anefzaoui/misterdownloadmanager/issues/663)).
- Torrents: magnet links without trackers find peers through the DHT again where its first nodes didn't answer. MDM asked only two public routers to join the DHT; where neither answered (one name pointing at an old address, or a network blocking one), the DHT stayed empty and the log said "error in bootstrap" every minute or two. It now asks four together (`dht.libtorrent.org`, `dht.transmissionbt.com`, `router.bittorrent.com`, `router.utorrent.com`), any one that answers is enough, and the others are asked no more once one has. The nodes it knows are kept for the next start, the IPv6 ones too ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 28922512..b3c6d31b 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -587,6 +587,10 @@ These ship in a later version, when they're ready.
- 🔄 Windows: a crash when the clipboard was read in two places at once (the clipboard monitor and
Add URL) ([#629](https://github.com/anefzaoui/misterdownloadmanager/issues/629)): every read and
write of the clipboard now goes one at a time; fix in review
+- 🔄 The window waiting on the program that owns the clipboard when it doesn't answer (Linux
+ especially; follows [#418](https://github.com/anefzaoui/misterdownloadmanager/issues/418)): a
+ text box's right-click menu, Add URL, Add batch download, Add torrent and Download video now
+ read the clipboard beside the window, and fill in a copied link when it comes; fix in review
- 🔄 Categories without their own folder following General's folder (`Video`, `Music`, `Torrents`
inside it), and Add torrent starting with the Torrents category's folder instead of flipping
from General when metadata arrives ([#556](https://github.com/anefzaoui/misterdownloadmanager/issues/556),
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 4bf0d865..84a8b899 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -641,8 +641,8 @@ pub struct App {
/// yet) and when.
clip_seen: Option<Option<String>>,
clip_checked: Option<Instant>,
- /// The clipboard read under way, off the window thread (#418).
- clip_reading: Option<ClipRead>,
+ /// The monitor's ask for the clipboard, its read off the window thread (#418).
+ clip_asked: Option<crate::clipboard::Ask>,
confirm_delete: Option<dialogs::ConfirmDelete>,
/// Queue right-click → Delete, asking first: the queue and the question.
confirm_queue_delete: Option<(usize, dialogs::Confirm)>,
@@ -855,28 +855,6 @@ pub fn auth_headers(login: Option<&(String, String)>) -> HeaderMap {
h
}
-/// A read of the clipboard on a thread of its own, its answer taken when it has come (#418).
-struct ClipRead(std::sync::Arc<std::sync::Mutex<Option<Option<String>>>>);
-
-impl ClipRead {
- fn start(read: impl FnOnce() -> Option<String> + Send + 'static) -> Self {
- let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
- let answer = slot.clone();
- let _ = std::thread::Builder::new()
- .name("clipboard read".into())
- .spawn(move || {
- *answer.lock().unwrap() = Some(read());
- });
- ClipRead(slot)
- }
-
- /// The text, once the read has answered; else the read, still waiting.
- fn answer(self) -> Result<Option<String>, Self> {
- let got = self.0.lock().unwrap().take();
- got.ok_or(self)
- }
-}
-
/// A stopped download's files: its state and part files, and its finished file when it was
/// complete (a Stop-then-remove of a download that finished meanwhile).
fn remove_files_of(dest: &std::path::Path, complete: bool) {
@@ -1200,7 +1178,7 @@ impl App {
limit_notice: None,
clip_seen: None,
clip_checked: None,
- clip_reading: None,
+ clip_asked: None,
tray: None,
tray_limiter: None,
tray_last_focused: None,
@@ -3260,17 +3238,16 @@ impl App {
return;
}
ctx.request_repaint_after(Duration::from_secs(1));
- // One read at a time, on its own thread: the program that owns the clipboard may hang,
- // and a read that waits for it took the window with it (#418). A read under way
- // that never answers just means no new look at the clipboard.
- let reading = self.clip_reading.take();
- let text = match reading {
- Some(read) => match read.answer() {
- Ok(text) => text,
- Err(still) => {
- self.clip_reading = Some(still);
- return;
- }
+ // Read off the window's thread (clipboard.rs): the program that owns the clipboard may
+ // hang, and a read that waits for it took the window with it (#418). An ask that is
+ // never answered just means no new look at the clipboard.
+ let text = match self.clip_asked {
+ Some(ask) => match crate::clipboard::answer(ask) {
+ Some(text) => {
+ self.clip_asked = None;
+ text
+ }
+ None => return,
},
None => {
if self
@@ -3280,7 +3257,7 @@ impl App {
return;
}
self.clip_checked = Some(Instant::now());
- self.clip_reading = Some(ClipRead::start(crate::clipboard_text));
+ self.clip_asked = Some(crate::clipboard::ask());
return;
}
};
@@ -9428,31 +9405,6 @@ mod page_data_tests {
mod window_thread_tests {
use super::*;
- /// #418: a clipboard read that never answers (its owner hung) doesn't hold up the window:
- /// its answer just isn't there yet; one that answers is taken.
- #[test]
- fn a_stuck_clipboard_owner_does_not_hold_the_window() {
- let (release, wait) = std::sync::mpsc::channel::<()>();
- let stuck = ClipRead::start(move || {
- let _ = wait.recv();
- Some("late".to_owned())
- });
- let started = Instant::now();
- let Err(mut waiting) = stuck.answer() else {
- panic!("no answer yet");
- };
- assert!(started.elapsed() < Duration::from_millis(500));
- release.send(()).unwrap();
- let text = loop {
- match waiting.answer() {
- Ok(text) => break text,
- Err(still) => waiting = still,
- }
- std::thread::sleep(Duration::from_millis(2));
- };
- assert_eq!(text.as_deref(), Some("late"));
- }
-
/// #423: the files of a stopped download go as a group, off the window's thread.
#[test]
fn a_stopped_downloads_files_are_removed_together() {
diff --git a/crates/app/src/batch.rs b/crates/app/src/batch.rs
index fc0c6c4c..bfd31fba 100644
--- a/crates/app/src/batch.rs
+++ b/crates/app/src/batch.rs
@@ -18,6 +18,8 @@ pub struct Batch {
focused: bool,
/// The pattern's addresses (or why none), and the inputs they were made from.
cached: Option<(PatternKey, Result<Vec<url::Url>, &'static str>)>,
+ /// The clipboard's address, read off the window's thread (#661).
+ clip: crate::clipboard::Prefill,
}
/// What a pattern's addresses are made from: address, letters, from, to, size.
@@ -30,18 +32,11 @@ pub struct Added {
}
impl Batch {
- /// Pre-filled from the clipboard when it holds an http(s) or ftp(s) address, as IDM's.
+ /// Pre-filled from the clipboard when it holds an http(s) or ftp(s) address, as IDM's: read
+ /// off the window's thread, the address put in the box on the frame it comes.
pub fn new(from_clipboard: bool) -> Self {
- let address = if from_clipboard {
- crate::clipboard_text()
- .map(|t| t.trim().to_owned())
- .filter(|t| url::Url::parse(t).is_ok_and(|u| mdm_engine::supported(&u)))
- .unwrap_or_default()
- } else {
- String::new()
- };
Batch {
- address,
+ address: String::new(),
letters: false,
from: "0".into(),
to: "10".into(),
@@ -51,6 +46,21 @@ impl Batch {
password: String::new(),
focused: false,
cached: None,
+ clip: if from_clipboard {
+ crate::clipboard::Prefill::ask()
+ } else {
+ Default::default()
+ },
+ }
+ }
+
+ /// The clipboard's text as the address, when it is one MDM downloads and the box is still
+ /// empty (nothing typed meanwhile).
+ fn fill_from_clipboard(&mut self, clip: &str) {
+ let clip = clip.trim();
+ if self.address.is_empty() && url::Url::parse(clip).is_ok_and(|u| mdm_engine::supported(&u))
+ {
+ self.address = clip.to_owned();
}
}
@@ -124,6 +134,9 @@ impl Batch {
}
pub fn show(&mut self, ctx: &egui::Context) -> Outcome<Added> {
+ if let Some(clip) = self.clip.take() {
+ self.fill_from_clipboard(&clip);
+ }
// Worked out again only when the pattern changes (up to 100,000 addresses).
let key = (
self.address.clone(),
@@ -442,6 +455,24 @@ mod tests {
}
}
+ /// #661: the clipboard's address comes a frame or more after the window opens: it fills
+ /// an empty box only, and only with an address MDM downloads.
+ #[test]
+ fn the_clipboard_fills_only_an_empty_box() {
+ let mut b = batch("");
+ b.fill_from_clipboard(
+ " http://x/img*.jpg
+",
+ );
+ assert_eq!(b.address, "http://x/img*.jpg");
+ let mut b = batch("http://typed/*.png");
+ b.fill_from_clipboard("http://x/img*.jpg");
+ assert_eq!(b.address, "http://typed/*.png");
+ let mut b = batch("");
+ b.fill_from_clipboard("not an address");
+ assert_eq!(b.address, "");
+ }
+
#[test]
fn numbers_with_a_wildcard_size() {
let mut b = batch("http://x/img*.jpg");
diff --git a/crates/app/src/clipboard.rs b/crates/app/src/clipboard.rs
new file mode 100644
index 00000000..8bbcd582
--- /dev/null
+++ b/crates/app/src/clipboard.rs
@@ -0,0 +1,269 @@
+//! The clipboard's text, read off the window's thread (#418, #661). A read waits for the program
+//! that owns the clipboard: on X11 (and Wayland, through XWayland) until it answers or a time
+//! limit runs out, on Windows until a program that hands its copy over late does so, which a
+//! hung program never does. Read on the window's thread, that wait froze the window.
+//!
+//! One thread reads, for everyone: the clipboard monitor, a text box's Paste and the dialogs
+//! that open with a copied link ([`Prefill`]) ask ([`ask`]) and take the answer on a later
+//! frame ([`answer`]); the window is woken when it comes. A read that never answers holds up
+//! nothing but the next read.
+
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
+
+/// One ask for the clipboard's text, answered by a read that starts after it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Ask(u64);
+
+/// The thread that reads the clipboard when asked, one read at a time. Asks made while a read is
+/// under way are answered together by the next one.
+pub struct Reader {
+ shared: Arc<Shared>,
+}
+
+struct Shared {
+ state: Mutex<State>,
+ asked: Condvar,
+}
+
+#[derive(Default)]
+struct State {
+ /// The newest ask, and the newest one a read has answered.
+ asked: u64,
+ answered: u64,
+ /// What the last read found.
+ text: Option<String>,
+ closed: bool,
+}
+
+impl Shared {
+ fn lock(&self) -> MutexGuard<'_, State> {
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+}
+
+impl Reader {
+ /// `read` reads the clipboard (it may wait, for ever); `wake` is told when an answer has
+ /// come (the window takes it on its next frame).
+ pub fn new(
+ read: impl Fn() -> Option<String> + Send + 'static,
+ wake: impl Fn() + Send + 'static,
+ ) -> Self {
+ let shared = Arc::new(Shared {
+ state: Mutex::new(State::default()),
+ asked: Condvar::new(),
+ });
+ let worker = shared.clone();
+ let spawned = std::thread::Builder::new()
+ .name("clipboard read".into())
+ .spawn(move || {
+ loop {
+ let ask = {
+ let mut s = worker.lock();
+ while s.asked == s.answered && !s.closed {
+ s = worker.asked.wait(s).unwrap_or_else(PoisonError::into_inner);
+ }
+ if s.closed {
+ return;
+ }
+ s.asked
+ };
+ // Not under the lock: an ask is never held up by the read under way.
+ let text = read();
+ {
+ let mut s = worker.lock();
+ s.text = text;
+ s.answered = ask;
+ }
+ wake();
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!("clipboard: no thread to read it ({e}), it is not read");
+ }
+ Reader { shared }
+ }
+
+ /// Ask for the clipboard's text, at once (never waits for a read).
+ pub fn ask(&self) -> Ask {
+ let mut s = self.shared.lock();
+ s.asked += 1;
+ self.shared.asked.notify_one();
+ Ask(s.asked)
+ }
+
+ /// The clipboard's text once a read started after `ask` has answered (None inside: no
+ /// text); None while it hasn't.
+ pub fn answer(&self, ask: Ask) -> Option<Option<String>> {
+ let s = self.shared.lock();
+ (s.answered >= ask.0).then(|| s.text.clone())
+ }
+
+ /// What the last read found (None: no text, or nothing read yet).
+ pub fn latest(&self) -> Option<String> {
+ self.shared.lock().text.clone()
+ }
+}
+
+impl Drop for Reader {
+ fn drop(&mut self) {
+ self.shared.lock().closed = true;
+ self.shared.asked.notify_one();
+ }
+}
+
+/// The window woken when an answer comes (set once the window exists).
+static WINDOW: OnceLock<egui::Context> = OnceLock::new();
+
+/// MDM's reader, of the system clipboard ([`crate::clipboard_text`]); started at its first ask.
+fn reader() -> &'static Reader {
+ static READER: OnceLock<Reader> = OnceLock::new();
+ READER.get_or_init(|| {
+ Reader::new(crate::clipboard_text, || {
+ // A pass of the main window's UI, which draws the dialogs, even minimized.
+ if let Some(ctx) = WINDOW.get() {
+ ctx.request_ui_pass(egui::ViewportId::ROOT);
+ }
+ })
+ })
+}
+
+/// The window to wake when a read answers.
+pub fn wake(ctx: &egui::Context) {
+ let _ = WINDOW.set(ctx.clone());
+}
+
+/// [`Reader::ask`] of the system clipboard.
+pub fn ask() -> Ask {
+ reader().ask()
+}
+
+/// [`Reader::answer`] of the system clipboard.
+pub fn answer(ask: Ask) -> Option<Option<String>> {
+ reader().answer(ask)
+}
+
+/// [`Reader::latest`] of the system clipboard.
+pub fn latest() -> Option<String> {
+ reader().latest()
+}
+
+/// A dialog's box filled from the clipboard as it opens (Add URL, Batch download, Add torrent,
+/// Download video): asked when the dialog opens, and the text handed over once, on the frame
+/// its answer comes. The dialog fills its box then if the user hasn't typed in it.
+#[derive(Default)]
+pub struct Prefill(Option<(Ask, &'static Reader)>);
+
+impl Prefill {
+ /// Ask the system clipboard now.
+ pub fn ask() -> Self {
+ Self::ask_of(reader())
+ }
+
+ /// Ask `reader` now (a test's).
+ pub fn ask_of(reader: &'static Reader) -> Self {
+ Prefill(Some((reader.ask(), reader)))
+ }
+
+ /// Whether the answer is still to come.
+ #[cfg(test)]
+ pub fn pending(&self) -> bool {
+ self.0.is_some()
+ }
+
+ /// The clipboard's text, on the frame it comes, once (None before and after; and when the
+ /// clipboard holds no text).
+ pub fn take(&mut self) -> Option<String> {
+ let (ask, reader) = self.0?;
+ let got = reader.answer(ask)?;
+ self.0 = None;
+ got
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::{Duration, Instant};
+
+ /// Wait (at most 5 s) for `ask`'s answer.
+ fn wait(r: &Reader, ask: Ask) -> Option<Option<String>> {
+ let until = Instant::now() + Duration::from_secs(5);
+ while Instant::now() < until {
+ if let Some(got) = r.answer(ask) {
+ return Some(got);
+ }
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ None
+ }
+
+ /// #418, #661: a clipboard owner that never answers holds up no frame: asking, looking for
+ /// the answer, the last text and a dialog's prefill all return at once, the answer just
+ /// isn't there. When the owner answers at last, the window is woken and the text taken.
+ #[test]
+ fn a_clipboard_owner_that_never_answers_holds_up_no_frame() {
+ let (release, stuck) = std::sync::mpsc::channel::<()>();
+ let stuck = Mutex::new(stuck);
+ let (woke, woken) = std::sync::mpsc::channel::<()>();
+ let r: &'static Reader = Box::leak(Box::new(Reader::new(
+ move || {
+ let _ = stuck.lock().unwrap().recv();
+ Some("https://late.example/a.zip".to_owned())
+ },
+ move || {
+ let _ = woke.send(());
+ },
+ )));
+ let started = Instant::now();
+ let first = r.ask();
+ let mut prefill = Prefill::ask_of(r);
+ for _ in 0..1000 {
+ assert_eq!(r.answer(first), None);
+ assert_eq!(prefill.take(), None);
+ assert_eq!(r.latest(), None);
+ // A text box's menu asks each time it opens: no second thread, no wait.
+ let _ = r.ask();
+ }
+ assert!(
+ started.elapsed() < Duration::from_millis(500),
+ "{:?} for 1000 frames",
+ started.elapsed()
+ );
+ assert!(woken.try_recv().is_err(), "no answer, no wake");
+ // The owner answers at last (and every read after it at once).
+ drop(release);
+ assert_eq!(
+ wait(r, first),
+ Some(Some("https://late.example/a.zip".into()))
+ );
+ woken.recv_timeout(Duration::from_secs(5)).unwrap();
+ // The asks made meanwhile are answered by the next read.
+ let last = r.ask();
+ assert!(wait(r, last).is_some());
+ assert_eq!(
+ prefill.take().as_deref(),
+ Some("https://late.example/a.zip")
+ );
+ assert_eq!(prefill.take(), None, "handed over once");
+ }
+
+ /// An ask is answered by a read that started after it: a text copied just before a dialog
+ /// opens is the one it gets, not an older read's.
+ #[test]
+ fn an_answer_is_never_older_than_its_ask() {
+ let now = Arc::new(Mutex::new("old".to_owned()));
+ let clip = now.clone();
+ let r = Reader::new(move || Some(clip.lock().unwrap().clone()), || {});
+ let first = r.ask();
+ assert_eq!(wait(&r, first), Some(Some("old".into())));
+ *now.lock().unwrap() = "new".into();
+ assert_eq!(
+ r.answer(first),
+ Some(Some("old".into())),
+ "still the old one"
+ );
+ let second = r.ask();
+ assert_eq!(wait(&r, second), Some(Some("new".into())));
+ assert_eq!(r.latest().as_deref(), Some("new"));
+ }
+}
diff --git a/crates/app/src/dialogs.rs b/crates/app/src/dialogs.rs
index 29cb24ae..c92ed702 100644
--- a/crates/app/src/dialogs.rs
+++ b/crates/app/src/dialogs.rs
@@ -611,6 +611,8 @@ pub struct AddUrl {
/// (#511): "Use authorization" shows it while the box is left as it was filled.
looked_up: String,
filled: Option<(String, String)>,
+ /// The clipboard's link, read off the window's thread (#661).
+ clip: crate::clipboard::Prefill,
}
pub struct NewUrl {
@@ -620,21 +622,30 @@ pub struct NewUrl {
impl AddUrl {
/// Opens like IDM's: pre-filled with the clipboard's text when it is an http(s) URL (or a
- /// magnet link: OK then opens Add torrent).
+ /// magnet link: OK then opens Add torrent). The clipboard is read off the window's thread,
+ /// and the address put in the box on the frame it comes ([`AddUrl::fill_from_clipboard`]).
pub fn from_clipboard(history: &[String]) -> Self {
- let clip = crate::clipboard_text().unwrap_or_default();
- let clip = clip.trim();
- let address = match Url::parse(clip) {
- Ok(u) if mdm_engine::supported(&u) || u.scheme() == "magnet" => clip.to_owned(),
- _ => String::new(),
- };
AddUrl {
- address,
history: history.to_vec(),
+ clip: crate::clipboard::Prefill::ask(),
..AddUrl::default()
}
}
+ /// The clipboard's text in the box, when it is an address MDM downloads and the box is
+ /// still empty (nothing typed or picked meanwhile).
+ fn fill_from_clipboard(&mut self, clip: &str) {
+ let clip = clip.trim();
+ if !self.address.is_empty() {
+ return;
+ }
+ if let Ok(u) = Url::parse(clip)
+ && (mdm_engine::supported(&u) || u.scheme() == "magnet")
+ {
+ self.address = clip.to_owned();
+ }
+ }
+
/// "Use authorization" shows the Sites Logins entry the download will use for the address
/// (#511): `site_login` is that same match (`Settings::site_login`). A login typed or
/// changed in the box is left alone; one filled from Options follows the address.
@@ -672,6 +683,9 @@ impl AddUrl {
ctx: &egui::Context,
site_login: impl Fn(&Url) -> Option<(String, String)>,
) -> Outcome<NewUrl> {
+ if let Some(clip) = self.clip.take() {
+ self.fill_from_clipboard(&clip);
+ }
self.follow_site_login(site_login);
window(
ctx,
@@ -3403,6 +3417,94 @@ mod tests {
.expect("Add URL hung");
}
+ /// #661: Add URL asks for the clipboard as it opens and draws its frames without waiting for
+ /// the answer, even from a clipboard owner that never answers; the link fills the box on the
+ /// frame it comes, the caret after it as when it opens with it, and never a box typed in.
+ #[test]
+ fn add_url_never_waits_for_the_clipboard() {
+ use std::time::{Duration, Instant};
+ let (release, stuck) = std::sync::mpsc::channel::<()>();
+ let stuck = std::sync::Mutex::new(stuck);
+ let reader: &'static crate::clipboard::Reader =
+ Box::leak(Box::new(crate::clipboard::Reader::new(
+ move || {
+ let _ = stuck.lock().unwrap().recv();
+ Some(
+ " https://late.example/a.zip
+"
+ .to_owned(),
+ )
+ },
+ || {},
+ )));
+ let ctx = egui::Context::default();
+ let frame = |dlg: &mut AddUrl, events: Vec<egui::Event>| {
+ let input = egui::RawInput {
+ events,
+ ..Default::default()
+ };
+ let mut out = ctx.run_ui(input, |ui| {
+ let _ = dlg.show(ui.ctx(), |_| None);
+ });
+ out.textures_delta.clear();
+ };
+ let mut dlg = AddUrl {
+ clip: crate::clipboard::Prefill::ask_of(reader),
+ ..AddUrl::default()
+ };
+ let mut typed = AddUrl {
+ clip: crate::clipboard::Prefill::ask_of(reader),
+ ..AddUrl::default()
+ };
+ let started = Instant::now();
+ for _ in 0..10 {
+ frame(&mut dlg, vec![]);
+ }
+ assert!(
+ started.elapsed() < Duration::from_secs(5),
+ "10 frames took {:?}",
+ started.elapsed()
+ );
+ assert!(dlg.address.is_empty(), "nothing yet");
+ typed.address = "https://typed.example/b.zip".into();
+ drop(release);
+ let until = Instant::now() + Duration::from_secs(5);
+ while dlg.address.is_empty() && Instant::now() < until {
+ frame(&mut dlg, vec![]);
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ assert_eq!(dlg.address, "https://late.example/a.zip");
+ // The caret is at its end, as in a box that opened with it: typing goes after it.
+ frame(&mut dlg, vec![]);
+ frame(&mut dlg, vec![egui::Event::Text("x".into())]);
+ assert_eq!(dlg.address, "https://late.example/a.zipx");
+ while typed.clip.pending() && Instant::now() < until {
+ frame(&mut typed, vec![]);
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ assert!(!typed.clip.pending(), "answered");
+ assert_eq!(typed.address, "https://typed.example/b.zip", "typed: kept");
+ }
+
+ #[test]
+ fn add_url_takes_only_an_address_it_downloads_from_the_clipboard() {
+ let fill = |clip: &str| {
+ let mut d = AddUrl::default();
+ d.fill_from_clipboard(clip);
+ d.address
+ };
+ assert_eq!(
+ fill(
+ " https://a.example/f.zip
+"
+ ),
+ "https://a.example/f.zip"
+ );
+ assert_eq!(fill("magnet:?xt=urn:btih:ab"), "magnet:?xt=urn:btih:ab");
+ assert_eq!(fill("some words"), "");
+ assert_eq!(fill("mailto:[email protected]"), "");
+ }
+
/// #511: an address with an Options → Sites Logins entry shows that login in "Use
/// authorization" (the match the download uses), follows the address while left as filled,
/// and keeps a login typed in the box. OK hands on only a login of the user's own.
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index 9bd3b1dc..f2256741 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -5,6 +5,7 @@ mod batch;
mod categories;
mod checksum;
mod chrome;
+mod clipboard;
mod clock;
mod countries;
mod crash;
@@ -114,7 +115,8 @@ pub fn offscreen() -> bool {
/// The clipboard's text, if any. Never read in an off-screen run ([`offscreen`]): its windows
/// open from scripts, and the clipboard belongs to the person at the computer (Add URL's
-/// address came from it, and was fetched).
+/// address came from it, and was fetched). It may wait for the clipboard's owner for ever:
+/// never called on the window's thread, only by `clipboard`'s reader (#418, #661).
pub fn clipboard_text() -> Option<String> {
read_clipboard(offscreen(), || {
arboard::Clipboard::new().ok()?.get_text().ok()
@@ -447,6 +449,7 @@ fn app() -> eframe::Result {
win32::set_main_window(cc);
scale::start(&cc.egui_ctx, z);
let _ = window.set(cc.egui_ctx.clone());
+ clipboard::wake(&cc.egui_ctx);
renderer::test_slow_start();
app::App::new(&cc.egui_ctx, handle, commands, sink, loaded, start)
});
diff --git a/crates/app/src/torrentdlg.rs b/crates/app/src/torrentdlg.rs
index 1a93d6cc..a8141df6 100644
--- a/crates/app/src/torrentdlg.rs
+++ b/crates/app/src/torrentdlg.rs
@@ -84,6 +84,8 @@ pub struct TorrentDialog {
/// A .torrent on the web (#39, Add URL or the browser): the request it is fetched with
/// (the browser's cookies). One typed in the box goes as MDM's own downloads do.
remote: Option<crate::torrents::Remote>,
+ /// The clipboard's magnet link, read off the window's thread (#661).
+ clip: crate::clipboard::Prefill,
}
/// The category of a torrent: its largest file's.
@@ -206,7 +208,7 @@ impl TorrentDialog {
/// `source`: a magnet link, a .torrent path or a .torrent's web address (`remote`: how to
/// ask for it) to look up at once, or None (the clipboard's magnet, if any, is offered and
- /// looked up).
+ /// looked up on the frame it comes: the clipboard is read off the window's thread).
#[allow(clippy::too_many_arguments)]
pub fn new(
source: Option<String>,
@@ -218,12 +220,12 @@ impl TorrentDialog {
rt: &tokio::runtime::Handle,
ctx: &egui::Context,
) -> Self {
- let source = source.unwrap_or_else(|| {
- crate::clipboard_text()
- .filter(|t| Source::magnet(t).is_some())
- .map(|t| t.trim().to_owned())
- .unwrap_or_default()
- });
+ let clip = if source.is_none() {
+ crate::clipboard::Prefill::ask()
+ } else {
+ Default::default()
+ };
+ let source = source.unwrap_or_default();
let folder = category_folder(Category::Torrents, &downloads, &category_dirs);
let mut d = TorrentDialog {
source,
@@ -250,6 +252,7 @@ impl TorrentDialog {
asking: None,
asking_files: None,
remote,
+ clip,
};
if !d.source.is_empty() {
d.look_up(rt, ctx);
@@ -257,6 +260,16 @@ impl TorrentDialog {
d
}
+ /// The clipboard's magnet link in the box, when it holds one and the box is still empty
+ /// (nothing typed meanwhile); whether it was put there (and is to be looked up).
+ fn fill_from_clipboard(&mut self, clip: &str) -> bool {
+ let fill = self.source.is_empty() && Source::magnet(clip).is_some();
+ if fill {
+ clip.trim().clone_into(&mut self.source);
+ }
+ fill
+ }
+
fn look_up(&mut self, rt: &tokio::runtime::Handle, ctx: &egui::Context) {
let text = self.source.trim().to_owned();
let magnet = Source::magnet(&text);
@@ -343,6 +356,11 @@ impl TorrentDialog {
ctx: &egui::Context,
rt: &tokio::runtime::Handle,
) -> Outcome<TorrentAdd> {
+ if let Some(clip) = self.clip.take()
+ && self.fill_from_clipboard(&clip)
+ {
+ self.look_up(rt, ctx);
+ }
let looked = self.lookup.as_ref().and_then(|s| s.lock().unwrap().take());
if let Some(res) = looked {
self.lookup = None;
diff --git a/crates/app/src/videodlg.rs b/crates/app/src/videodlg.rs
index 59d77f6c..cec9c7e2 100644
--- a/crates/app/src/videodlg.rs
+++ b/crates/app/src/videodlg.rs
@@ -98,6 +98,8 @@ pub struct VideoDialog {
embed: bool,
/// The last video's choice (settings.video_subs), applied to each video looked up.
pref: Subs,
+ /// The clipboard's page address, read off the window's thread (#661).
+ clip: crate::clipboard::Prefill,
}
/// What is installed in the tools folder: (folder, yt-dlp, ffmpeg).
@@ -136,18 +138,26 @@ fn tools() -> Tools {
}
impl VideoDialog {
- /// Opened from the menu: a video page's address on the clipboard is taken.
+ /// Opened from the menu: a video page's address on the clipboard is taken (read off the
+ /// window's thread, put in the box on the frame it comes).
pub fn new(folder: PathBuf) -> Self {
- let page = crate::clipboard_text()
- .map(|t| t.trim().to_owned())
- .filter(|t| url::Url::parse(t).is_ok_and(|u| matches!(u.scheme(), "http" | "https")))
- .unwrap_or_default();
VideoDialog {
- page,
+ clip: crate::clipboard::Prefill::ask(),
..Self::blank(folder)
}
}
+ /// The clipboard's text as the page, when it is a web address and the box is still empty
+ /// (nothing typed meanwhile).
+ fn fill_from_clipboard(&mut self, clip: &str) {
+ let clip = clip.trim();
+ if self.page.is_empty()
+ && url::Url::parse(clip).is_ok_and(|u| matches!(u.scheme(), "http" | "https"))
+ {
+ self.page = clip.to_owned();
+ }
+ }
+
/// No address yet, saving into `folder` (the Video category's).
fn blank(folder: PathBuf) -> Self {
let folder = folder.display().to_string();
@@ -180,6 +190,7 @@ impl VideoDialog {
sub_pick: 0,
embed: false,
pref: Subs::default(),
+ clip: Default::default(),
}
}
@@ -349,6 +360,9 @@ impl VideoDialog {
}
pub fn show(&mut self, ctx: &egui::Context, rt: &tokio::runtime::Handle) -> Outcome<VideoOut> {
+ if let Some(clip) = self.clip.take() {
+ self.fill_from_clipboard(&clip);
+ }
// Results from the background work.
let looked = self.lookup.as_ref().and_then(|s| s.lock().unwrap().take());
if let Some(res) = looked {
@@ -1523,6 +1537,27 @@ mod tests {
assert!(auto.automatic && auto.embed);
}
+ /// #661: a page's address from the clipboard comes a frame or more after the window opens:
+ /// it fills an empty box only, and only with a web address.
+ #[test]
+ fn the_clipboard_fills_only_an_empty_page_box() {
+ let (video, _) = dirs();
+ let mut d = VideoDialog::blank(video.clone());
+ d.fill_from_clipboard(
+ " https://video.example/talk
+",
+ );
+ assert_eq!(d.page, "https://video.example/talk");
+ d.fill_from_clipboard("https://video.example/other");
+ assert_eq!(
+ d.page, "https://video.example/talk",
+ "not over what is there"
+ );
+ let mut d = VideoDialog::blank(video);
+ d.fill_from_clipboard("ftp://files.example/a.mp4");
+ assert_eq!(d.page, "");
+ }
+
/// The Video and Music categories' folders (not made: only their names are compared).
fn dirs() -> (PathBuf, PathBuf) {
let base = std::env::temp_dir().join("mdm-611");
diff --git a/crates/app/src/winui.rs b/crates/app/src/winui.rs
index 8c7c23f9..e76e220a 100644
--- a/crates/app/src/winui.rs
+++ b/crates/app/src/winui.rs
@@ -2152,6 +2152,18 @@ fn edit_text_with(
ui.memory_mut(|m| m.request_focus(edit_id));
}
}
+ // A box that was empty and is then filled by its window, not typed in (a link from the
+ // clipboard, read off the window's thread, comes a frame or two after the window opens:
+ // #661), has its caret where it would be had it opened with the text (at its end), not left
+ // at its start.
+ let was_empty = edit_id.with("was-empty");
+ if !value.is_empty() && ui.data(|d| d.get_temp::<bool>(was_empty)).is_some() {
+ ui.data_mut(|d| d.remove::<bool>(was_empty));
+ if let Some(mut state) = egui::text_edit::TextEditState::load(ui.ctx(), edit_id) {
+ state.cursor.set_char_range(None);
+ state.store(ui.ctx(), edit_id);
+ }
+ }
let te = egui::TextEdit::singleline(value)
.id(edit_id)
.align(egui::Align2([align, egui::Align::TOP]))
@@ -2242,6 +2254,9 @@ fn edit_text_with(
)));
state.store(ui.ctx(), edit_id);
}
+ if value.is_empty() && ui.data(|d| d.get_temp::<bool>(was_empty)).is_none() {
+ ui.data_mut(|d| d.insert_temp(was_empty, true));
+ }
if enabled {
edit_menu(&resp, value, password, false);
}
@@ -2378,15 +2393,26 @@ pub fn edit_menu(resp: &Response, value: &mut String, password: bool, multiline:
let ctx = resp.ctx.clone();
let id = resp.id;
let key = id.with("edit-menu");
+ // Paste is offered when the clipboard has text: asked as the menu opens, read off the
+ // window's thread (clipboard.rs; read here at every frame, a clipboard owner that hung froze
+ // the window, #661).
+ let clip_key = key.with("clipboard");
+ let open_at = |p: Pos2| {
+ let ask = crate::clipboard::ask();
+ ctx.data_mut(|d| {
+ d.insert_temp(key, p);
+ d.insert_temp(clip_key, ask);
+ });
+ };
if resp.secondary_clicked()
&& let Some(p) = resp.interact_pointer_pos()
{
- ctx.data_mut(|d| d.insert_temp(key, p));
+ open_at(p);
}
// Shift+F10 (the keyboard's way to a right-click menu) opens it under the box.
if resp.has_focus() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F10))
{
- ctx.data_mut(|d| d.insert_temp(key, resp.rect.left_bottom()));
+ open_at(resp.rect.left_bottom());
}
let Some(at) = ctx.data(|d| d.get_temp::<Pos2>(key)) else {
return;
@@ -2402,7 +2428,13 @@ pub fn edit_menu(resp: &Response, value: &mut String, password: bool, multiline:
})
.unwrap_or((n, n));
let has = a < b;
- let clip = crate::clipboard_text().filter(|t| !t.is_empty());
+ // Until the answer comes (a frame or two; never, from an owner that hung), what the
+ // clipboard last held.
+ let clip = ctx
+ .data(|d| d.get_temp::<crate::clipboard::Ask>(clip_key))
+ .and_then(crate::clipboard::answer)
+ .unwrap_or_else(crate::clipboard::latest)
+ .filter(|t| !t.is_empty());
// egui's own undo history (Ctrl+Z uses it too).
let mut undoer = state.undoer();
let now = (state.cursor.char_range().unwrap_or_default(), value.clone());
@@ -2428,7 +2460,10 @@ pub fn edit_menu(resp: &Response, value: &mut String, password: bool, multiline:
PopupResult::Dismissed => None,
PopupResult::Chosen(c) => Some(c),
};
- ctx.data_mut(|d| d.remove::<Pos2>(key));
+ ctx.data_mut(|d| {
+ d.remove::<Pos2>(key);
+ d.remove::<crate::clipboard::Ask>(clip_key);
+ });
let Some(cmd) = cmd else { return };
let byte = |c: usize| value.char_indices().nth(c).map_or(value.len(), |(i, _)| i);
let (ba, bb) = (byte(a), byte(b));