fix: 桌面——外殼設定即時生效、Bot 設定不破版(自訂顏色改點選色盤)、對話框不被撐寬

- 底色/對比/強調色/密度:每幀比對已套用的值,改了下一幀就換(以前淺色、深色主題要重開)
- Bot 設定:自訂顏色改成 12 色相 × 4 深淺 + 灰階的色盤加「色碼」欄(不用拖滑桿);
  形狀平均分列;預設色和「自訂」同一列;拿掉多的空隙
- 排版檢查多一條:對話框被內容撐得比標題列寬就失敗;修好它抓到的設定 › 電腦(瀏覽器設定檔改兩行)、
  例行任務(長標題換行、對話框標題截斷)、頁面(數字卡外框算進寬度)
- stats 漲跌規則(pages::stat_trend,認一般的 -,單獨 - 不算);長值一律縮字
- 圖表解析:列尾多的 | 不多出一欄;只有一行的圓餅用那一行的名字
- 問候看設定裡的時區;「你的瀏覽器」說明斷行不超寬;ANYBOT_SHOT_EVERY 不再卡住;簡體註解改繁體

已驗證: cargo test 514 全過、排版檢查 3 字型 × 2 資料 × 3 寬度、clippy 無新警告;
Bot 設定、設定 › 電腦深淺截圖目視
未驗證: 使用者機器上的實際視窗
This commit is contained in:
王性驊 2026-11-16 21:34:03 +08:00
parent 63e1f5383f
commit 9c1c6d9c6b
10 changed files with 464 additions and 150 deletions

View File

@ -532,8 +532,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
- 左上角 56 px 頭像預覽。
- 「Bot 名稱」。
- 「Bot 描述」:提示「它負責做什麼?」。
- 「頭像」:12 種形狀排成一列,每個 28 px,沒選的顯示灰色,滑過顯示名稱(第 32 節)。
- 顏色:10 個 24 px 圓點,選中的有一圈強調色外框。
- 「頭像」:14 種形狀平均排成幾列(放得下就 7+7,不會剩一個掉到下一列),每個 28 px,沒選的顯示灰色,滑過顯示名稱(第 32 節)。
- 顏色:10 個 24 px 圓點,選中的有一圈強調色外框;同一列最後是「自訂」(彩虹圈)。按「自訂」出現色盤:12 個色相 × 四種深淺(淡、亮、深、暗)加一列由淺到深的灰階,一格一格直接點(不用拖滑桿),選中的格子有外框;下面「色碼」欄打完整的 #rrggbb 就換成那個顏色,旁邊一格是目前的顏色。色盤和整張卡一樣寬,不會把視窗撐寬。
- 「AI 供應商與模型」
- 供應商下拉選單,換供應商時模型會自動換成那家的預設模型。
- 模型名稱輸入框,提示「模型名稱」。
@ -1536,7 +1536,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- **需要你允許**:不再是蓋住整個視窗的彈出視窗,改成固定在輸入框上方的黃色卡片,上面的聊天照樣看得到,下面的輸入框照樣可以打字告訴它怎麼改。輸入框空著時 Enter 允許、Esc 拒絕(卡片出現 0.6 秒後才算,免得原本要按的 Enter 誤答);游標在輸入框裡也一樣(以前輸入框先把 Enter 當成「送出」拿走,框是空的什麼都沒送出,也沒有允許)。框裡有字時 Enter 照樣是送出。要你親自處理的步驟(接管畫面)還是聊天裡的卡片。
- **黃色只代表「需要你」**:允許卡片、臉上的黃點、側邊欄 Bot 上的黃點、設定裡「更新」旁的黃點(有新版)。有新訊息是強調色(黏土橘)小點。
- **標題列**:Bot 的名字在左邊(按一下開對話詳細資訊),右邊「分享」和「⋯」不再有圓框;圖示線條粗一點(2.25)。
- **新對話**:Bot 的臉放大、依時段的問候(早安/午安/晚上好/夜深了)、一句「嗨,我是 …」和它的描述,下面三個可以直接點的開頭(點了把字放進輸入框)。
- **新對話**:Bot 的臉放大、依時段的問候(早安/午安/晚上好/夜深了;看的是 設定 › 一般 的時區,不是這台電腦的系統時區)、一句「嗨,我是 …」和它的描述,下面三個可以直接點的開頭(點了把字放進輸入框)。
- **設定**:左邊分頁只有文字,選中的黑底白字;每組設定一張白色細框卡片,一列一件事(左邊名稱、右邊控制項,名稱下最多一行小字,其餘說明在「?」裡);選項是分段按鈕,開關是黑軌白鈕。「一般」的名稱改成白話(聊天的顏色、用意思找記憶、Bot 可以翻的資料夾)。「整合」分成三頁(訊息管道、連接器、技能);訊息管道先列「已連接」(標記、名稱 · 種類、誰回覆、狀態、開關、⋯ 裡移除),「新增管道」是八個方塊,點了才在下面打開那一種的表單。權限頁的「直接操作」「自動審核」也是開關。
- **手機**:聊天跟著 Bot 的顏色、Bot 的回覆不用泡泡、允許卡片是黃色、輸入框是墨色框線;工作中在對話最後顯示 Bot 的小臉和跟電腦上一樣的那句「正在…」。
- **自己進化**:一件事做了 5 步以上(操作電腦、網頁、指令,不算記憶和設定),回答完後在背景回頭看一次:這是在網站或程式上動手操作的事(填表、發文、回留言、上傳下載、改設定),就把這次真的成功的最短做法存成技能(用畫面上的名字,不寫編號和座標;繞路和失敗寫成「注意」;使用者說過的偏好寫進去);已經有同一件事的技能就合併成更好的一版,照著做而且很順就不動。回覆下面會多一行「(學會了新做法「…」)」或「(把做法「…」更新了)」。系統指示要 Bot 開始做事前先看技能清單、有符合的先 use_skill。實測(httpbin 訂 pizza,真的 Grok):第一次 11 步學到技能;第二次先讀技能、10 步 24 秒一次做完,回頭看後判斷不用改。
@ -1854,7 +1854,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 淺色:米白紙底、側欄深一階、卡片純白;文字是帶暖調的黑。深色:暖黑三階(不藍黑)。
- 強調色(連結、選中、新訊息點、focus)是黏土橘;殼本身幾乎全灰階,**黃色只代表「需要你」**,紅只代表危險,圖表才有意識地用色(一套暖家族六色,見第 27 節頁面圖表)。
- 設定 › 一般 › 外觀有三個旋紐:**底色**(藍灰→米白)、**對比**(柔和→鮮明,整個殼的階層、細線、文字深淺一起調)、**強調色**(黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑八色,圖表六色跟著轉);預設就是「紙」。同處有**密度**(寬鬆/緊湊)和**慶祝動畫**開關;「外殼顏色重設」把三個旋紐歸零。側欄選中的 Bot 是一條強調色細條+淺底,不整條上色。
- 設定 › 一般 › 外觀有三個旋紐:**底色**(藍灰→米白)、**對比**(柔和→鮮明,整個殼的階層、細線、文字深淺一起調)、**強調色**(黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑八色,圖表六色跟著轉);預設就是「紙」。調了立刻整個殼跟著換(淺色、深色、跟著系統都一樣,不用重開)。同處有**密度**(寬鬆/緊湊)和**慶祝動畫**開關;「外殼顏色重設」把三個旋紐歸零。側欄選中的 Bot 是一條強調色細條+淺底,不整條上色。
- 工作完成撒彩帶:只在 /goal 目標達成時(不是每輪結束),落在該 Bot 的聊天上約 1.4 秒;設定 › 一般可關。
### 頭像

View File

@ -8,7 +8,7 @@
- 搜尋「搜尋 Bot 和訊息」:上面列名字或描述相符的 Bot,下面「訊息」列你和 Bot 說過的話和附件檔名(含過去的對話,最多 40 筆),點一筆就捲到那則訊息。
- Bot 選單:「釘選」/「取消釘選」、「移至」、「標示為已讀」/「標示為未讀」、「設為主要 Bot」、「編輯 Bot…」、「記憶…」、「開始新對話」、「過去的對話」、「分享與匯出」(「匯出 Bot(分享給別人)…」「匯出文字記錄…」「匯入 Bot…」「複製對話 ID」)、「重新啟動這個 Bot」、「清除聊天記錄」、「刪除」。
- 建立:「新增 Bot」,或「從範本建立」(研究助理、寫作夥伴、電腦助手、客服助理、開發助手)。新 Bot 沿用目前選中 Bot 的供應商和模型,電腦工具關著。
- 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀、10 種顏色和「自訂」);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」);「電腦操作」;「能力」;「技能」;「記憶」;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot(看得到它的聊天、頁面和檔案)」。
- 「Bot 設定」:「Bot 資料」(「Bot 名稱」「Bot 描述」和大頭像,同一張卡);「個人檔案」(Soul 與指示、擅長(什麼事找它)、不找它做的事);「頭像」(14 種形狀平均排成兩列;10 種顏色和「自訂」同一列;按「自訂」出現一格一格的色盤——12 個色相各四種深淺加一列灰階,直接點,沒有滑桿——和「色碼」欄,打完整的 #rrggbb 才換色);「AI 供應商與模型」(供應商、「模型名稱」、「選擇」、「執行步驟用的模型」、「思考模式」);「電腦操作」;「能力」;「技能」;「記憶」;最下面「釘選到側邊欄」「團隊成員可以使用這個 Bot(看得到它的聊天、頁面和檔案)」。
- Soul 與指示只有它自己讀;描述、擅長、不找它做的事、會的技能、在哪幾台電腦做事會寫進其他 Bot 的同事名冊。
- 能力 11 類:「上網」「瀏覽器」「看螢幕與操作」「檔案與指令」「Mac App」「連接器」「電話、簡訊、X」「例行任務」「頁面」「和其他 Bot 合作」「管理 App」。沒勾的工具不提供給它,也不寫進說明。記憶、技能、問你問題、傳檔案到聊天、表情和卡片每個 Bot 都有。
- 供應商:xAI Grok、OpenAI、Claude、Google Gemini、OpenRouter、OpenCode Go、Ollama(本機)、自訂(OpenAI 相容),每個 Bot 各選各的。
@ -24,7 +24,7 @@
## 怎麼操作
- Bot:使用者問「你會什麼」「你的設定是什麼」時先用 `my_profile`;要改自己用 `update_my_profile`,只帶要改的欄位(description、soul、strengths、not_for、abilities_on/abilities_off、skills_add/skills_remove、computers_add/computers_remove、default_computer、provider、model、thinking、step_model、color、shape);soul 要先讀再送整段。`list_bots` 看所有 Bot 的供應商、模型、描述和所在分區。`create_bot`(template,或 name、description、instructions、provider、model)建新 Bot;`update_bot`(bot 空白是自己)改名稱、描述、指示、供應商、模型、釘選、預設電腦。
- 驗證:用 + 建一個 Bot,填 Soul 與指示和擅長後按「建立 Bot」,重開 AnyBot 還在;在聊天裡說「把你的檔案與指令能力關掉」,要先跳出列出改動的確認卡片,按拒絕什麼都不變,按允許後 Bot 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。自動測試:`cargo test profile::`、`cargo test appctl::`、`cargo test app::sidebar_ui::`、`cargo test app::tests::`。
- 驗證:用 + 建一個 Bot,填 Soul 與指示和擅長後按「建立 Bot」,重開 AnyBot 還在;在聊天裡說「把你的檔案與指令能力關掉」,要先跳出列出改動的確認卡片,按拒絕什麼都不變,按允許後 Bot 設定的「能力」少勾一格;換一個沒金鑰的供應商,要出現紅字和「前往設定」。頭像按「自訂」,色盤點一格頭像就換色,「色碼」打 #6b4a55 也換;整個視窗不能變寬(下面的卡片和最上面的標題列一樣寬)。自動測試:`cargo test profile::`、`cargo test appctl::`、`cargo test app::sidebar_ui::`、`cargo test app::tests::`。
## 陷阱

View File

@ -6,7 +6,7 @@
設定視窗,分頁由上到下:
- 「一般」:
- 外觀:主題、底色(冷→暖滑桿)、對比(柔和→鮮明滑桿)、強調色(八個點:黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑)、密度(寬鬆/緊湊)、慶祝動畫(開/關,目標達成時撒彩帶)、外殼顏色重設(回預設「紙」)、聊天的顏色、字型、語言(選單和 Bot 回答用的語言)。
- 外觀:主題、底色(冷→暖滑桿)、對比(柔和→鮮明滑桿)、強調色(八個點:黏土、靛藍、苔綠、藍綠、玫紅、琥珀、石板、墨黑)、密度(寬鬆/緊湊)、慶祝動畫(開/關,目標達成時撒彩帶)、外殼顏色重設(回預設「紙」;這幾項調了立刻整個殼跟著換,不用重開)、聊天的顏色、字型、語言(選單和 Bot 回答用的語言)。
- 記憶與文件:用意思找記憶(本機模型/Ollama/關閉)、Bot 可以翻的資料夾([memory](memory.md))。
- 通知:Bot 做完或等你時通知、需要你時響一聲([phone](phone.md))。Mac 上的通知是 AnyBot.app 自己發的(貓的圖示),點一下打開那個 Bot;從建置資料夾直接跑(不是 .app)時改用系統的 display notification,圖示會是「工序指令編寫程式」。
- Bot:時區,例行任務和提醒用([routines](routines.md))。
@ -47,7 +47,7 @@ Bot 設定(每個 Bot 一個視窗,[bots](bots.md)):
## 怎麼操作
- Bot:大部分設定改不了。`update_settings` 只能改三樣:`theme`(light/dark/system)、`accent`(bot_color/black)、`timezone`(像 Asia/Taipei);「在這台電腦上執行」只有使用者能打開。改自己的個人檔案、能力、技能、電腦、模型、頭像:先用 `my_profile` 看,再用 `update_my_profile` 改(使用者先看到確認卡片,按允許才生效)。其他設定告訴使用者在哪個分頁、哪一塊。
- 驗證:打開設定,八個分頁都在,各區塊照上面的位置出現;請 Bot 換深色主題、時區改 Asia/Tokyo,設定 › 一般 的主題和時區要跟著變;給它不存在的時區,要回「不是有效的時區名稱」。自動測試:`cargo test featuremap::`(設定視窗的每個分頁和區塊標題、Bot 能改的設定都要寫在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test layout_audit::`(每個設定分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫一遍:字被切掉或疊在一起就失敗)。
- 驗證:打開設定,八個分頁都在,各區塊照上面的位置出現;請 Bot 換深色主題、時區改 Asia/Tokyo,設定 › 一般 的主題和時區要跟著變;給它不存在的時區,要回「不是有效的時區名稱」。主題選「淺色」時拉「底色」、點別的強調色、切「緊湊」,畫面要當下就變(不用重開);時區改成 America/New_York 後開新對話,問候要照紐約的時段。自動測試:`cargo test featuremap::`(設定視窗的每個分頁和區塊標題、Bot 能改的設定都要寫在這份)、`cargo test appctl::`、`cargo test policy::`、`cargo test layout_audit::`(每個設定分頁、Bot 設定、例行任務、右側面板,用三種字型、最窄和一般的視窗、示範和很長的資料畫一遍:字被切掉、疊在一起,或任何對話框被內容撐得比它的標題列寬,就失敗)。
## 陷阱

View File

@ -138,13 +138,16 @@ pub fn set_doc_folders(v: Vec<String>) {
pub struct App {
state: State,
pal: Palette,
/// The shell inputs `pal` was last built from (主題、底色、強調色、對比、密度): when the
/// state's differ, the next frame builds the shell again — whatever changed them.
shell_applied: Option<ShellKey>,
demo: bool,
screenshot: Option<PathBuf>,
/// ANYBOT_SHOT_EVERY: where the next per-frame picture goes (see handle_screenshot).
every_out: Option<PathBuf>,
frames: u32,
shot_requested: bool,
shot: Arc<Mutex<Option<Arc<egui::ColorImage>>>>,
/// Pictures that arrived, each with where it goes: `None` is the run's own picture (it ends
/// the run), `Some(path)` an ANYBOT_SHOT_EVERY frame.
shot: ShotQueue,
drafts: HashMap<u64, String>,
search: String,
streams: HashMap<u64, Live>,
@ -433,12 +436,12 @@ impl App {
let mut app = App {
state,
pal: LIGHT,
shell_applied: None,
demo,
screenshot,
every_out: None,
frames: 0,
shot_requested: false,
shot: Arc::new(Mutex::new(None)),
shot: Arc::new(Mutex::new(Vec::new())),
drafts: HashMap::new(),
search: String::new(),
streams: HashMap::new(),
@ -1209,13 +1212,19 @@ impl App {
ctx.request_repaint_after(std::time::Duration::from_millis(16));
}
/// What the shell is built from, to notice a change (f32s by their bits: equal means unchanged).
fn shell_key(&self) -> ShellKey {
(self.state.theme, self.state.shell_tone.to_bits(), self.state.shell_accent.clone(), self.state.shell_contrast.to_bits(), self.state.dense)
}
fn apply_theme(&mut self, ctx: &egui::Context) {
self.shell_applied = Some(self.shell_key());
let dark = match self.state.theme {
Theme::Light => false,
Theme::Dark => true,
Theme::System => ctx.input(|i| i.raw.system_theme) == Some(egui::Theme::Dark),
};
// The shell from the person's three dials (設定 › 一般); defaults reproduce 「纸」.
// The shell from the person's three dials (設定 › 一般); defaults reproduce 「紙」.
self.pal = crate::theme::shell(self.state.shell_tone, &self.state.shell_accent, self.state.shell_contrast, dark);
// Screenshot concept themes for picking a colour direction (see theme.rs `shot_palette`).
if let Ok(t) = std::env::var("ANYBOT_SHOT_PAL") {
@ -3418,9 +3427,8 @@ impl App {
self.live_face(ui, bot.id, face, true);
ui.vertical(|ui| {
ui.add_space(22.0);
// 問候依時段(和時區設定一起):先打招呼,再報名字。
let hour: u32 = chrono::Local::now().format("%H").to_string().parse().unwrap_or(12);
let hello = match hour { 5..=11 => "早安", 12..=17 => "午安", 18..=22 => "晚上好", _ => "夜深了" };
// 問候依時段(看設定裡的時區):先打招呼,再報名字。
let hello = greeting(chrono::Utc::now(), &self.state.timezone);
ui.label(RichText::new(t(hello)).size(FONT_LG).color(p.text3));
ui.label(RichText::new(t("嗨,我是 {name}").replace("{name}", &bot.name)).size(28.0).strong().family(crate::bold()).color(p.text));
let about = if bot.description.is_empty() { t("想做什麼?直接說,或從下面挑一個開始。") } else { bot.description.clone() };
@ -3562,7 +3570,7 @@ impl App {
}
let shown = self.ask_shown.entry(bot.id).or_insert_with(Instant::now).elapsed().as_secs_f32();
let mut answer = None;
// (長理由不許把輸入框頂出螢幕:卡片照內容估高、照窗口高度封頂,裡面的東西在卡面裡往下捲。
// (長理由不許把輸入框頂出螢幕:卡片照內容估高、照視窗高度封頂,裡面的東西在卡面裡往下捲。
// 下方的列問不到剩餘高度,所以捲動區用估出來的固定高度。)
let reason = self.approvals.get(&bot.id).map(|a| a.reason.clone()).unwrap_or_default();
let cap = (ui.ctx().content_rect().height() * 0.45).max(160.0);
@ -3633,7 +3641,7 @@ impl App {
Skip,
}
let mut act = None;
// (選項再多也不許把輸入框頂出螢幕:卡面照內容估高、照窗口高度封頂,裡面在卡面裡往下捲。)
// (選項再多也不許把輸入框頂出螢幕:卡面照內容估高、照視窗高度封頂,裡面在卡面裡往下捲。)
let cap = (ui.ctx().content_rect().height() * 0.45).max(160.0);
let body = ask_card_height(q, ui.available_width(), cap);
Frame::new().fill(p.attention_bg).stroke(Stroke::new(2.0, p.attention)).corner_radius(20).inner_margin(Margin::symmetric(16, 14)).show(ui, |ui| {
@ -4298,10 +4306,20 @@ impl App {
}
let current = crate::botbrowser::current();
for name in crate::botbrowser::choices() {
// (Radio + name + description + buttons: in a narrow window this overflows the
// card, so the buttons wrap onto a second line inside it.)
// Two lines a profile: the choice, its state and its buttons (wrapping inside the
// card in a narrow window), then what it is, broken to the card's width. (A note
// squeezed into the first line guessed the buttons' room and pushed the card wider.)
let firefox = name.ends_with(crate::botbrowser::FIREFOX_MARK);
let note = if name == crate::botbrowser::PERSON_PROFILE {
Some("你平常的 Chrome,切到哪個設定檔就讀哪個")
} else if firefox {
Some("你自己的 Firefox 設定檔:要讓 Bot 用,請從這裡開啟(先關掉它原本的視窗)")
} else {
None
};
let row_w = ui.available_width();
ui.horizontal_wrapped(|ui| {
ui.set_width(ui.available_width());
ui.set_max_width(row_w);
let mut on = name == current;
if ui.radio_value(&mut on, true, RichText::new(&name).strong().family(crate::bold())).clicked() && name != current {
let _ = crate::botbrowser::set_current(&name);
@ -4310,9 +4328,6 @@ impl App {
ui.add(egui::Label::new(RichText::new(t("使用中")).size(11.5).color(p.accent)).truncate());
}
if name == crate::botbrowser::PERSON_PROFILE {
// (A plain label expands to its text's natural width and runs over the
// buttons: it must take only the room left in the row.)
row_hint(ui, "你平常的 Chrome,切到哪個設定檔就讀哪個", 130.0, p.text2);
if crate::axread::trusted(false) {
crate::icons::label(ui, crate::icons::Icon::Check, &t("輔助使用已打開"), 11.5, p.text3);
} else if ui.small_button(t("打開輔助使用")).on_hover_text(t("macOS 要你允許一次,AnyBot 才看得到你的瀏覽器視窗")).clicked() && !crate::axread::trusted(true) {
@ -4320,10 +4335,6 @@ impl App {
}
return;
}
let firefox = name.ends_with(crate::botbrowser::FIREFOX_MARK);
if firefox {
row_hint(ui, "你自己的 Firefox 設定檔:要讓 Bot 用,請從這裡開啟(先關掉它原本的視窗)", 100.0, p.text2);
}
if ui.small_button(t("開啟視窗")).on_hover_text(t("打開這個設定檔的瀏覽器視窗,在裡面登入網站")).clicked() {
let note = self.browser_note.clone();
let name = name.clone();
@ -4353,9 +4364,19 @@ impl App {
}
}
});
if let Some(note) = note {
let font = egui::FontId::proportional(11.5);
let text = wrap_to_width(&t(note), (row_w - 26.0).max(80.0), |x| ui.painter().layout_no_wrap(x.to_string(), font.clone(), egui::Color32::WHITE).size().x);
ui.horizontal(|ui| {
// (Under the name, past the radio button.)
ui.add_space(26.0);
ui.label(RichText::new(text).size(11.5).color(p.text2));
});
}
ui.add_space(4.0);
}
ui.horizontal_wrapped(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.new_browser_profile).hint_text(t("新設定檔名稱,例如 工作")).desired_width(ui.available_width().min(180.0).max(90.0)));
ui.add(egui::TextEdit::singleline(&mut self.new_browser_profile).hint_text(t("新設定檔名稱,例如 工作")).desired_width(ui.available_width().clamp(90.0, 180.0)));
let ok = crate::botbrowser::check_name(&self.new_browser_profile).is_ok();
if ui.add_enabled(ok, egui::Button::new("新增設定檔")).clicked() {
let r = crate::botbrowser::add(&self.new_browser_profile).and_then(|n| crate::botbrowser::set_current(&n));
@ -4372,47 +4393,17 @@ impl App {
ui.label(RichText::new(sidebar_ui::shorten_width(ui, &note, ui.available_width() - 2.0, 11.5)).size(11.5).color(p.text2));
}
// (egui's own wrapping uses the style's fixed wrap width, not this column's, and breaks
// only at spaces — a long CJK run with no spaces runs past the card. Break the
// text to the card's width by hand: at spaces where words exist, between
// characters for runs without them. Each line's width is measured as a whole.)
let hint_txt: String = {
let full = t("選「你的瀏覽器」:Bot 從畫面讀你平常的 Chrome(macOS 會請你打開一次「輔助使用」),你在 Chrome 切到哪個設定檔,它就看哪個;讀之前會先問你。其他的是 AnyBot 自己的視窗,各自登入一次就好。");
let font = egui::FontId::proportional(11.0);
// (A wrapped column reports infinite `available_width`; the card's own rect is
// always finite, so the wrap width comes from the wider of the two.)
// (A ScrollArea body gets infinite max_rect; its clip rect is the viewport.)
let max_w = (ui.max_rect().width().min(ui.clip_rect().width()) - 36.0 - 2.0).max(80.0);
let w = |x: &str| ui.painter().layout_no_wrap(x.to_string(), font.clone(), egui::Color32::WHITE).size().x;
// (A break may fall before any CJK character, or before a Latin word.)
let breakable = |chars: &[char], i: usize| -> bool {
let c = chars[i];
let cjk = !c.is_ascii_alphanumeric() && !('a'..='z').contains(&c) && !('A'..='Z').contains(&c);
cjk || (i > 0 && !cjk && (chars[i - 1] == ' ' || { let p = chars[i - 1]; !p.is_ascii_alphanumeric() && p != '\'' }))
};
let mut out = String::new();
for para in full.split('\n') {
let chars: Vec<char> = para.chars().collect();
let mut start = 0usize;
for i in 1..=chars.len() {
if i == chars.len() || (breakable(&chars, i) && w(&chars[start..i].iter().collect::<String>()) > max_w) {
// (Trim trailing spaces off the line before emitting it.)
let mut end = i;
while end > start + 1 && chars[end - 1] == ' ' {
end -= 1;
}
out.extend(&chars[start..end]);
out.push('\n');
start = i;
}
}
if start < chars.len() {
out.extend(&chars[start..]);
out.push('\n');
}
}
out.trim_end().to_string()
};
ui.label(RichText::new(hint_txt).size(11.0).color(p.text3));
// only at spaces — a long CJK run with no spaces runs past the card. Break the text to
// the card's width by hand, see `wrap_to_width`.)
let hint_txt: String = {
let full = t("選「你的瀏覽器」:Bot 從畫面讀你平常的 Chrome(macOS 會請你打開一次「輔助使用」),你在 Chrome 切到哪個設定檔,它就看哪個;讀之前會先問你。其他的是 AnyBot 自己的視窗,各自登入一次就好。");
let font = egui::FontId::proportional(11.0);
// (A wrapped column reports infinite `available_width`; a ScrollArea body gets an
// infinite max_rect too, but its clip rect is the viewport: take the narrower.)
let max_w = (ui.max_rect().width().min(ui.clip_rect().width()) - 36.0 - 2.0).max(80.0);
wrap_to_width(&full, max_w, |x| ui.painter().layout_no_wrap(x.to_string(), font.clone(), egui::Color32::WHITE).size().x)
};
ui.label(RichText::new(hint_txt).size(11.0).color(p.text3));
}
/// The bot's routines: what repeats, when it runs next, pause / run now / delete.
@ -4447,7 +4438,9 @@ impl App {
for r in &bot.routines {
setting_card(ui, p, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(&r.title).strong().family(crate::bold()).size(FONT_LG));
// (A long title wraps inside the card; in a row a plain label never wraps
// and pushed the whole window wider.)
ui.add(egui::Label::new(RichText::new(&r.title).strong().family(crate::bold()).size(FONT_LG)).wrap());
if r.paused {
ui.label(RichText::new(t("已暫停")).size(11.5).color(p.text3));
}
@ -4646,7 +4639,6 @@ impl App {
});
});
});
ui.add_space(16.0);
// 個人檔案 (a group has none: its members answer, each as itself).
if b.members.is_empty() {
self.profile_identity_card(ui, &mut b);
@ -4654,34 +4646,36 @@ impl App {
setting_card(ui, p, |ui| {
setting_title(ui, "頭像", "", p);
let inactive_grey = if is_dark(p) { Color32::from_gray(90) } else { Color32::from_gray(185) };
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
for s in avatar::SHAPES {
let r = avatar::avatar(ui, 28.0, s, if b.shape == s { avatar::color(&b.color) } else { inactive_grey }).on_hover_text(avatar::shape_label(s));
if r.clicked() {
b.shape = s.into();
// Shapes in even rows (7 + 7, not 13 + a lone one) that fit the card.
let (cell, gap) = (28.0, 6.0);
let fit = (((ui.available_width() + gap) / (cell + gap)).floor() as usize).max(1);
let rows = avatar::SHAPES.len().div_ceil(fit);
for row in avatar::SHAPES.chunks(avatar::SHAPES.len().div_ceil(rows)) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for &s in row {
let r = avatar::avatar(ui, cell, s, if b.shape == s { avatar::color(&b.color) } else { inactive_grey }).on_hover_text(avatar::shape_label(s));
if r.clicked() {
b.shape = s.into();
}
}
}
});
});
}
ui.add_space(4.0);
// The ten colours, then 自訂 (a rainbow ring) in the same row.
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
ui.spacing_mut().item_spacing.x = gap;
for (key, name, _) in avatar::COLORS {
let (rect, r) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::click());
let (rect, r) = ui.allocate_exact_size(vec2(cell, cell), egui::Sense::click());
ui.painter().circle_filled(rect.center(), 10.0, avatar::color(key));
if b.color == key {
ui.painter().circle_stroke(rect.center(), 12.0, Stroke::new(2.0, p.focus));
}
if r.on_hover_text(name).clicked() {
if r.on_hover_text(name).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
b.color = key.into();
}
}
});
// Custom: a rainbow ring; click it and three sliders appear. The colour is
// kept as its hex ("#rrggbb"), so the picker and the saved bot agree.
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let (rect, r) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::click());
let (rect, r) = ui.allocate_exact_size(vec2(cell, cell), egui::Sense::click());
for i in 0..12 {
let a = i as f32 / 12.0 * std::f32::consts::TAU;
let c = egui::pos2(rect.center().x + 10.0 * a.cos(), rect.center().y + 10.0 * a.sin());
@ -4690,27 +4684,14 @@ impl App {
if avatar::is_custom(&b.color) {
ui.painter().circle_stroke(rect.center(), 12.0, Stroke::new(2.0, p.focus));
}
if r.on_hover_text(t("自訂顏色")).clicked() && !avatar::is_custom(&b.color) {
if r.on_hover_text(t("自訂顏色")).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && !avatar::is_custom(&b.color) {
b.color = avatar::hex_of_hsv(avatar::hsv_of(&b.color));
}
ui.label(RichText::new(t("自訂")).size(FONT_XS).color(p.text3));
});
if avatar::is_custom(&b.color) {
let mut hsv = avatar::hsv_of(&b.color);
let mut touched = false;
ui.horizontal(|ui| {
touched |= ui.add(egui::Slider::new(&mut hsv[0], 0.0..=360.0).text(t("色相").to_string())).changed();
touched |= ui.add(egui::Slider::new(&mut hsv[1], 0.0..=1.0).text(t("飽和").to_string())).changed();
touched |= ui.add(egui::Slider::new(&mut hsv[2], 0.0..=1.0).text(t("明度").to_string())).changed();
let (sr, _) = ui.allocate_exact_size(vec2(24.0, 24.0), egui::Sense::hover());
ui.painter().circle_filled(sr.center(), 9.0, avatar::color(&avatar::hex_of_hsv(hsv)));
});
// Only write back when a slider moved. The hsv→hex→hsv round trip is not
// exactly the identity (8-bit rounding), so assigning every frame made
// the colour (avatar, ring) tick by ±1/255 for as long as the editor was open.
if touched {
b.color = avatar::hex_of_hsv(hsv);
}
ui.add_space(6.0);
avatar_color_grid(ui, p, &mut b.color);
}
});
setting_card(ui, p, |ui| {
@ -5013,7 +4994,7 @@ impl App {
}
});
card_row(ui, p, "強調色", "", "選中項、連結和新訊息點的顏色;圖表六色跟著它轉。", |ui| {
let darkish = self.pal.pane.r() < 128;
let darkish = is_dark(self.pal);
for (name, label, light, darkv) in crate::theme::ACCENTS {
let (rect, r) = ui.allocate_exact_size(vec2(26.0, 26.0), egui::Sense::click());
let c = rect.center();
@ -5566,14 +5547,14 @@ impl App {
let Some(path) = self.screenshot.clone() else { return };
self.frames += 1;
let need = std::env::var("ANYBOT_SHOT_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(SCREENSHOT_FRAMES);
// ANYBOT_SHOT_EVERY=N: 每 N 幀存一張(path.png.fNN)——用来看哪一块在闪。
// ANYBOT_SHOT_EVERY=N: 每 N 幀另存一張(<名稱>-<幀>.png),用來看哪一塊在閃。
if let Some(n) = std::env::var("ANYBOT_SHOT_EVERY").ok().and_then(|v| v.parse::<u32>().ok()) {
if n > 0 && self.frames.is_multiple_of(n) && self.frames >= 40 && self.frames <= 80 && !self.shot_requested && self.every_out.is_none() {
self.every_out = Some(path.with_file_name(format!("{}-{:03}.png", path.file_stem().unwrap_or_default().to_string_lossy(), self.frames)));
if every_shot_due(self.frames, n, need) {
let to = path.with_file_name(format!("{}-{:03}.png", path.file_stem().unwrap_or_default().to_string_lossy(), self.frames));
let slot = self.shot.clone();
let repaint = ctx.clone();
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |img| {
*slot.lock().unwrap() = Some(img);
slot.lock().unwrap().push((Some(to.clone()), img));
repaint.request_repaint();
})));
}
@ -5599,14 +5580,15 @@ impl App {
let slot = self.shot.clone();
let repaint = ctx.clone();
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |img| {
*slot.lock().unwrap() = Some(img);
slot.lock().unwrap().push((None, img));
repaint.request_repaint();
})));
}
let shot = self.shot.lock().unwrap().take();
// only claim the per-frame name when a picture actually arrived with it
let path = if shot.is_some() { self.every_out.take().unwrap_or(path) } else { path };
if let Some(img) = shot {
let arrived = std::mem::take(&mut *self.shot.lock().unwrap());
for (to, img) in arrived {
// The run's own picture is the last thing a run does; per-frame ones keep it going.
let last = to.is_none();
let path = to.unwrap_or_else(|| path.clone());
let [w, h] = img.size;
let bytes: Vec<u8> = img.pixels.iter().flat_map(|c| c.to_array()).collect();
if let Some(dir) = path.parent() {
@ -5620,8 +5602,7 @@ impl App {
}
None => eprintln!("screenshot had an unexpected size"),
}
// EVERY mode keeps running until its last frame; otherwise this closes the run.
if !(std::env::var("ANYBOT_SHOT_EVERY").is_ok() && self.frames < 80) {
if last {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
}
@ -6076,7 +6057,9 @@ impl eframe::App for App {
}
self.background(ctx);
self.call_poll(ctx);
if self.state.theme == Theme::System {
// 跟著系統: every frame (the system may switch). Otherwise when a dial in 設定 › 一般
// (or anything else) changed what the shell is built from.
if self.state.theme == Theme::System || self.shell_applied.as_ref() != Some(&self.shell_key()) {
self.apply_theme(ctx);
}
if ctx.input(|i| i.modifiers.command && i.key_pressed(Key::N)) {
@ -6994,17 +6977,55 @@ fn hint(ui: &mut egui::Ui, text: impl Into<String>, p: Palette) {
ui.add(egui::Label::new(RichText::new(t(&text.into())).size(11.5).color(p.text3)).wrap());
}
/// A rounded group of related settings, like a macOS settings card.
/// A label inside a row of buttons: it takes the row's remaining width minus `keep` px kept
/// for the buttons that follow, so it truncates with「…」instead of pushing them off the card.
fn row_hint(ui: &mut egui::Ui, text: &str, keep: f32, color: egui::Color32) {
let w = (ui.available_width() - keep).max(60.0);
let full = t(text);
let cut = sidebar_ui::shorten_width(ui, &full, w, 11.5);
let (rect, _) = ui.allocate_exact_size(vec2(w, 14.0), egui::Sense::hover());
ui.painter().text(rect.left_top(), egui::Align2::LEFT_CENTER, cut, egui::FontId::proportional(11.5), color);
/// 自訂顏色, to click rather than drag: `avatar::custom_swatches` as a grid as wide as the card
/// (twelve across, square cells), then a 色碼 box for an exact colour. Writes `color` only on a
/// click or a valid code (never every frame: see the old sliders' ±1/255 flicker).
fn avatar_color_grid(ui: &mut egui::Ui, p: Palette, color: &mut String) {
let gap = 4.0;
let cols = avatar::SWATCH_COLUMNS as f32;
let cell = ((ui.available_width() - gap * (cols - 1.0)) / cols).clamp(14.0, 30.0);
for row in avatar::custom_swatches() {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = vec2(gap, gap);
for hex in row {
let (rect, r) = ui.allocate_exact_size(vec2(cell, cell), egui::Sense::click());
ui.painter().rect_filled(rect, 6, avatar::color(&hex));
// (A hairline, so the near-black and near-white cells still show on the card.)
ui.painter().rect_stroke(rect, 6, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
if color.eq_ignore_ascii_case(&hex) {
ui.painter().rect_stroke(rect.expand(2.0), 7, Stroke::new(2.0, p.focus), egui::StrokeKind::Inside);
} else if r.hovered() {
ui.painter().rect_stroke(rect, 6, Stroke::new(1.0, p.text3), egui::StrokeKind::Inside);
}
if r.on_hover_text(&hex).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
*color = hex;
}
}
});
}
ui.add_space(6.0);
// (One row as tall as the text box, everything centred on it.)
ui.allocate_ui_with_layout(vec2(ui.available_width(), 28.0), Layout::left_to_right(Align::Center), |ui| {
ui.label(RichText::new(t("色碼")).size(FONT_XS).color(p.text2));
// What is typed stays while typing; the colour changes once it is a full code.
let id = ui.scope_id().with("avatar-hex");
let mut draft = ui.data(|d| d.get_temp::<String>(id)).unwrap_or_else(|| color.clone());
let r = ui.add(egui::TextEdit::singleline(&mut draft).desired_width(96.0).hint_text("#6b4a55"));
if r.changed() {
if let Some(h) = avatar::parse_hex(&draft) {
*color = h;
}
}
if !r.has_focus() {
draft = color.clone();
}
ui.data_mut(|d| d.insert_temp(id, draft));
let (sr, _) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::hover());
ui.painter().rect_filled(sr, 6, avatar::color(color));
});
}
/// A rounded group of related settings, like a macOS settings card.
fn setting_card<R>(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mut egui::Ui) -> R) -> R {
let r = Frame::new()
.fill(p.elevated)
@ -7054,6 +7075,79 @@ fn dialog_max_height(ctx: &egui::Context) -> f32 {
(ctx.content_rect().height() - WINDOW_SCREEN_MARGIN).max(240.0)
}
/// `text` broken into lines no wider than `max_w` (as `width` measures a line), for a label whose
/// column egui can't wrap to. Greedy: a line ends at the last break point that still fits; a
/// break falls between CJK characters or between Latin words, never inside a word; closing
/// punctuation (,。)…) never starts a line and an opening one ((「…) never ends one. Only a
/// single word wider than the whole line is left wider. Paragraphs (\n) and blank lines stay.
fn wrap_to_width(text: &str, max_w: f32, width: impl Fn(&str) -> f32) -> String {
const NO_START: &str = ",。、;:!?)」』】〉》,.;:!?)]}%";
const NO_END: &str = "(「『【〈《([{";
let word = |c: char| c.is_ascii_alphanumeric() || c == '\'';
let breakable = |chars: &[char], i: usize| {
let (prev, c) = (chars[i - 1], chars[i]);
!NO_START.contains(c) && !NO_END.contains(prev) && !(word(prev) && word(c))
};
let line = |chars: &[char]| chars.iter().collect::<String>().trim_matches(' ').to_string();
let mut lines: Vec<String> = vec![];
for para in text.split('\n') {
let chars: Vec<char> = para.chars().collect();
let (mut start, mut fit, mut i) = (0usize, None::<usize>, 1usize);
while i <= chars.len() {
if i < chars.len() && !breakable(&chars, i) {
i += 1;
continue;
}
if width(&line(&chars[start..i])) <= max_w {
fit = Some(i);
i += 1;
continue;
}
match fit.take() {
// End the line at the last break that fitted, then look at `i` again.
Some(j) if j > start => {
lines.push(line(&chars[start..j]));
start = j;
}
// One piece wider than the whole line: it gets a line of its own.
_ => {
lines.push(line(&chars[start..i]));
start = i;
i += 1;
}
}
}
if start < chars.len() || chars.is_empty() {
lines.push(line(&chars[start..]));
}
}
lines.join("\n")
}
/// ANYBOT_SHOT_EVERY=n: whether frame `frame` gets its own picture — every n-th frame from 40
/// to 80, and only before the run's own picture (frame `need`), so that picture always comes
/// last and ends the run (a short ANYBOT_SHOT_FRAMES used to leave the window open forever).
fn every_shot_due(frame: u32, n: u32, need: u32) -> bool {
n > 0 && frame.is_multiple_of(n) && (40..=80).contains(&frame) && frame < need
}
/// 新對話的問候:照設定裡的時區(不是系統時區)看現在幾點。
fn greeting(now: chrono::DateTime<chrono::Utc>, timezone: &str) -> &'static str {
use chrono::Timelike;
match now.with_timezone(&crate::routines::tz_of(timezone)).hour() {
5..=11 => "早安",
12..=17 => "午安",
18..=22 => "晚上好",
_ => "夜深了",
}
}
/// Screenshot-mode pictures as they arrive: (where it goes — `None` is the run's own — , picture).
type ShotQueue = Arc<Mutex<Vec<(Option<PathBuf>, Arc<egui::ColorImage>)>>>;
/// 主題、底色 bits、強調色、對比 bits、緊湊 — what `App::apply_theme` builds the shell from.
type ShellKey = (Theme, u32, String, u32, bool);
/// A centred dialog over a dimmed window: title and × on top, then the caller's body.
/// Returns true when the person asked to close it (×, Esc, or a click outside when `outside_closes`).
fn dialog(ctx: &egui::Context, id: &str, title: &str, width: f32, outside_closes: bool, p: Palette, content: impl FnOnce(&mut egui::Ui)) -> bool {
@ -7062,6 +7156,9 @@ fn dialog(ctx: &egui::Context, id: &str, title: &str, width: f32, outside_closes
// Read before the content runs: a text box drops its caret on Esc while it draws, so asked
// afterwards it would always say "no box had the caret".
let find_had_caret = ctx.memory(|m| m.has_focus(egui::Id::unique("page-find")));
// Never wider than the window (a narrow window keeps the whole dialog on screen).
let set_w = width.min(ctx.content_rect().width() - 32.0).max(280.0);
let mut sizing = false;
let resp = egui::Modal::new(egui::Id::unique(("dialog", id)))
.backdrop_color(Color32::from_black_alpha(if dark { 130 } else { 70 }))
.frame(
@ -7072,14 +7169,23 @@ fn dialog(ctx: &egui::Context, id: &str, title: &str, width: f32, outside_closes
.shadow(egui::epaint::Shadow { offset: [0, 12], blur: 36, spread: 0, color: Color32::from_black_alpha(if dark { 110 } else { 45 }) }),
)
.show(ctx, |ui| {
// Never wider than the window (a narrow window keeps the whole dialog on screen).
ui.set_width(width.min(ctx.content_rect().width() - 32.0).max(280.0));
// (egui lays a new window out once unseen, unconstrained, to learn its size.)
sizing = ui.is_sizing_pass();
ui.set_width(set_w);
// Header, body and footer sit flush; each sets its own inner spacing.
ui.spacing_mut().item_spacing.y = 0.0;
Frame::new().inner_margin(Margin { left: 20, right: 12, top: 12, bottom: 12 }).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(t(title)).strong().family(crate::bold()).size(FONT_XL));
// A long title (a bot's long name) is cut with … before the ×, never pushing
// the window wider. (Measured in the regular weight; the bold one runs ~6% wider.)
let full = t(title);
let shown = sidebar_ui::shorten_width(ui, &full, ((ui.available_width() - 40.0) * 0.94).max(60.0), FONT_XL);
let cut = shown != full;
let r = ui.label(RichText::new(shown).strong().family(crate::bold()).size(FONT_XL));
if cut {
r.on_hover_text(&full);
}
ui.add_space((ui.available_width() - 28.0).max(0.0));
// Drawn, not a glyph: not every Chinese font has "✕".
let (rect, r) = ui.allocate_exact_size(vec2(28.0, 28.0), egui::Sense::click());
@ -7099,6 +7205,11 @@ fn dialog(ctx: &egui::Context, id: &str, title: &str, width: f32, outside_closes
ui.painter().hline(r.x_range(), r.bottom(), Stroke::new(1.0, p.border));
content(ui);
});
// (The frame's 1 px stroke on each side is part of its size.)
let over = resp.response.rect.width() - set_w - 2.0;
if over > 1.0 && !sizing {
WIDER_DIALOGS.with(|v| v.borrow_mut().push((t(title), over)));
}
// Esc closes the dialog — except when the 目錄 box (⌘F) has the caret: there Esc just
// leaves the box.
let escape_pressed = ctx.input(|i| i.key_pressed(Key::Escape));
@ -7120,6 +7231,15 @@ fn bot_jump_key(ctx: &egui::Context) -> Option<usize> {
thread_local! {
/// The layout check (layout_audit) scrolls dialogs to see their lower rows.
static DIALOG_SCROLL: std::cell::Cell<Option<f32>> = const { std::cell::Cell::new(None) };
/// Dialogs drawn wider than they were set to be (title, px over): content that doesn't fit
/// pushes the whole window out past its own title bar. The layout check reports them.
static WIDER_DIALOGS: std::cell::RefCell<Vec<(String, f32)>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// The dialogs drawn wider than set since the last call (see WIDER_DIALOGS).
#[cfg(test)]
fn take_wider_dialogs() -> Vec<(String, f32)> {
WIDER_DIALOGS.with(|v| std::mem::take(&mut *v.borrow_mut()))
}
/// Where dialogs are scrolled to for a picture or a check: ANYBOT_SHOT_SCROLL=<points> (a
@ -8239,4 +8359,82 @@ mod tests {
assert_eq!(std::fs::read_to_string(&marker).unwrap().trim(), "clean");
relaunched.wait().unwrap();
}
/// 手動斷行:每一行都不超過寬度(只有單一個放不下的英文字例外);英文字中間不切,
/// 中文逐字可切;逗號句號等不放在行首,開括號不留在行尾。
#[test]
fn hand_wrapping_keeps_every_line_inside_the_width() {
let w = |s: &str| s.chars().count() as f32;
let out = super::wrap_to_width("一二三四五六七八九十", 4.0, w);
assert_eq!(out, "一二三四\n五六七八\n九十");
// Latin words stay whole and the line that would overflow breaks one word earlier.
let out = super::wrap_to_width("use your own Chrome window", 10.0, w);
assert_eq!(out, "use your\nown Chrome\nwindow");
for line in out.lines() {
assert!(w(line) <= 10.0, "{line:?} is wider than 10");
}
// A word wider than the line goes on its own line (nothing better to do).
assert_eq!(super::wrap_to_width("a verylongword b", 5.0, w), "a\nverylongword\nb");
// 行首不放「,」「。」「)」, 行尾不留「(」.
let out = super::wrap_to_width("一二三,四五六(七)", 3.0, w);
assert!(out.lines().all(|l| !l.starts_with([',', '。', ')']) && !l.ends_with('(')), "{out:?}");
// Mixed Chinese and English, measured as the card does.
let out = super::wrap_to_width("你平常的 Chrome 設定檔", 6.0, w);
for line in out.lines() {
assert!(w(line) <= 6.0, "{line:?} is wider than 6");
}
assert!(out.contains("Chrome"));
// Paragraphs stay paragraphs; a blank line stays.
assert_eq!(super::wrap_to_width("一二\n\n三", 9.0, w), "一二\n\n三");
}
/// ANYBOT_SHOT_EVERY 的逐幀截圖永遠排在這次的正式截圖之前:正式那張一到就收工,
/// ANYBOT_SHOT_FRAMES 設得比 80 小也一樣(以前視窗會一直開著)。
#[test]
fn per_frame_pictures_never_come_after_the_last_one() {
let due = |n, need| (0..200).filter(|f| super::every_shot_due(*f, n, need)).collect::<Vec<u32>>();
assert_eq!(due(10, 120), vec![40, 50, 60, 70, 80]);
assert_eq!(due(10, 60), vec![40, 50]);
assert!(due(10, 30).is_empty());
assert!(due(0, 120).is_empty());
}
/// 新對話的問候看的是設定裡的時區,不是這台電腦的系統時區。
#[test]
fn the_greeting_follows_the_timezone_setting() {
use chrono::TimeZone;
// UTC 01:00 = 台北 09:00(早安)= 紐約前一天 21:00(晚上好)。
let at = chrono::Utc.with_ymd_and_hms(2026, 11, 16, 1, 0, 0).unwrap();
assert_eq!(super::greeting(at, "Asia/Taipei"), "早安");
assert_eq!(super::greeting(at, "America/New_York"), "晚上好");
assert_eq!(super::greeting(chrono::Utc.with_ymd_and_hms(2026, 11, 16, 5, 0, 0).unwrap(), "Asia/Taipei"), "午安");
assert_eq!(super::greeting(chrono::Utc.with_ymd_and_hms(2026, 11, 16, 17, 0, 0).unwrap(), "Asia/Taipei"), "夜深了");
}
/// 設定 › 一般 的底色/對比/強調色/密度一改,下一幀整個殼就跟著換——不只「跟著系統」主題,
/// 淺色、深色主題也一樣(以前要重開 App 才看得到)。
#[test]
fn shell_dials_apply_on_the_next_frame_in_a_fixed_theme() {
use eframe::App as _;
let ctx = egui::Context::default();
let mut app = super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-shell-dials.png")));
app.state.theme = super::Theme::Light;
let mut frame = eframe::Frame::_new_kittest();
let mut run = |app: &mut super::App| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.ui(ui, &mut frame));
out.textures_delta.clear();
};
run(&mut app);
app.state.shell_accent = "indigo".into();
run(&mut app);
assert_eq!(app.pal.accent, crate::theme::shell(1.0, "indigo", 1.0, false).accent);
app.state.shell_tone = 0.0;
app.state.shell_contrast = 1.3;
run(&mut app);
assert_eq!(app.pal.pane, crate::theme::shell(0.0, "indigo", 1.3, false).pane);
assert_eq!(app.pal.border, crate::theme::shell(0.0, "indigo", 1.3, false).border);
app.state.dense = true;
run(&mut app);
assert_eq!(ctx.global_style().spacing.item_spacing, egui::vec2(8.0, 5.0));
}
}

View File

@ -502,7 +502,7 @@ impl App {
}
},
|ui| {
// (长的伺服器名字在行尾的按钮前截断,不会压到「重新连线」。)
// (長的伺服器名字在行尾的按鈕前截斷,不會壓到「重新連線」。)
ui.add(egui::Label::new(RichText::new(&name).strong().family(crate::bold()).size(FONT_BASE)).truncate());
let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover());
ui.painter().circle_filled(r.center(), 4.0, col);
@ -632,7 +632,7 @@ impl App {
}
},
|ui| {
// (长的技能名字在行尾的按钮前截断,不会压到「检视」。)
// (長的技能名字在行尾的按鈕前截斷,不會壓到「檢視」。)
ui.add(egui::Label::new(RichText::new(&name).strong().family(crate::bold()).size(FONT_SM).color(name_col)).truncate()).on_hover_text(&description);
if files > 0 {
ui.label(RichText::new(format!("{files} 檔")).size(11.0).color(p.accent));

View File

@ -192,6 +192,16 @@ fn scenes() -> Vec<(&'static str, Open)> {
}
}),
),
(
// 自訂顏色: its sliders used to push the whole window wider than its title bar.
"Bot 設定(自訂顏色)",
Box::new(|a: &mut App| {
if let Some(mut b) = a.state.bots.first().cloned() {
b.color = "#6b4a55".into();
a.edit_bot = Some((b, false));
}
}),
),
(
"例行任務",
Box::new(|a: &mut App| {
@ -274,6 +284,9 @@ fn audit_one(font: &str, worst: bool) -> Vec<String> {
for p in problems(&shapes, worst) {
report.push(format!("[{data} {font} {w:.0}] {name}: {p}"));
}
for (title, over) in super::take_wider_dialogs() {
report.push(format!("[{data} {font} {w:.0}] {name}: 「{title}」視窗被內容撐寬 {over:.0}px"));
}
if step > 0 && fresh == 0 {
break;
}

View File

@ -718,25 +718,27 @@ impl App {
ui.spacing_mut().item_spacing.x = gap;
for (label, value, note) in row {
Frame::new().fill(p.muted).stroke(Stroke::new(1.0, p.border)).corner_radius(12).inner_margin(Margin { left: 14, right: 14, top: 12, bottom: 12 }).show(ui, |ui| {
ui.set_width(tile_w - 28.0);
// (tile = 14 + 14 px margins and the 1 px stroke on each side around this.)
ui.set_width(tile_w - 30.0);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 3.0;
ui.add(egui::Label::new(RichText::new(label).size(11.0).color(p.text3)).wrap());
// A long value (a phrase, not a number) a size smaller, so it doesn't fill the tile.
// An arrow up front is a verdict: green up, red down (with the arrow
// itself as the non-colour signal).
let (size, col) = match value.chars().next() {
Some('↑') | Some('+') => (26.0, p.up),
Some('↓') | Some('−') => (26.0, p.danger),
_ if value.chars().count() > 10 => (16.0, p.text),
_ => (26.0, p.text),
// A long value (a phrase, not a number) a size smaller, so it doesn't fill
// the tile — with or without a direction in front.
// A direction up front is a verdict: green up, red down (the arrow or
// sign itself is the non-colour signal). Same rule as the phone.
let size = if value.chars().count() > 10 { 16.0 } else { 26.0 };
let col = match crate::pages::stat_trend(value) {
Some(true) => p.up,
Some(false) => p.danger,
None => p.text,
};
ui.add(egui::Label::new(RichText::new(value).size(size).strong().family(crate::bold()).color(col)).wrap());
if !note.is_empty() {
let nc = match note.chars().next() {
Some('↑') | Some('+') => p.up,
Some('↓') | Some('−') => p.danger,
_ => p.text2,
let nc = match crate::pages::stat_trend(note) {
Some(true) => p.up,
Some(false) => p.danger,
None => p.text2,
};
ui.add(egui::Label::new(RichText::new(note).size(11.5).color(nc)).wrap());
}

View File

@ -130,6 +130,25 @@ pub fn hex_of_hsv(hsv: [f32; 3]) -> String {
format!("#{:02x}{:02x}{:02x}", q(r + m), q(g + m), q(b + m))
}
/// Hues across the custom colour grid.
pub const SWATCH_COLUMNS: usize = 12;
/// The custom colours to click (Bot 設定 › 頭像 › 自訂), rows of `SWATCH_COLUMNS`: four tones of
/// twelve hues — soft, clear, deep, dark — then a grey row from light to dark. Each is a "#rrggbb"
/// the bot keeps as its colour.
pub fn custom_swatches() -> Vec<Vec<String>> {
let tones = [(0.30, 0.92), (0.62, 0.86), (0.78, 0.66), (0.70, 0.42)];
let mut rows: Vec<Vec<String>> = tones.iter().map(|&(s, v)| (0..SWATCH_COLUMNS).map(|i| hex_of_hsv([i as f32 * 360.0 / SWATCH_COLUMNS as f32, s, v])).collect()).collect();
rows.push((0..SWATCH_COLUMNS).map(|i| hex_of_hsv([0.0, 0.0, 0.92 - 0.8 * i as f32 / (SWATCH_COLUMNS - 1) as f32])).collect());
rows
}
/// A colour the person typed ("6B4A55", "#6b4a55 "): "#rrggbb" in lowercase, or None.
pub fn parse_hex(s: &str) -> Option<String> {
let h = s.trim().trim_start_matches('#');
(h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit())).then(|| format!("#{}", h.to_ascii_lowercase()))
}
fn ellipse_points(c: Pos2, rx: f32, ry: f32, rot: f32, n: usize) -> Vec<Pos2> {
let (s, co) = rot.sin_cos();
(0..n)
@ -370,6 +389,35 @@ pub fn avatar(ui: &mut egui::Ui, size: f32, shape: &str, col: Color32) -> egui::
mod tests {
use super::*;
/// 自訂顏色是點的,不是滑的:每列 12 個色相(淡→深四列),最後一列灰階;全部是不同的
/// 色碼,都算「自訂」。
#[test]
fn custom_swatches_are_a_grid_of_distinct_hex_colours() {
let rows = custom_swatches();
assert_eq!(rows.len(), 5);
assert!(rows.iter().all(|r| r.len() == SWATCH_COLUMNS));
let all: Vec<&String> = rows.iter().flatten().collect();
let mut uniq = all.clone();
uniq.sort();
uniq.dedup();
assert_eq!(uniq.len(), all.len(), "every swatch is a different colour");
assert!(all.iter().all(|h| is_custom(h) && parse_hex(h).as_deref() == Some(h.as_str())));
// The grey row runs light → dark.
let grey = &rows[4];
assert!(color(&grey[0]).r() > color(&grey[SWATCH_COLUMNS - 1]).r());
}
/// 色碼欄:有沒有 #、大小寫、前後空白都收;不是六位十六進位就不收。
#[test]
fn a_typed_hex_is_cleaned_or_refused() {
assert_eq!(parse_hex("#6B4A55").as_deref(), Some("#6b4a55"));
assert_eq!(parse_hex(" 6b4a55 ").as_deref(), Some("#6b4a55"));
assert_eq!(parse_hex("#6b4a5"), None);
assert_eq!(parse_hex("#6b4a5g"), None);
assert_eq!(parse_hex(""), None);
assert_eq!(parse_hex("red"), None);
}
#[test]
fn custom_hex_roundtrip() {
assert!(is_custom("#7a4bd6"));

View File

@ -401,6 +401,22 @@ pub fn stats(src: &str) -> Vec<(String, String, String)> {
.collect()
}
/// A stats value's or note's direction: `Some(true)` up (↑, +), `Some(false)` down (↓, −, and
/// the plain "-" bots usually type), `None` neither. A sign counts only when something follows
/// it right away — a lone "-" is "no data", not a drop. (mobile/index.html `trend` is the same rule.)
pub fn stat_trend(s: &str) -> Option<bool> {
let mut it = s.trim_start().chars();
let first = it.next()?;
let signed = it.next().is_some_and(|c| !c.is_whitespace());
match first {
'↑' => Some(true),
'↓' => Some(false),
'+' if signed => Some(true),
'−' | '-' if signed => Some(false),
_ => None,
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Step {
Done,
@ -481,7 +497,8 @@ pub fn chart(src: &str) -> Option<Chart> {
title = t.trim().to_string();
continue;
}
let cells: Vec<String> = line.split('|').map(|c| plain(c.trim())).collect();
// (A closing "|", as Markdown tables are often typed, is not one more empty column.)
let cells: Vec<String> = line.trim_end_matches('|').split('|').map(|c| plain(c.trim())).collect();
if cells[0].is_empty() && labels.is_empty() {
labels = cells[1..].to_vec();
continue;
@ -496,6 +513,10 @@ pub fn chart(src: &str) -> Option<Chart> {
labels = series.iter().map(|(s, _)| s.clone()).collect();
series = vec![(String::new(), series.iter().map(|(_, v)| v[0]).collect())];
}
// A pie of one plain row: its one slice is named after that row (not 「1」).
if kind == ChartKind::Pie && labels.is_empty() && series.len() == 1 && series[0].1.len() == 1 {
labels = vec![series[0].0.clone()];
}
let n = labels.len().max(series.iter().map(|(_, v)| v.len()).max().unwrap_or(0));
if series.is_empty() || n == 0 {
return None;
@ -552,6 +573,23 @@ pub fn demo(now: i64) -> (Vec<Page>, u64, u64) {
mod tests {
use super::*;
/// 數字卡的漲跌(桌面和手機同一套規則):箭頭、+、全形 −,還有 Bot 最常寫的一般「-」。
/// 單獨一個符號(「-」當作「沒有資料」)不算漲跌。
#[test]
fn stat_trend_reads_arrows_and_both_minus_signs() {
assert_eq!(stat_trend("↑ 12%"), Some(true));
assert_eq!(stat_trend("+12%"), Some(true));
assert_eq!(stat_trend("↓ 3"), Some(false));
assert_eq!(stat_trend("−5%"), Some(false));
assert_eq!(stat_trend("-12%"), Some(false));
assert_eq!(stat_trend("-"), None);
assert_eq!(stat_trend("+"), None);
assert_eq!(stat_trend("- 待補"), None);
assert_eq!(stat_trend("—"), None);
assert_eq!(stat_trend("2027 Q2"), None);
assert_eq!(stat_trend(""), None);
}
#[test]
fn chart_parses_plain_multi_series_and_pie() {
let c = chart("bar 月度下載\n1月 | 120\n2月 | 320\n3月 | 240").unwrap();
@ -572,6 +610,21 @@ mod tests {
assert_eq!(chart_num(2.5), "2.5");
}
/// Markdown 表格習慣在列尾多打一個「|」:不會多出一欄空的「3」。只有一行的圓餅,那一片叫
/// 那一行的名字,不是「1」。(手機的 chartParse 同樣這麼讀。)
#[test]
fn chart_ignores_a_closing_pipe_and_names_a_lone_pie_slice() {
let c = chart("bar\n| 1月 | 2月 |\n下載 | 120 | 320 |\n上傳 | 90 | 140 |").unwrap();
assert_eq!(c.labels, vec!["1月", "2月"]);
assert_eq!(c.series[0], ("下載".into(), vec![120.0, 320.0]));
let c = chart("bar 月度\n1月 | 120 |\n2月 | 320 |").unwrap();
assert_eq!(c.labels, vec!["1月", "2月"]);
assert_eq!(c.series, vec![(String::new(), vec![120.0, 320.0])]);
let c = chart("pie 車主意向\n想訂閱 | 520").unwrap();
assert_eq!(c.labels, vec!["想訂閱"]);
assert_eq!(c.series.len(), 1);
}
#[test]
fn a_colleagues_page_is_listed_and_read_but_stays_its() {
let mut pages = vec![];

View File

@ -78,7 +78,7 @@ pub const LIGHT: Palette = Palette {
// primary hover #dbdbdb; translucent tokens are the ink at hover 6%, active 8%, agent bubble 4%,
// user bubble 18%, text 66/54%, border 10%. Accent blue/0 #1884fc, danger red/0 #fc2c3e.
// Measured from the original's dark window: chat rgb 19, sidebar 16, bubbles/cards 31–33.
// Kept as the documented reference of 「纸 dark」; the live dark palette comes from `shell`.
// Kept as the documented reference of 「紙」dark; the live dark palette comes from `shell`.
#[allow(dead_code)]
pub const DARK: Palette = Palette {
pane: hexa(0x1e, 0x1d, 0x1b, 0xff),
@ -167,7 +167,7 @@ pub const ACCENTS: [(&str, &str, Color32, Color32); 8] = [
pub fn shell(tone: f32, accent: &str, contrast: f32, dark: bool) -> Palette {
let tone = tone.clamp(0.0, 1.0);
let c = contrast.clamp(0.6, 1.5);
// Cool end is Linear's neutral grey; warm end is 「纸」 (the shipped default, tone=1).
// Cool end is Linear's neutral grey; warm end is 「紙」 (the shipped default, tone=1).
let (paper, ink) = if dark {
(mix(rgb(0x10, 0x11, 0x13), rgb(0x1e, 0x1d, 0x1b), tone), mix(rgb(0xf1, 0xf1, 0xf3), rgb(0xf2, 0xf0, 0xeb), tone))
} else {
@ -269,7 +269,7 @@ mod tests {
#[test]
fn shell_defaults_land_on_the_shipped_paper_palette() {
// tone=1 (warm) + clay + contrast 1 must reproduce 「纸」 within rounding.
// tone=1 (warm) + clay + contrast 1 must reproduce 「紙」 within rounding.
let s = shell(1.0, "clay", 1.0, false);
assert_eq!(s.pane, LIGHT.pane);
assert_eq!(s.text, LIGHT.text);