diff --git a/FEATURES.md b/FEATURES.md index 49fb30a..5ae4fd7 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -2440,7 +2440,9 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) 推播內容只有手機解得開(Web Push 加密),點通知會直接打開那個 Bot 的聊天。 -通知像那個 Bot 傳來的訊息:標題就是 Bot 的名字,內容就是那句話,不加別的——做完了是它回答的第一行(沒有字的寫「做完了」),要你允許是「需要你允許:修改 Bot 自己:名稱 → 新名字」(整段原因接成一行,不是停在冒號的第一行),要你處理是「需要你處理:…」,問你就是那個問題,例行任務暫停是「例行任務「…」連續失敗…」,目標是「目標達成…/目標暫停…」;別台裝置傳來的檔案,標題是那台裝置的名字。以前標題是「○○ 完成了」「○○ 需要你允許」這種。圖示:iPhone 的網頁 App 一律用 App 的圖示,最上面的 App 名稱那行(「from AnyBot」)也是系統加的,網頁推播換不掉、拿不掉(iOS 不理通知裡指定的 icon);Bot 的頭像要原生 App 才放得上去。電腦上的通知照舊。等你的卡(允許、問你、需要處理)只由大腦推:螢幕電腦推的通知會把手機帶到螢幕電腦,那台不替手機做事也不給手機畫面,按「允許」等於沒按,所以螢幕電腦不推;大腦不在前面時照樣推同一張卡。 +通知像那個 Bot 傳來的訊息:標題就是 Bot 的名字,內容就是那句話,不加別的——做完了是它回答的第一行(沒有字的寫「做完了」),要你允許是「需要你允許:修改 Bot 自己:名稱 → 新名字」(整段原因接成一行,不是停在冒號的第一行),要你處理是「需要你處理:…」,問你就是那個問題,例行任務暫停是「例行任務「…」連續失敗…」,目標是「目標達成…/目標暫停…」;別台裝置傳來的檔案,標題是那台裝置的名字。以前標題是「○○ 完成了」「○○ 需要你允許」這種。圖示:iPhone 的網頁 App 一律用 App 的圖示,最上面的 App 名稱那行(「from AnyBot」)也是系統加的,網頁推播換不掉、拿不掉(iOS 不理通知裡指定的 icon);Bot 的頭像要原生 App 才放得上去。 + +電腦上的通知也一樣:標題是 Bot 的名字、內容就是那句話,帶著那個 Bot 的頭像。Linux(notify-send)的圖示在左邊,就是 Bot 的頭像;Mac(AnyBot.app 的 NSUserNotification)左邊固定是 App 的圖示,頭像放在右邊(contentImage)。頭像圖是用畫面上同一套畫法畫的:egui 把它切成三角形(邊緣已經柔化),AnyBot 一格一格填成 PNG,照形狀、顏色存在資料夾的 `avatars/`,只畫一次(`avatar::png_file`)。等你的卡(允許、問你、需要處理)只由大腦推:螢幕電腦推的通知會把手機帶到螢幕電腦,那台不替手機做事也不給手機畫面,按「允許」等於沒按,所以螢幕電腦不推;大腦不在前面時照樣推同一張卡。 - **在通知上直接允許/拒絕**(Android 會顯示按鈕;iPhone 點了打開聊天):只有「要你允許的事」才有按鈕(某個操作、讓 Bot 用電腦工具、在這台電腦上執行);問題卡和「需要處理」沒有,要打開來回答。按「允許」是允許一次。通知帶著那個請求的編號,大腦會確認它還是正在等的那一個:已經回答過、或換成別的請求時,不會被舊通知答到,聊天裡留一行「通知上的「允許/拒絕」沒有用上…」。大腦也記得這是通知送來的:通知上的按鈕只回答「要你允許的事」、只有允許一次或拒絕,不會變成「需要處理」的「我完成了」、問題卡的「略過」或一律允許(放按鈕和收回答用同一條規則)。 - 手機網頁:新訊息從下面滑進來(打開聊天時舊訊息不動;系統設定減少動態時不動);iPhone 鍵盤蓋住畫面時輸入框跟著抬高;送出和按允許時輕震一下(支援的手機)。 diff --git a/docs/feature-map/settings.md b/docs/feature-map/settings.md index 825dc8c..f800f2c 100644 --- a/docs/feature-map/settings.md +++ b/docs/feature-map/settings.md @@ -7,7 +7,7 @@ - `settings-general` 「一般」: - 外觀:主題、強調色、聊天的顏色、語言,「更多外觀設定」(底色、對比、密度、慶祝動畫、頭像動態、外殼顏色重設)([appearance](appearance.md))。 - 記憶與文件:用意思找記憶(本機模型/Ollama/關閉)、Bot 可以翻的資料夾([memory](memory.md))。 - - 通知:Bot 做完或等你時通知、需要你時響一聲([account](account.md))。Mac 上的通知是 AnyBot.app 自己發的(貓的圖示),點一下打開那個 Bot;從建置資料夾直接跑(不是 .app)時改用系統的 display notification,圖示是「工序指令編寫程式」。 + - 通知:Bot 做完或等你時通知、需要你時響一聲([account](account.md))。通知像那個 Bot 傳來的訊息:標題是 Bot 的名字,內容就是那句話(回答的第一行、「需要你允許:…」、問的問題…),帶著它的頭像——Linux 在左邊(通知的圖示),Mac 在右邊(左邊固定是 App 的貓,換不掉)。Mac 上的通知是 AnyBot.app 自己發的,點一下打開那個 Bot;從建置資料夾直接跑(不是 .app)時改用系統的 display notification,圖示是「工序指令編寫程式」。 - Bot:時區,例行任務和提醒用([routines](routines.md))。 - 帳戶:「登入」或「管理帳戶」打開「手機與帳號」頁;資料放在哪。 - `settings-whose` 左下角(你的名字):名字下面一行寫 Bot 在哪一台——「這台電腦」,或「大腦「名字」」(綠點連得到、灰點連不到)。點一下開「Bot 在哪一台」選單:「這台電腦(這台的名字)」、帳號裡每台可以當大腦的電腦(現在用的打勾,離線的灰、不能點),點一下就換——跟「手機與帳號」頁大腦那一欄的「改用它當大腦」「改回用這台自己的 Bot」一樣([account](account.md));沒登入帳號多一行「登入帳號,才能換到別台大腦…」;分隔線下「所有檔案…」([library](library.md))、「個人資料與用量…」、「設定…」(⌘, 也可以)。 diff --git a/src/app.rs b/src/app.rs index 4806dd4..2beab65 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2418,7 +2418,8 @@ impl App { if chime { crate::voice::chime(); } - notify::banner_for(&format!("{} 完成了", b.name), &last, !chime, Some(bot_id)); + // Like a message from the bot: its name, what it said, its avatar. + notify::banner_for(&b.name, if last.is_empty() { "做完了" } else { &last }, !chime, Some(bot_id), avatar::png_file(&b.shape, avatar::color(&b.color), NOTICE_PX)); } // 手機: like a message from the bot — its name, then what it said (the system // adds the app's own line; nothing more from us). @@ -2489,7 +2490,8 @@ impl App { self.dirty = true; if let Some((name, title, why)) = paused { if !self.headless && !self.demo { - notify::banner_for(&format!("{name} 的例行任務暫停了"), &format!("「{title}」{why}"), false, Some(bot_id)); + let pic = self.state.bot(bot_id).and_then(|b| avatar::png_file(&b.shape, avatar::color(&b.color), NOTICE_PX)); + notify::banner_for(&name, &format!("例行任務「{title}」{why}"), false, Some(bot_id), pic); } crate::remote::notify(crate::remote::Notice::Routine, &name, &format!("例行任務「{title}」{why}"), bot_id); } @@ -4797,10 +4799,6 @@ impl App { title = format!("{} 問你", b.name); what = crate::ask::describe(&a.reason); } - if !self.headless { - // The banner doesn't ring a second time when the 提示音 just did. - notify::banner_for(&title, &what, !chime, Some(bot_id)); - } // To the phone: not from a screen — its push would open the phone on the // screen, which runs nothing from a phone and shows it nothing (the 允許 // vanished). The brain pushes its own for this card (the same 通知 setting, @@ -4826,6 +4824,11 @@ impl App { ApprovalKind::Handoff => format!("需要你處理:{}", whole()), _ => format!("需要你允許:{}", whole()), }; + if !self.headless { + // The banner doesn't ring a second time when the 提示音 just did. Like the + // phone's: the bot's name, what it needs, its avatar. + notify::banner_for(&b.name, &said, !chime, Some(bot_id), avatar::png_file(&b.shape, avatar::color(&b.color), NOTICE_PX)); + } if self.mir.on { crate::hooks::notification(&title, &what, bot_id); } else if notice_answers(a) { @@ -8090,6 +8093,9 @@ fn tidy_dots(s: &str) -> String { s.replace(" · ", "·") } +/// The avatar's picture on a notification (pixels; the system scales it down). +const NOTICE_PX: u32 = 128; + fn first_line(s: &str, max: usize) -> String { let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); let line = line.trim_start_matches(['#', '-', '*', ' ']); diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs index e8e31ab..b27eddf 100644 --- a/src/app/goal_ui.rs +++ b/src/app/goal_ui.rs @@ -127,11 +127,13 @@ impl App { return; } let body = first_line(¬e.replace('\n', " "), 120); - if !self.headless { - notify::banner_for(title, &body, true, Some(bot_id)); - } - // 手機: the bot's name, then what became of the goal (the note says it: 目標達成…, 目標暫停…). + // Like a message from the bot: its name, then what became of the goal (the note says it: + // 目標達成…, 目標暫停…), its avatar on the desktop's banner. let name = self.state.bot(bot_id).map(|b| b.name.clone()).unwrap_or_else(|| title.to_string()); + if !self.headless { + let pic = self.state.bot(bot_id).and_then(|b| avatar::png_file(&b.shape, avatar::color(&b.color), NOTICE_PX)); + notify::banner_for(&name, &body, true, Some(bot_id), pic); + } crate::remote::notify(crate::remote::Notice::Done, &name, &body, bot_id); } diff --git a/src/avatar.rs b/src/avatar.rs index 78cd93d..a59f9ec 100644 --- a/src/avatar.rs +++ b/src/avatar.rs @@ -379,6 +379,82 @@ fn paint_body(painter: &egui::Painter, rect: Rect, shape: &str, col: Color32, sp }; } +/// The avatar as pixels (RGBA, `px`×`px`, a little room around it) for a picture outside the +/// window — a notification's. Drawn by the same `paint` as on screen: egui turns it into +/// triangles (edges already softened) and each is filled here, pixel by pixel. +pub fn rgba(shape: &str, col: Color32, px: u32) -> Vec { + let size = px as f32; + let full = Rect::from_min_size(Pos2::ZERO, vec2(size, size)); + let ctx = egui::Context::default(); + let input = egui::RawInput { screen_rect: Some(full), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()); + paint(&painter, full.shrink(size * 0.06), shape, col); + }); + // (Only plain shapes: nothing of the font atlas is needed here.) + out.textures_delta.clear(); + let prims = ctx.tessellate(out.shapes, 1.0); + // Premultiplied colour, 0…1, filled triangle by triangle ("over"). + let n = px as usize; + let mut buf = vec![[0f32; 4]; n * n]; + let edge = |a: Pos2, b: Pos2, p: Pos2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + for prim in &prims { + let egui::epaint::Primitive::Mesh(m) = &prim.primitive else { continue }; + for t in m.indices.as_chunks::<3>().0 { + let v = [&m.vertices[t[0] as usize], &m.vertices[t[1] as usize], &m.vertices[t[2] as usize]]; + let area = edge(v[0].pos, v[1].pos, v[2].pos); + if area.abs() < 1e-6 { + continue; + } + let (x0, x1) = (v.iter().map(|q| q.pos.x).fold(f32::MAX, f32::min).floor().max(0.0) as usize, v.iter().map(|q| q.pos.x).fold(f32::MIN, f32::max).ceil().min(size) as usize); + let (y0, y1) = (v.iter().map(|q| q.pos.y).fold(f32::MAX, f32::min).floor().max(0.0) as usize, v.iter().map(|q| q.pos.y).fold(f32::MIN, f32::max).ceil().min(size) as usize); + for y in y0..y1 { + for x in x0..x1 { + let p = pos2(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1) = (edge(v[1].pos, v[2].pos, p) / area, edge(v[2].pos, v[0].pos, p) / area); + let w2 = 1.0 - w0 - w1; + if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 { + continue; + } + let mut c = [0f32; 4]; + for (w, q) in [(w0, v[0]), (w1, v[1]), (w2, v[2])] { + let k = q.color.to_array(); + for i in 0..4 { + c[i] += w * k[i] as f32 / 255.0; + } + } + let d = &mut buf[y * n + x]; + for i in 0..4 { + d[i] = c[i] + d[i] * (1.0 - c[3]); + } + } + } + } + } + // Straight alpha, as a PNG holds it. + buf.iter() + .flat_map(|c| { + let a = c[3].clamp(0.0, 1.0); + let un = |v: f32| if a > 0.0 { (v / a).clamp(0.0, 1.0) } else { 0.0 }; + [(un(c[0]) * 255.0).round() as u8, (un(c[1]) * 255.0).round() as u8, (un(c[2]) * 255.0).round() as u8, (a * 255.0).round() as u8] + }) + .collect() +} + +/// The avatar as a PNG file in the data folder (`avatars/--.png`, made once), +/// for a notification's picture. +pub fn png_file(shape: &str, col: Color32, px: u32) -> Option { + let dir = crate::model::State::path().parent()?.join("avatars"); + let safe: String = shape.chars().filter(|c| c.is_ascii_alphanumeric()).collect(); + let path = dir.join(format!("{safe}-{:02x}{:02x}{:02x}-{px}.png", col.r(), col.g(), col.b())); + if path.exists() { + return Some(path); + } + std::fs::create_dir_all(&dir).ok()?; + image::RgbaImage::from_raw(px, px, rgba(shape, col, px))?.save(&path).ok()?; + Some(path) +} + pub fn avatar(ui: &mut egui::Ui, size: f32, shape: &str, col: Color32) -> egui::Response { let (rect, resp) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click()); paint(ui.painter(), rect, shape, col); @@ -389,6 +465,30 @@ pub fn avatar(ui: &mut egui::Ui, size: f32, shape: &str, col: Color32) -> egui:: mod tests { use super::*; + /// A notification's picture of the avatar: every shape in its colour in the middle, clear + /// at the corners, with its two eyes, edges softened. (ANYBOT_DUMP_AVATARS= keeps them.) + #[test] + fn avatars_become_pictures_for_notifications() { + let px = 96u32; + let col = color("red"); + let eye = [0xfc, 0xfc, 0xfc]; + for shape in SHAPES { + let img = rgba(shape, col, px); + assert_eq!(img.len(), (px * px * 4) as usize); + let at = |x: u32, y: u32| &img[((y * px + x) * 4) as usize..((y * px + x) * 4 + 4) as usize]; + assert_eq!(at(0, 0)[3], 0, "{shape}: a corner is clear"); + let body = (0..px * px).filter(|i| { let p = &img[(*i * 4) as usize..(*i * 4 + 4) as usize]; p[3] == 255 && p[..3] == [col.r(), col.g(), col.b()] }).count(); + let eyes = (0..px * px).filter(|i| { let p = &img[(*i * 4) as usize..(*i * 4 + 4) as usize]; p[3] == 255 && p[..3] == eye }).count(); + let soft = (0..px * px).filter(|i| { let a = img[(*i * 4 + 3) as usize]; a > 0 && a < 255 }).count(); + assert!(body > (px * px / 5) as usize, "{shape}: the body ({body} pixels)"); + assert!(eyes > 10, "{shape}: the eyes ({eyes} pixels)"); + assert!(soft > 20, "{shape}: softened edges ({soft} pixels)"); + if let Some(dir) = std::env::var_os("ANYBOT_DUMP_AVATARS") { + image::RgbaImage::from_raw(px, px, img).unwrap().save(std::path::Path::new(&dir).join(format!("{shape}.png"))).unwrap(); + } + } + } + /// 自訂顏色是點的,不是滑的:每列 12 個色相(淡→深四列),最後一列灰階;全部是不同的 /// 色碼,都算「自訂」。 #[test] diff --git a/src/notify.rs b/src/notify.rs index 288a8d2..faf5854 100644 --- a/src/notify.rs +++ b/src/notify.rs @@ -138,7 +138,7 @@ pub fn banner_script_with(title: &str, body: &str, sound: bool) -> String { /// Show a banner, with the system's sound. Doesn't wait. pub fn banner(title: &str, body: &str) { - banner_for(title, body, true, None) + banner_for(title, body, true, None, None) } /// A banner about one bot: a click on it opens that bot's chat (`take_clicked`). @@ -147,29 +147,41 @@ pub fn banner(title: &str, body: &str) { /// yellow); a click brings AnyBot to the front on that bot. Run from a build folder (no bundle), /// macOS's `display notification` instead (that banner shows Script Editor's icon). /// - Linux: the desktop's notification service through notify-send, with AnyBot's icon. -pub fn banner_for(title: &str, body: &str, sound: bool, bot: Option) { +pub fn banner_for(title: &str, body: &str, sound: bool, bot: Option, picture: Option) { let body: String = body.chars().take(180).collect(); if !cfg!(target_os = "macos") { - // The desktop's notification service (GNOME, KDE, XFCE…) through notify-send. + // The desktop's notification service (GNOME, KDE, XFCE…) through notify-send. Its icon, + // at the left, is the bot's avatar when it is the bot speaking (AnyBot's otherwise). let mut cmd = Command::new("notify-send"); - cmd.args(["-a", "AnyBot"]); - if let Some(icon) = icon_png() { - cmd.arg("-i").arg(icon); - } - let _ = crate::computer::spawn_reaped(cmd.args([title, &body]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())); + cmd.args(notify_send_args(title, &body, picture.clone().or_else(icon_png))); + let _ = crate::computer::spawn_reaped(cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())); return; } #[cfg(target_os = "macos")] - if center::post(title, &body, sound, bot) { + if center::post(title, &body, sound, bot, picture.as_deref()) { return; } + let _ = &picture; let _ = bot; let _ = crate::computer::spawn_reaped(Command::new("osascript").arg("-e").arg(banner_script_with(title, &body, sound)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())); } +/// notify-send's words: the app, the icon at the left (the bot's avatar, or AnyBot's), the title, +/// the text. +fn notify_send_args(title: &str, body: &str, icon: Option) -> Vec { + let mut a: Vec = vec!["-a".into(), "AnyBot".into()]; + if let Some(i) = icon { + a.push("-i".into()); + a.push(i.into()); + } + a.push(title.into()); + a.push(body.into()); + a +} + /// One banner from a command (`anybot --banner`): sends it and says which way it went. pub fn banner_now(title: &str, body: &str) -> String { - banner_for(title, body, true, None); + banner_for(title, body, true, None, None); #[cfg(target_os = "macos")] { if !center::usable() { @@ -307,13 +319,17 @@ mod center { /// Show the banner. False: not inside AnyBot.app (the caller uses display notification). #[allow(deprecated)] - pub fn post(title: &str, body: &str, sound: bool, bot: Option) -> bool { + pub fn post(title: &str, body: &str, sound: bool, bot: Option, picture: Option<&std::path::Path>) -> bool { if !usable() { return false; } let n = NSUserNotification::new(); n.setTitle(Some(&NSString::from_str(title))); n.setInformativeText(Some(&NSString::from_str(body))); + // The bot's avatar, at the banner's right (the left is always the app's own icon). + if let Some(img) = picture.and_then(image_at) { + let _: () = unsafe { msg_send![&*n, setContentImage: &*img] }; + } n.setIdentifier(Some(&NSString::from_str(&super::banner_id(bot, NEXT.fetch_add(1, Ordering::SeqCst))))); if sound { n.setSoundName(Some(&NSString::from_str("Glass"))); @@ -322,6 +338,16 @@ mod center { true } + /// An NSImage of a picture file (AppKit is in every window app; no bindings needed for one call). + pub(super) fn image_at(path: &std::path::Path) -> Option> { + let cls = AnyClass::get(c"NSImage")?; + let p = NSString::from_str(&path.to_string_lossy()); + unsafe { + let a: objc2::rc::Allocated = msg_send![cls, alloc]; + msg_send![a, initWithContentsOfFile: &*p] + } + } + /// How many of AnyBot's banners the system is keeping (`anybot --banner`'s check). #[allow(deprecated)] pub fn delivered() -> usize { @@ -363,6 +389,22 @@ mod tests { assert_eq!(next_update_check_secs(0.999), 3899); } + /// A bot's banner: its name, what it says, its avatar — at the left on Linux (notify-send's + /// icon), at the right on a Mac (an NSImage of the same picture). + #[test] + fn a_bots_banner_wears_its_avatar() { + let pic = std::env::temp_dir().join("anybot-banner-avatar.png"); + image::RgbaImage::from_raw(64, 64, crate::avatar::rgba("pebble", crate::avatar::color("green"), 64)).unwrap().save(&pic).unwrap(); + let a = notify_send_args("賴桑a炭吉貓", "回好了 3 則留言", Some(pic.clone())); + let words: Vec = a.iter().map(|x| x.to_string_lossy().into_owned()).collect(); + assert_eq!(words, ["-a", "AnyBot", "-i", &pic.to_string_lossy(), "賴桑a炭吉貓", "回好了 3 則留言"]); + assert_eq!(notify_send_args("t", "b", None).len(), 4, "no picture: no -i"); + #[cfg(target_os = "macos")] + assert!(center::image_at(&pic).is_some(), "the Mac reads the avatar as an NSImage"); + #[cfg(target_os = "macos")] + assert!(center::image_at(std::path::Path::new("/nonexistent/x.png")).is_none()); + } + #[test] fn banner_text_is_quoted() { let s = banner_script("電腦助手 需要你允許", "執行 \"rm\" \\ 指令\n下一行");