// 每個 Bot 一個螢幕, as the window shows it (Grok Bot's split: one computer for the account, a // screen of its own for each bot; cloudbox has the box's side). // // - The 電腦 card shows the selected bot's own screen. In a group chat it is the member speaking, // unless the person picked a member (the small pictures in the 成員 card). // - 全部螢幕: every screen open on the bots' computer, a small live picture each; a click opens // that screen to watch or take over. // - On the brain, every few seconds: which bot is on which screen (what viewers from the phone, // a screen computer or the account server go by), the screens open now, and the idle ones closed. use super::*; use crate::cloudbox; /// A bot's own screen on the bots' computer nobody used this long is closed (its browser too). const SCREEN_IDLE_SECS: u64 = 600; /// How often the small pictures of 全部螢幕 and the 成員 card are taken again. const TILE_EVERY: u64 = 3; /// Their width in pixels. const TILE_W: u32 = 240; #[derive(Default)] pub struct ScreensUi { /// 全部螢幕 is open. pub(super) open: bool, /// In a group chat (its id), the member whose screen the 電腦 card shows: picked by the /// person; none, the member speaking. pub(super) pick: HashMap, /// The screen the person took over (bot, screen), to give that one back. pub(super) held: Option<(u64, String)>, /// The small pictures, by bot. tiles: HashMap, fresh: Arc>>, busy: Arc, tiles_at: Option, /// When the brain last told the box which bot is on which screen, looked at the screens open, /// and swept idle ones. mapped_at: Option, listed_at: Option, listing: Arc, reaped_at: Option, } /// One open screen: whose it is, and how long since a bot used it. #[derive(Clone, Debug, PartialEq)] pub(super) struct Tile { pub bot: u64, pub name: String, pub idle: u64, } impl App { /// The screen to show for `bot_id` on the bots' computer: its own, by the folder it works in; /// a 支線's temporary one; in a group chat the member speaking now, else the first member. /// "" when it isn't a bot. pub(super) fn screen_key_for(&self, bot_id: u64) -> String { let Some(b) = self.state.bot(bot_id) else { return String::new() }; if b.branch_of != 0 { return cloudbox::branch_screen(&cloudbox::screen_of_bot(b.branch_of), bot_id); } let who = if b.members.is_empty() { bot_id } else { b.messages.iter().rev().find(|m| m.role == Role::Assistant && m.author != 0).map(|m| m.author).or_else(|| b.members.first().copied()).unwrap_or(bot_id) }; cloudbox::screen_of_bot(self.state.home_of(who)) } /// Whose screen the 電腦 card shows for `bot_id`: in a group chat the member the person /// picked (when still a member), else `bot_id` itself (screen_key_for goes on from there). pub(super) fn shown_bot(&self, bot_id: u64) -> u64 { let members = self.state.bot(bot_id).map(|b| b.members.clone()).unwrap_or_default(); self.cu.screens.pick.get(&bot_id).copied().filter(|m| members.contains(m)).unwrap_or(bot_id) } /// On the brain: tell the box side which bot is on which screen, look at the screens open, /// and close the screens no bot used for 10 minutes (their browsers too; the profiles stay). pub(super) fn tend_screens(&mut self) { if self.mir.on || self.demo { return; } let s = &mut self.cu.screens; if !s.mapped_at.is_some_and(|t| t.elapsed().as_secs() < 2) { s.mapped_at = Some(Instant::now()); let ids: Vec = self.state.bots.iter().chain(self.state.branch_bots.iter()).map(|b| b.id).collect(); let map = ids.into_iter().map(|id| (id, self.screen_key_for(id))).collect(); cloudbox::set_bot_screens(map); } // (A box that stopped has none open: the list empties without asking it.) let s = &mut self.cu.screens; if !s.listed_at.is_some_and(|t| t.elapsed().as_secs() < 5) && !s.listing.swap(true, Ordering::SeqCst) { s.listed_at = Some(Instant::now()); let busy = s.listing.clone(); std::thread::spawn(move || { cloudbox::refresh_open_screens(); busy.store(false, Ordering::SeqCst); }); } if !s.reaped_at.is_some_and(|t| t.elapsed().as_secs() < 60) && cloudbox::run_state().is_running() { s.reaped_at = Some(Instant::now()); std::thread::spawn(|| cloudbox::reap_screens(SCREEN_IDLE_SECS)); } } /// The screens open on the bots' computer here, by bot (a 支線's under its bot's name). pub(super) fn local_tiles(&self) -> Vec { cloudbox::open_screens_seen() .into_iter() .filter_map(|(key, idle)| { let (own, branch) = cloudbox::bot_of_screen(&key)?; let (bot, name) = if branch != 0 { (branch, format!("{}(支線)", self.state.bot(branch)?.name)) } else { (own, self.state.bots.iter().find(|b| b.id == own && b.members.is_empty())?.name.clone()) }; Some(Tile { bot, name, idle }) }) .collect() } /// The screens open on the bots' computer (on a screen of a brain: the brain's, as it said). pub(super) fn screen_tiles(&self) -> Vec { if !self.mir.on { return self.local_tiles(); } self.mir.box_state["screens"] .as_array() .map(|a| a.iter().filter_map(|t| Some(Tile { bot: t["bot"].as_u64()?, name: t["name"].as_str()?.to_string(), idle: t["idle"].as_u64().unwrap_or(0) })).collect()) .unwrap_or_default() } /// What a screen of this brain is told about the screens open (its 全部螢幕). pub(super) fn tiles_json(&self) -> serde_json::Value { self.local_tiles().iter().map(|t| serde_json::json!({"bot": t.bot, "name": t.name, "idle": t.idle})).collect() } /// The small picture of `bot`'s screen, when there is one (screens_frame keeps it fresh). pub(super) fn screen_tile(&self, bot: u64) -> Option<(egui::TextureId, egui::Vec2)> { self.cu.screens.tiles.get(&bot).map(|t| (t.id(), t.size_vec2())) } /// Pictures of the bots in `wanted` taken again every few seconds (in the background; on a /// screen of a brain, from it). fn refresh_tiles(&mut self, ctx: &egui::Context, wanted: &[u64]) { let s = &mut self.cu.screens; for (bot, img) in std::mem::take(&mut *s.fresh.lock().unwrap()) { match s.tiles.get_mut(&bot) { Some(t) => t.set(img, egui::TextureOptions::LINEAR), None => { s.tiles.insert(bot, ctx.load_texture(format!("screen-tile-{bot}"), img, egui::TextureOptions::LINEAR)); } } } if wanted.is_empty() { return; } ctx.request_repaint_after(std::time::Duration::from_secs(TILE_EVERY)); if s.tiles_at.is_some_and(|t| t.elapsed().as_secs() < TILE_EVERY) || s.busy.swap(true, Ordering::SeqCst) { return; } s.tiles_at = Some(Instant::now()); let (fresh, busy, c) = (s.fresh.clone(), s.busy.clone(), ctx.clone()); let brain = self.mir.on.then(|| self.state.remote.clone()); let jobs: Vec<(u64, String)> = wanted.iter().map(|&b| (b, self.screen_key_for(b))).collect(); std::thread::spawn(move || { for (bot, key) in jobs { let img = match &brain { Some(s) => crate::remote::sync_screen(s, true, bot).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), None if key.is_empty() => None, None => cloudbox::thumbnail_of(&key, TILE_W), }; if let Some(img) = img { let size = [img.width() as usize, img.height() as usize]; fresh.lock().unwrap().push((bot, egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()))); c.request_repaint(); } } busy.store(false, Ordering::SeqCst); }); } /// Every frame: the pictures shown now (全部螢幕, the 成員 card of the group chat open) kept /// fresh, and 全部螢幕 itself. pub(super) fn screens_frame(&mut self, ctx: &egui::Context) { let tiles = self.screen_tiles(); let mut wanted: Vec = vec![]; if self.cu.screens.open { wanted.extend(tiles.iter().map(|t| t.bot)); } if let Some(b) = self.state.bot(self.state.selected).filter(|b| !b.members.is_empty()) { wanted.extend(b.members.iter().filter(|m| tiles.iter().any(|t| t.bot == **m))); } wanted.sort_unstable(); wanted.dedup(); self.refresh_tiles(ctx, &wanted); if self.cu.screens.open { self.screens_window(ctx, &tiles); } } /// 全部螢幕: a small live picture of each screen open; a click opens it. fn screens_window(&mut self, ctx: &egui::Context, tiles: &[Tile]) { let p = self.pal; let mut view: Option = None; let pictures: Vec> = tiles.iter().map(|t| self.screen_tile(t.bot)).collect(); let dismissed = dialog(ctx, "all-screens", &t("全部螢幕"), 560.0, true, p, |ui| { if tiles.is_empty() { ui.label(RichText::new(t("現在沒有 Bot 開著自己的螢幕。Bot 第一次看畫面或用瀏覽器時才會開,閒置 10 分鐘自動關掉。")).color(p.text2)); return; } hint(ui, t("每個 Bot 在 Bot 的電腦上有自己的螢幕,互不干擾。點一格看它的畫面,也可以在那裡接手。"), p); ui.add_space(6.0); let w = 256.0; let cols = ((ui.available_width() + 12.0) / (w + 12.0)).floor().max(1.0) as usize; egui::Grid::new("all-screens-grid").spacing(vec2(12.0, 12.0)).show(ui, |ui| { for (i, (tile, pic)) in tiles.iter().zip(&pictures).enumerate() { let (rect, r) = ui.allocate_exact_size(vec2(w, w * 10.0 / 16.0 + 40.0), egui::Sense::click()); let shot = egui::Rect::from_min_size(rect.min, vec2(w, w * 10.0 / 16.0)); match pic { Some((tex, size)) => egui::Image::new((*tex, *size)).fit_to_exact_size(shot.size()).corner_radius(R_M).paint_at(ui, shot), None => { ui.painter().rect_filled(shot, R_M, p.active); } } ui.painter().rect_stroke(shot, R_M, Stroke::new(if r.hovered() { 2.0 } else { 1.0 }, if r.hovered() { p.accent } else { p.border }), egui::StrokeKind::Inside); let when = if tile.idle < 60 { t("剛剛還在用") } else { t("閒置 {n} 分鐘").replace("{n}", &(tile.idle / 60).to_string()) }; ui.painter().text(shot.left_bottom() + vec2(2.0, 8.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, &tile.name, w - 4.0, 13.0), egui::FontId::proportional(FONT_SM), p.text); ui.painter().text(shot.left_bottom() + vec2(2.0, 25.0), egui::Align2::LEFT_TOP, when, egui::FontId::proportional(FONT_XS), p.text3); if r.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("看「{name}」的螢幕,也可以取得控制權自己操作").replace("{name}", &tile.name)).clicked() { view = Some(tile.bot); } if (i + 1) % cols == 0 { ui.end_row(); } } }); }); if dismissed { self.cu.screens.open = false; } if let Some(bot) = view { self.open_screen_of(bot, false); } } } #[cfg(test)] mod tests { use super::*; #[test] fn a_branch_and_a_picked_member_have_their_own_screens() { let ctx = egui::Context::default(); let mut app = super::super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-screens-ui.png"))); let (a, b) = (app.state.bots[0].id, app.state.bots[1].id); let mut branch = app.state.bot(a).cloned().unwrap(); branch.id = 9_001; branch.branch_of = a; app.state.branch_bots.push(branch); assert_eq!(app.screen_key_for(a), format!("bot{a}")); assert_eq!(app.screen_key_for(9_001), format!("bot{a}-t9001"), "a branch beside its main bot"); assert_eq!(cloudbox::bot_of_screen(&format!("bot{a}-t9001")), Some((a, 9_001))); assert_eq!(cloudbox::bot_of_screen(&format!("bot{b}")), Some((b, 0))); assert_eq!(cloudbox::bot_of_screen("main"), None); // A group chat shows the member speaking; one the person picked instead. let mut group = app.state.bots[0].clone(); group.id = 9_002; group.members = vec![a, b]; group.messages = vec![Message { author: b, ..Message::assistant("我來", "") }]; app.state.bots.push(group); let g = 9_002; assert_eq!(app.screen_key_for(g), format!("bot{b}")); assert_eq!(app.shown_bot(g), g); app.cu.screens.pick.insert(g, a); assert_eq!(app.screen_key_for(app.shown_bot(g)), format!("bot{a}")); // (Not a member any more: back to the one speaking.) app.state.bot_mut(g).unwrap().members.retain(|m| *m != a); assert_eq!(app.shown_bot(g), g); } }