// 傳送 in the window: pick a device of the account (a computer, the phone), then drop files on // the dialog, choose them, or paste a few words. Below: what was sent and what arrived in the // last 7 days, with where each one is. What arrives on this computer is announced here too // (words go on the clipboard). The carrying itself is drops.rs. use super::sidebar_ui::shorten_width; use super::*; use serde_json::{json, Value}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{channel, Receiver}; const PAGE_W: f32 = 560.0; struct Job { name: String, total: u64, sent: Arc, rx: Receiver>, } pub struct DropPage { /// The chosen destination (its id). to: String, targets: Vec, you: String, rx_targets: Option>, items: Vec, rx_list: Option>, asked: Instant, text: String, jobs: Vec, picked: Option>>, note: String, loaded: bool, } impl DropPage { fn new() -> Self { DropPage { to: String::new(), targets: vec![], you: String::new(), rx_targets: None, items: vec![], rx_list: None, asked: Instant::now(), text: String::new(), jobs: vec![], picked: None, note: String::new(), loaded: false } } /// Already filled (screenshots). pub fn shown(targets: Vec, items: Vec, you: &str, to: &str) -> Self { DropPage { targets, items, you: you.into(), to: to.into(), loaded: true, ..Self::new() } } } /// What a parcel's row says about where it is. pub(crate) fn state_words(p: &Value, now: i64) -> (String, bool) { let pct = |p: &Value| { let (a, b) = (p["sent"].as_u64().unwrap_or(0), p["bytes"].as_u64().unwrap_or(0).max(1)); (a * 100 / b).min(100) }; let to = p["to_name"].as_str().unwrap_or(""); let note = p["note"].as_str().unwrap_or(""); match p["state"].as_str().unwrap_or("") { "uploading" => (format!("{} {}%", t("正在交給大腦"), pct(p)), false), "waiting" if note.contains("更新") => (note.to_string(), false), "waiting" => (format!("{}「{to}」{}", t("等"), t("開機上線,會自動送達")), false), "sending" => (format!("{} {}%", t("傳送中"), pct(p)), false), "ready" => (t("在手機的「傳送」裡可以拿(保留 7 天)"), false), "done" => (format!("{} · {}", t(if p["to"] == crate::drops::PHONE && p["text"].as_str().unwrap_or("").is_empty() { "手機已下載" } else { "已送達" }), crate::pages::ago(p["at"].as_i64().unwrap_or(0), now)), false), _ => (format!("{}:{}", t("沒有送達"), if note.is_empty() { t("不知道原因") } else { note.to_string() }), true), } } impl App { fn drop_call(&self, what: &'static str, method: &'static str, body: Value) -> Receiver { let (tx, rx) = channel(); let repaint = self.repaint_fn(); let (s, mirror) = (self.state.remote.clone(), self.mir.on); std::thread::spawn(move || { let b = if method == "GET" { vec![] } else { body.to_string().into_bytes() }; let _ = tx.send(crate::drops::ask(&s, mirror, what, method, &[], &b).unwrap_or_else(|e| json!({"error": e}))); repaint(); }); rx } pub(super) fn open_drops(&mut self) { self.drop_page = Some(DropPage::new()); } fn drop_send_files(&mut self, pg: &mut DropPage, paths: Vec) { if pg.to.is_empty() { pg.note = t("先選要傳到哪一台"); return; } pg.note.clear(); for path in paths { let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let total = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); let sent = Arc::new(AtomicU64::new(0)); let (tx, rx) = channel(); let repaint = self.repaint_fn(); let (s, mirror, to, sent2) = (self.state.remote.clone(), self.mir.on, pg.to.clone(), sent.clone()); std::thread::spawn(move || { let _ = tx.send(crate::drops::send_file(&s, mirror, &path, &to, &sent2)); repaint(); }); pg.jobs.push(Job { name, total, sent, rx }); } } /// Every frame, the window open or not: what arrived on this computer since the last look. pub(super) fn drops_tick(&mut self, ctx: &egui::Context) { if self.demo { return; } let fresh = crate::drops::office().take_fresh(); if fresh.is_empty() { return; } // Words the person sent here are for pasting: the newest goes on the clipboard. if let Some(r) = fresh.iter().rev().find(|r| !r.text.is_empty()) { crate::platform::copy_text(&ctx, &r.text); } if !self.headless && self.state.alert_sound { crate::voice::chime(); } if let Some(pg) = self.drop_page.as_mut() { pg.asked = Instant::now() - std::time::Duration::from_secs(60); } } pub(super) fn drops_page(&mut self, ctx: &egui::Context) { let Some(mut pg) = self.drop_page.take() else { return }; let p = self.pal; // Answers. if let Some(rx) = &pg.rx_targets { if let Ok(v) = rx.try_recv() { pg.rx_targets = None; if let Some(e) = v["error"].as_str() { pg.note = e.to_string(); } else { pg.you = v["you"].as_str().unwrap_or("").to_string(); pg.targets = v["targets"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["id"].as_str() != Some(pg.you.as_str())).collect(); if !pg.targets.iter().any(|t| t["id"].as_str() == Some(pg.to.as_str())) { // The one used last time, else the first that is on. let last = self.drop_last.clone(); pg.to = pg.targets.iter().find(|t| t["id"].as_str() == Some(last.as_str())).or_else(|| pg.targets.iter().find(|t| t["online"] == true)).and_then(|t| t["id"].as_str()).unwrap_or("").to_string(); } } pg.loaded = true; } } if let Some(rx) = &pg.rx_list { if let Ok(v) = rx.try_recv() { pg.rx_list = None; if v.get("error").is_none() { pg.items = v["items"].as_array().cloned().unwrap_or_default(); } } } let mut finished = false; pg.jobs.retain(|j| match j.rx.try_recv() { Ok(r) => { if let Err(e) = r { pg.note = e; } finished = true; false } Err(_) => true, }); if let Some(rx) = &pg.picked { if let Ok(paths) = rx.try_recv() { pg.picked = None; self.drop_send_files(&mut pg, paths); } } // Files dropped on the window while this is open are for sending (not for the chat). let dropped: Vec = ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty()).collect()); if !dropped.is_empty() { self.drop_send_files(&mut pg, dropped); } // Asking: the devices once (and every 15 s), the list while something is moving. let shot = self.demo; if !shot { if !pg.loaded && pg.rx_targets.is_none() { pg.rx_targets = Some(self.drop_call("targets", "GET", Value::Null)); pg.asked = Instant::now() - std::time::Duration::from_secs(60); } let moving = !pg.jobs.is_empty() || pg.items.iter().any(|i| matches!(i["state"].as_str(), Some("uploading" | "sending" | "waiting"))); let every = std::time::Duration::from_millis(if moving { 1000 } else { 5000 }); if (finished || pg.asked.elapsed() >= every) && pg.rx_list.is_none() { pg.asked = Instant::now(); pg.rx_list = Some(self.drop_call("list", "GET", Value::Null)); if pg.rx_targets.is_none() && pg.loaded { pg.rx_targets = Some(self.drop_call("targets", "GET", Value::Null)); } } ctx.request_repaint_after(if moving { std::time::Duration::from_millis(250) } else { every }); } // A steady height: the list arrives after the first frame. let max_h = dialog_max_height(ctx).min(620.0) - 60.0; let mut acts: Vec<(&'static str, String)> = vec![]; let close = dialog(ctx, "drops", "傳送到其他裝置", PAGE_W, true, p, |ui| { egui::ScrollArea::vertical().id_salt("drops-page").max_height(max_h).min_scrolled_height(max_h).auto_shrink([false, false]).show(ui, |ui| { Frame::new().inner_margin(Margin { left: 20, right: 20, top: 14, bottom: 18 }).show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = 6.0; self.drops_body(ui, &mut pg, &mut acts); }); }); }); for (what, id) in acts { match what { "reveal" => crate::preview::reveal(std::path::Path::new(&id)), "copy" => crate::platform::copy_text(&ctx, &id), "pick" => { let (tx, rx) = channel(); pg.picked = Some(rx); let c = ctx.clone(); std::thread::spawn(move || { let _ = tx.send(crate::attach::pick_files()); c.request_repaint(); }); } "text" => { let (s, mirror, to, repaint) = (self.state.remote.clone(), self.mir.on, pg.to.clone(), self.repaint_fn()); let (tx, rx) = channel(); let sent = Arc::new(AtomicU64::new(0)); let n = id.len() as u64; std::thread::spawn(move || { let _ = tx.send(crate::drops::send_text(&s, mirror, &id, &to)); repaint(); }); pg.jobs.push(Job { name: t("一段文字"), total: n, sent, rx }); } w => { let w = if w == "retry" { "retry" } else { "remove" }; pg.items.retain(|i| w == "retry" || i["id"].as_str() != Some(id.as_str())); let _ = self.drop_call(w, "POST", json!({"id": id})); pg.asked = Instant::now() - std::time::Duration::from_secs(60); } } } if !pg.to.is_empty() { self.drop_last = pg.to.clone(); } if !close { self.drop_page = Some(pg); } } fn drops_body(&mut self, ui: &mut egui::Ui, pg: &mut DropPage, acts: &mut Vec<(&'static str, String)>) { let p = self.pal; let now = crate::model::now_ms(); if self.state.remote.relay_url.is_empty() && !self.demo { ui.label(RichText::new(t("還沒登入帳號:現在只能和直接連到這台的手機互傳。登入帳號後,帳號裡每一台都能互傳(設定 › 一般 › 手機與帳號)。")).size(FONT_XS).color(p.text3)); ui.add_space(4.0); } // Where to. ui.label(RichText::new(t("傳到")).size(FONT_XS).color(p.text3)); if !pg.loaded { ui.label(RichText::new(t("正在找帳號裡的裝置…")).size(FONT_SM).color(p.text3)); } else if pg.targets.is_empty() { ui.label(RichText::new(t("帳號裡還沒有其他裝置。")).size(FONT_SM).color(p.text3)); } ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(6.0, 6.0); for tg in &pg.targets { let id = tg["id"].as_str().unwrap_or(""); let on = pg.to == id; let online = tg["online"] == true; let name = tg["name"].as_str().unwrap_or(""); let name = if tg["kind"] == "phone" { t(name) } else { name.to_string() }; let label = if online { name } else { format!("{name} · {}", t("離線")) }; let (fill, stroke, ink) = if on { (p.accent.gamma_multiply(0.14), Stroke::new(1.0, p.accent.gamma_multiply(0.7)), p.text) } else { (Color32::TRANSPARENT, Stroke::new(1.0, p.border), if online { p.text2 } else { p.text3 }) }; let r = ui.add(egui::Button::new(RichText::new(label).size(FONT_SM).color(ink)).fill(fill).stroke(stroke).corner_radius(R_L).min_size(vec2(0.0, 30.0))); let r = if online { r } else { r.on_hover_text(t("現在沒開:先交給大腦,它一上線就會收到(保留 7 天)")) }; if r.clicked() { pg.to = id.to_string(); pg.note.clear(); } } }); ui.add_space(8.0); // The place to drop files. let hovering = ui.ctx().input(|i| !i.raw.hovered_files.is_empty()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 104.0), egui::Sense::hover()); ui.painter().rect_filled(rect, R_L, if hovering { p.accent.gamma_multiply(0.10) } else { p.hover.gamma_multiply(0.5) }); ui.painter().rect_stroke(rect, R_L, Stroke::new(if hovering { 1.6 } else { 1.0 }, if hovering { p.accent } else { p.border }), egui::StrokeKind::Inside); crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 26.0), vec2(20.0, 20.0)), crate::icons::Icon::Upload, if hovering { p.accent } else { p.text3 }); ui.painter().text(rect.center_top() + vec2(0.0, 50.0), egui::Align2::CENTER_CENTER, t(if hovering { "放開就傳送" } else { "把檔案拖到這裡" }), egui::FontId::proportional(FONT_BASE), p.text2); let btn = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 78.0), vec2(96.0, 26.0)); if ui.put(btn, egui::Button::new(RichText::new(t("選擇檔案…")).size(FONT_SM)).corner_radius(R_M)).clicked() { if pg.to.is_empty() { pg.note = t("先選要傳到哪一台"); } else { acts.push(("pick", String::new())); } } // (A widget put inside the zone moved the cursor up to its own bottom.) ui.advance_cursor_after_rect(rect); ui.add_space(4.0); // Or a few words (an address, a code, a paragraph): they land on the other clipboard. ui.horizontal(|ui| { let w = ui.available_width() - 78.0; let r = ui.add_sized([w, 30.0], egui::TextEdit::singleline(&mut pg.text).hint_text(t("或貼上一段文字、網址(對方收到就在剪貼簿裡)")).margin(Margin::symmetric(10, 6))); let enter = r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); if (ui.add(primary_button("傳送", p)).clicked() || enter) && !pg.text.trim().is_empty() { if pg.to.is_empty() { pg.note = t("先選要傳到哪一台"); } else { acts.push(("text", std::mem::take(&mut pg.text))); } } }); if !pg.note.is_empty() { ui.label(RichText::new(&pg.note).size(FONT_SM).color(p.danger)); } // On their way from this computer. for j in &pg.jobs { let done = j.sent.load(Ordering::Relaxed); let frac = if j.total == 0 { 0.0 } else { (done as f32 / j.total as f32).clamp(0.0, 1.0) }; ui.add_space(4.0); ui.horizontal(|ui| { ui.label(RichText::new(shorten_width(ui, &j.name, ui.available_width() - 150.0, 13.0)).size(FONT_SM).color(p.text)); ui.label(RichText::new(format!("{} / {}", crate::attach::human(done), crate::attach::human(j.total))).size(FONT_XS).color(p.text3)); }); let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 4.0), egui::Sense::hover()); ui.painter().rect_filled(bar, R_S, p.border); ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * frac, 4.0)), 2, p.accent); } // What went and what came. if pg.items.is_empty() { return; } ui.add_space(12.0); ui.label(RichText::new(t("最近 7 天")).size(FONT_XS).color(p.text3)); let here: HashMap = if self.demo { HashMap::new() } else { crate::drops::office().received().into_iter().map(|r| (r.id, r.path)).collect() }; for it in pg.items.iter().take(40) { let id = it["id"].as_str().unwrap_or("").to_string(); let words = it["text"].as_str().unwrap_or(""); let (state, bad) = state_words(it, now); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), egui::Sense::hover()); let icon = if !words.is_empty() { crate::icons::Icon::Copy } else { match crate::preview::kind_of(it["name"].as_str().unwrap_or("")) { "image" => crate::icons::Icon::FileImage, "video" => crate::icons::Icon::FileVideo, "audio" => crate::icons::Icon::FileAudio, "sheet" | "csv" => crate::icons::Icon::FileSheet, "code" | "html" => crate::icons::Icon::FileCode, "text" | "markdown" | "pdf" | "doc" => crate::icons::Icon::FileText, _ => crate::icons::Icon::File, } }; crate::icons::paint(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(12.0, 0.0), vec2(18.0, 18.0)), icon, p.text3); // Buttons on the right, then the words in what is left. let mut right = rect.right(); let mut button = |ui: &mut egui::Ui, label: &str, w: f32| -> bool { let r = egui::Rect::from_min_size(egui::pos2(right - w, rect.center().y - 13.0), vec2(w, 26.0)); right -= w + 6.0; ui.put(r, egui::Button::new(RichText::new(t(label)).size(FONT_XS)).corner_radius(R_M)).clicked() }; if button(ui, "移除", 44.0) { acts.push(("remove", id.clone())); } if bad && button(ui, "再試一次", 68.0) { acts.push(("retry", id.clone())); } if !words.is_empty() { if button(ui, "複製", 44.0) { acts.push(("copy", words.to_string())); } } else if let Some(path) = here.get(&id).filter(|f| std::path::Path::new(f).exists()) { if button(ui, "顯示", 44.0) { acts.push(("reveal", path.clone())); } } let tx = rect.left() + 30.0; let max_w = (right - tx - 6.0).max(60.0); let name = shorten_width(ui, it["name"].as_str().unwrap_or(""), max_w, 13.5); ui.painter().text(egui::pos2(tx, rect.top() + 6.0), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(FONT_SM), p.text); let size = if words.is_empty() { format!("{} · ", crate::attach::human(it["bytes"].as_u64().unwrap_or(0))) } else { String::new() }; let to = it["to_name"].as_str().unwrap_or(""); let to = if it["to"] == crate::drops::PHONE { t(to) } else { to.to_string() }; let sub = format!("{size}{} → {to} · {state}", it["from"].as_str().unwrap_or("")); let sub = shorten_width(ui, &sub, max_w, 11.5); ui.painter().text(egui::pos2(tx, rect.top() + 26.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(FONT_XS), if bad { p.danger } else { p.text3 }); ui.advance_cursor_after_rect(rect); } } } #[cfg(test)] mod tests { use super::*; #[test] fn a_row_says_where_the_parcel_is() { let now = crate::model::now_ms(); let row = |state: &str, note: &str| json!({"state": state, "note": note, "sent": 1, "bytes": 4, "to_name": "Mac mini", "at": now}); // (The words follow the menus' language, which other tests may set: compare through t().) assert_eq!(state_words(&row("uploading", ""), now), (format!("{} 25%", t("正在交給大腦")), false)); assert_eq!(state_words(&row("sending", ""), now), (format!("{} 25%", t("傳送中")), false)); assert!(state_words(&row("waiting", "目前離線"), now).0.contains(&format!("{}「Mac mini」", t("等")))); assert!(state_words(&row("waiting", "「Mac mini」的 AnyBot 要先更新才收得到"), now).0.contains("要先更新")); assert_eq!(state_words(&row("done", ""), now), (format!("{} · {}", t("已送達"), crate::pages::ago(now, now)), false)); assert_eq!(state_words(&row("failed", "磁碟滿了"), now), (format!("{}:{}", t("沒有送達"), "磁碟滿了"), true)); } }