From ef2c97a76f400db9255f58f3dd0e18fb07ea5d7b Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 26 Nov 2026 22:40:28 +0800 Subject: [PATCH] feat(xiaoyi): consolidate Stitch components and conversation motion --- apps/detail-photocraft/Cargo.lock | 2 +- apps/detail-photocraft/DESIGN.md | 60 +- .../crates/ui-egui/src/jiansun.rs | 282 +++- .../ui-egui/src/jiansun/agent_motion.rs | 246 ++- .../crates/ui-egui/src/jiansun/agent_panel.rs | 251 ++-- .../ui-egui/src/jiansun/agent_stream.rs | 81 +- .../crates/ui-egui/src/jiansun/blob_warp.rs | 13 +- .../crates/ui-egui/src/jiansun/glow_pill.rs | 4 +- .../ui-egui/src/jiansun/operation_error.rs | 125 +- .../crates/ui-egui/src/jiansun/siri_orb.rs | 628 ++++++-- .../ui-egui/src/jiansun/stitch_cache.rs | 272 ++++ .../crates/ui-egui/src/jiansun/stitch_kit.rs | 533 +++++++ .../ui-egui/src/jiansun/stitch_state.rs | 641 ++++++++ .../ui-egui/src/jiansun/stitch_timeline.rs | 1060 +++++++++++++ .../crates/ui-egui/src/jiansun/stitch_ui.rs | 1319 ++++++++++++----- .../ui-egui/src/jiansun/test_support.rs | 35 + .../crates/ui-egui/src/jiansun/typing_text.rs | 533 ++++++- .../crates/ui-egui/src/theme.rs | 364 +++++ 18 files changed, 5618 insertions(+), 831 deletions(-) create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_cache.rs create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/test_support.rs diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 887d6621..3fc512a6 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -4993,11 +4993,11 @@ dependencies = [ "dispatch2", "eframe", "egui", + "flate2", "fmv-macos-events", "futures-lite", "image", "keyring", - "flate2", "log", "muda", "objc2 0.6.5", diff --git a/apps/detail-photocraft/DESIGN.md b/apps/detail-photocraft/DESIGN.md index e63dd068..43da5bf6 100644 --- a/apps/detail-photocraft/DESIGN.md +++ b/apps/detail-photocraft/DESIGN.md @@ -76,7 +76,7 @@ Cult UI 和 SmoothUI 用作交互与视觉参考,客户端以原生组件实 | Prompt Composer | 小壹消息输入与附件 | 部分 | | Halo Search | 项目、提示词搜索 | 部分 | | Prompt Library | 输入区旁的账号提示库 | 待验证 | -| AI Blob Warp | 原生blob_warp独立扭曲色带,接真实图片等待区;Siri Orb不重复计入 | 部分;回归/离屏通过,真实新等待待验 | +| AI Blob Warp | 原生blob_warp独立扭曲色带;目前只在测试构建里编译(`agent_motion.rs` 以 `#[cfg(test)]` 挂载),生产等待区用的是光涌与光球;Siri Orb不重复计入 | 未接入;去留待定 | | Halo Dropzone | 产品资料参考图 | 待验证 | | Timer | 真实任务耗时 | 部分 | | Halo Input | 小壹及产品资料输入 | 部分 | @@ -102,9 +102,9 @@ Cult UI 和 SmoothUI 用作交互与视觉参考,客户端以原生组件实 | AI Task List | 真实任务列表 | 待验证 | | AI Context Meter | Pi 模型容量与当前项目有效用量的百分比 | 已接入 | | Siri Orb | 输入框待命及本地输入反馈;真实任务另由任务卡表达 | 待命/输入连续实窗采集通过;减少动态为回归证据 | -| Fluid Hover Highlight | 项目及候选等真实操作区 | 待验证 | +| Fluid Hover Highlight | 库内保留 `hover_highlight` 原语,暂无生产调用方;项目卡与候选各自使用局部悬停表面 | 未接入 | -`jiansun/agent_motion.rs` 使用真实状态驱动共享运动:`Surface::new(id, rect, radius)` 的 ID 必须是组件或业务目标稳定身份,不使用屏幕坐标;需要在内容之下绘制时,在 Frame 内容闭包中用 `reserve_background` 保留绘制位置并通过 `behind` 关联,必要时使用 `clipped_to` 约束裁剪。`component_light` 的 `Idle`、`Hover`、`Focus`、`Running`、`Stopped` 描述真实交互与任务状态;只有实际任务运行才传入 `Running`。`waiting_field` 仅用于尚无结果的真实等待,不能据此创造进度或修改轨迹。`message_enter` / `message_repaint`、`image_enter` / 图片入场模糊由调用方依据真实消息与结果生命周期使用,不得因滚动或重绘反复播放。 +`jiansun/agent_motion.rs` 使用真实状态驱动共享运动:`Surface::new(id, rect, radius)` 的 ID 必须是组件或业务目标稳定身份,不使用屏幕坐标;需要在内容之下绘制时,在 Frame 内容闭包中用 `reserve_background` 保留绘制位置并通过 `behind` 关联,必要时使用 `clipped_to` 约束裁剪。`component_light` 只有 `Idle`、`Hover`、`Focus` 三个状态(没有 `Running`、`Stopped`,也没有 `waiting_field`):闲置时只有细边巡行,悬停与聚焦才点亮。任务运行由任务卡的光涌表达,不传给流光;尚无结果的等待由光涌与光球表达,不能据此创造进度或修改轨迹。`message_enter` / `message_repaint`、`image_enter` / 图片入场模糊由调用方依据真实消息与结果生命周期使用,不得因滚动或重绘反复播放。 各动效调用须传入同一用户设置的 `reduce_motion`:减少动态时停止循环及位移,保留可辨识的状态和操作;局部原生组件自身的过渡也应遵守该设置。光效与内容分层绘制,不应遮挡文字、图像或输入。隐藏区域不应为了动画持续重绘。当前设置弹层已接入默认关闭的同帧毛玻璃试验,只有显式设置 `PHOTOCRAFT_EXPERIMENTAL_STITCH_GLASS=1` 且渲染能力可用时启用;静态半透明、柔雾或图片入场模糊不能作为背景模糊的证据。本地窗口已对高对比文字做同帧对照,设备丢失、资源异常和性能仍待验证,不应宣称正式可用。 @@ -189,7 +189,7 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 - 流光使用统一两档视觉:`Inactive` 仅显示清楚、明亮的半圈渐变细光带,不绘制内晕染;`Active` 为同一光带加向内柔和晕染,内外位置、颜色顺序和转速完全绑定。带外保留原有中性暗边,禁止整圈彩色高亮。保持紫→青→紫,不使用近白彗星头,不靠加粗、大面积色底或外扩光圈增强亮度。减少动态时一起冻结当前光带与内雾位置。 - 2026-10-28亲自查看 Cult UI Halo Button、Border Beam Button 与 SmoothUI Border Beam 实际网页后,用户提供更精确截图并明确最终约束:约半圈紫→青→紫的移动渐变,内外光效绑定。用户最新截图与说明优先于官网其他短彗星变体,因此不采用先前16%短光段或5秒/9秒独立相位。0.8逻辑点、9秒一周属于客户端设计参数,不宣称为Stitch内部参数。当前Stitch画布可见同样紫青参考图;尚未通过DOM独立核实资源标识`17294198817713014040`。参考:[Cult UI](https://www.cult-ui.com/docs/components/border-beam-button)、[SmoothUI](https://smoothui.dev/docs/components/border-beam)。 - 处理中的激活流光归属于当前任务卡片。输入浮层不会继承任务的 Running 状态;任务运行时使用 `Inactive`,即使保留输入焦点或鼠标悬停也不增加内晕染。停止后任务卡收敛到 `Inactive`,Orb 静止;完成后任务卡退场,输入框仍为未激活细边。空闲时真实聚焦按 `Active`、悬停按 `Inactive`,组件不自行发明第三种材质。 -- 小壹头像与任务标识参考 SmoothUI Siri Orb 的柔和粉、青、紫内部色场、圆形遮罩与球面高光;禁止以描边圆圈、轨道或点阵代替球体。历史消息静止,处理中只加快内部运动,不暗示语音输入。2026-10-29 修订:输入框内的实时小壹入口(包括空白 mini)默认缓慢流动并轻缓呼吸,输入时增强;回到空闲时平滑减速,不重置相位。此为待命身份动效,不代表模型已经调用;处理中输入框仍不继承任务卡的激活流光。减少动态效果冻结色场与呼吸,隐藏、裁掉或最小化时不因 Orb 安排重绘。 +- 小壹头像与任务标识的球面形态参考 SmoothUI Siri Orb 的圆形遮罩与球面高光;禁止以描边圆圈、轨道或点阵代替球体。2026-11-26 修订:内部色场改为小壹自己的四层液态微光——暖玉白基底上,琥珀、冷月青、暖玉白与月芯四层缓缓绕行,球外一圈冷月青柔光;不再使用粉、青、紫。历史消息静止,处理中只加快内部运动,不暗示语音输入。2026-10-29 修订:输入框内的实时小壹入口(包括空白 mini)默认缓慢流动并轻缓呼吸,输入时轻柔响应;回到空闲时平滑减速,不重置相位。此为待命身份动效,不代表模型已经调用;处理中输入框仍不继承任务卡的激活流光。减少动态效果冻结色场与呼吸,隐藏、裁掉或最小化时不因 Orb 安排重绘。 - 2026-10-29 精简:对话内容区去掉重复的 Orb+“小壹”标题行,直接展示回复、处理对象与候选结果;身份入口保留在首位“小壹”标签和输入框内,任务卡继续展示真实任务状态。 - 对话中的候选卡片按图片比例显示,页号和候选序号叠在图内底部,悬停可查看完整图位和花色。同一轮的后续选项放在图片下方。身份缺失或不唯一时使用通用候选名称。产品资料的参考图读取与同步使用真实任务状态展示不确定进度,不推测百分比。 - 提示库遇到云端版本冲突后,只有成功读取最新云端快照才能继续“保留本机”;刷新失败时保留草稿、提示先同步。线上个人提示库尚未随本地改动部署。 @@ -206,8 +206,8 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 | 实际入口 | 组件角色 | 激活规则 | | --- | --- | --- | | `agent_panel::paint_tag`,小壹标签 | Entry | 只保留细边;处理任务不激活入口内雾。 | -| `agent_panel::processing_card_ui`,任务卡 | Task | 真实运行时激活;本地停止后收敛为细边并保留原请求;任务结束后整体约160ms淡出。 | -| `agent_panel`,对话输入浮层 | Composer | 待处理任务存在时优先Inactive,即使仍有键盘焦点或悬停;空闲时真实聚焦可激活。 | +| `agent_panel::processing_card_ui`,任务卡 | 光涌(不经 `role_light`) | 真实运行时光涌起伏;本地停止后 190ms 收敛并保留原请求;任务结束后整体淡出。 | +| `agent_panel`,对话输入浮层 | 光涌(不经 `role_light`) | 发送后 640ms 发送脉冲;运行、聚焦、悬停时满帧,纯待机平滑降频。 | | `canvas_workspace`,真实操作目标框 | CanvasTarget | 只画共享细边与真实操作标识,不绘制内雾覆盖作品。 | 图像等待色场、Siri Orb、普通中性按钮/菜单/字段各自保留原语义,选中图片使用未激活细边,不为统一而新增整圈流光。减少动态效果时立即使用对应静态状态;未知结果不显示为完成,也不重发。控制通道可只读核对`composerLightMode`、`processingLightMode`及`processingOpacity`,它们记录实际渲染状态,不提供伪造任务入口。 @@ -322,7 +322,7 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 - 创建流程的Escape一次只退一层:先关闭当前菜单或退出字段,再返回上一步;商品简报退回画布时保留脏草稿,不擅自取消运行任务。250pt窄栏以共享Stitch更多菜单收纳参考图及提示词库,发送和停止始终完整可见,高DPI按逻辑点布局。 ### 2026-10-31 全景Stitch组件边界 -- Agent调用方统一使用实际共享组件:`segmented_control`持有整组选中胶囊、键盘与禁用状态,`filter_chip`是独立28pt筛选选项,`file_drop_zone`持有真实拖入视觉与原生响应,`menu_item`持有菜单行;`icon_button`沿用Agent专用tokens与现有SVG。规范化名称复用已有原生实现,新增行为由真实组件承担,不以空代理或额外Frame宣称视觉完成。 +- Agent调用方统一使用实际共享组件:`segmented_control`持有整组选中胶囊、键盘与禁用状态,`filter_chip`是独立34点筛选选项,`file_drop_zone`持有真实拖入视觉与原生响应,`menu_item`持有菜单行;`icon_button`沿用Agent专用tokens与现有SVG。规范化名称复用已有原生实现,新增行为由真实组件承担,不以空代理或额外Frame宣称视觉完成。 - 提示词每条内容使用`surface_card`,12pt圆角、中性轻描边与12pt内距,填满可用列;160ms悬停背景处于正文下层,不拦子操作,前景遮挡不触发悬停。卡片与子控件ID由账号、来源及真实条目ID隔离,过滤/同步不能将键盘操作漂移到其他条目。 - 所有Agent按钮的布局框不随hover、pressed或键盘焦点变化;焦点轮廓在既有几何内绘制,Quiet也必须可见,禁用及减少动态保留真实语义。250pt的125%与150%缩放均需验证更多菜单和完整发送/停止入口。 - 空草稿的输入栏在工具按钮按下至释放及自身“更多”菜单打开期间保持展开,避免输入框失焦使释放目标提前收缩;关闭菜单后自然回到待命,普通悬停不持续撑开输入栏。验证必须包含空草稿的分帧按下、保持、释放和真实菜单操作。 @@ -446,3 +446,49 @@ Agent 导入的完全透明页面背景以原生“无填充”表达,保留 制作使用当前模板组件的原稿版本、图层映射及图文关系。模板可声明场景或同款原片、目标部件、主体数量、构图限制和样例图层,商品名称、颜色和部件由当前款式的资料及实拍提供。详情屏数、主图和 SKU 布局取自有实际字段映射的输出。校验、派发、验图、回填、导出使用同一流程。 详情、主图和 SKU 的前台选中视图由用户决定。后台切换工作步骤保留当前视图,人工修改过的文字和图片由用户版本优先。 + +## 小壹组件库第 1 批:Token、结构化状态与空转治理 + +2026-11-26。本批只补库、校准品牌动效、加守卫,不改时间流与面板的业务结构;第 2 批再把 `agent_panel` 迁到这些库件上。四条红线全部守住:光涌的玻璃质感、流光与发送脉冲原样保留;对话框与输入框的展开收缩动画原样保留;逐字节奏改为 300ms 加 15ms 步进;`panel_geometry` 的字符串键一个不改。 + +**Token(`theme.rs`)。** 原生 `Tokens` 的十四套主题一个字节不动,字体注册逻辑也未触碰;小壹的增量都在 `agent()` 之后: + +| 类别 | 入口 | 内容 | +|---|---|---| +| 语义色 | `Tokens::agent_semantic()` | 成功、已核验、进度、进行中;冷月青、琥珀、暖玉白、月芯(光球);正文与用户两套逐字柔光;菜单基底、玻璃静止/点亮底、模态遮罩;叠图文字与衬底;未读圆点四层 | +| 字体阶梯 | `agent_scale::Type` | Caption 11、Meta 12、Title 13、Body 14、Subheading 15、Heading 16、TitleLg 18、Display 20;`size()` / `font_id()` / `semibold()` | +| 间距 | `agent_scale::space` | 2 / 4 / 8 / 12 / 16 / 24,另有作用域默认项间距 (10, 10) 与按钮内距 (12, 7) | +| 圆角 | `agent_scale::radius` | 行 6、菜单 8、控件 9、标签 12、对话框 20、输入浮层 24(收起 28) | +| 控件高度 | `agent_scale::control` | 行 24、紧凑 26、标准 28、发送 30、菜单行 32、默认 34、命令行 36 | +| 图标 | `agent_scale::icon` | 12 / 14 / 16,发送箭头 15 | +| 动效时长 | `agent_scale::motion` | 见下 | + +`agent()` 同时补齐了此前漏掉的 `chrome / canvas_dot / separator / shadow / row_selected / accent_text / scrim`:换任何宿主主题,小壹的每个表面读出来都一样,浅色宿主的分隔线、阴影、选中行与遮罩不再漏进来。 + +**品牌动效的定稿参数。** + +- 逐字扩散(输入框、用户气泡、回复正文共用 `typing_text.rs`):单字 300ms cubic-out 入场,自下方 4 点升起并从 1.035 倍收拢到原大;相邻两字步进 15ms,同一批到达的字按字素簇铺开,积压时整体压回 650ms。一次到达激起一道柔光,以每字 22ms 向回传、按 exp(−距离/9) 衰减,在流头身后留下约 11 字宽的尾韵;流头另有一团柔光。尚未轮到的字以 12% 的光雾占位,光标不会跑到文字前面。回复里柔光垫在字形下面;输入浮层的文字经光涌透镜绘制,柔光由 `typing_text::paint_glow` 画在玻璃上面、文字光标下面。 +- 停止:流光、内雾与占位、光球的减速定格统一收敛在 190ms;光球停下时略微变暗。 +- 光球档位:待机极柔慢呼吸、输入轻柔响应、运行平稳流动、等待结果慢一档巡视、暂停减速变暗定格。 +- 光涌:玻璃光场、流光与 640ms 发送脉冲原样不动,只改了“什么时候申请下一帧”。 +- 对话框与输入框的展开收缩没有改动:同一个临界阻尼弹簧(角频率 20)、弹窗 220ms 入 160ms 出、选项行的渐变都保持原值,只是数值搬进了 `motion` Token。 + +**重绘档位(`agent_motion::schedule`)。** 装饰动画申请下一帧只有一个出口:发送脉冲、任务运行、悬停聚焦、逐字入场按 16ms 满帧;纯待机在最后一次满帧请求 1.5s 之后平滑降到 32ms,帧间隔只增不减;15s 内没有任何输入再降到 50ms;窗口最小化或区域不可见时一帧都不申请。 + +**组件库新增原语。** + +| 模块 | 内容 | +|---|---| +| `jiansun/stitch_state.rs` | `Tone`、`ToolStatus`、`WorkerStage`、`NoticeKind`、`RunState`、`ErrorCategory`、`FieldState`、`WaitingState`,各自带规范文案、色调与图标。线上字符串只在 `ToolStatus::parse`、`WorkerStage::infer`、`ErrorCategory::classify`、`BadgeKind::from_status_text` 四处各解析一次 | +| `jiansun/stitch_kit.rs` | `label / caption / page_title / section_heading / empty_state`、`inline_notice`、`stop_button`、`waiting_card`、`adaptive_grid`、`list_row`、`status_badge`、`on_image_caption` | +| `jiansun/stitch_timeline.rs` | 时间流 11 块外壳:用户消息、处理对象、思考、工具组、通知、回复、图片集、待审核卡、交互卡、结果反馈卡、建议行;目标驾驶舱 `goal_progress_panel` | +| `jiansun/stitch_cache.rs` | 已定稿文字的排版缓存:历史回复连画几帧只排版一次,换宽度、字体或缩放才重排 | +| `jiansun/stitch_ui.rs` | `focus_ring`(六种规格,库内八处手绘已统一)、`GlowPace`、`tool_group_head`、`task_status_row`、`paint_status_badge`、`user_bubble_with_reveal`;字号、间距、圆角与时长字面量全部换成 Token | + +目标驾驶舱 `GoalProgressPanel`:主条有进度环、状态与当前步骤、流水线(详情页 → 主图 → SKU 图)、预算、展开钮与停止钮;展开后是路线图抽屉(各阶段进度条、图位、子代理列表)。预算支持两种口径:`GoalBudget::Time`(已用 / 上限,上限未知时只报已用)与 `GoalBudget::Tokens`;抽屉里的每个阶段可以同时带时段明细与 Token 明细。窄栏(不超过 260 点)把整行让给步骤名。 + +**守卫(`jiansun.rs`)。** 既有守卫的文件清单补上新模块;新增四条:库内生产代码不得出现字号字面量与原始颜色构造;业务代码的字号字面量只许减少(棘轮基线);`panel_geometry` 的 92 个字符串键冻结,改名、删除或新增未登记的键都会失败;库内带中文的文案行不得出现实现方的产品名。 + +**接入情况。** 已在本批接入生产代码的:语义色与阶梯 Token(库内全部字面量已替换)、`focus_ring`、`task_status_row`、`tool_group_head`、`paint_status_badge`、用户气泡(减少动态已一路透传)、输入浮层的光涌档位、输入框的光球档位与柔光、排版缓存、错误提示的类别驱动(`operation_error.rs`)。 + +**仍未接入。** 时间流 11 块外壳、目标驾驶舱、等待卡、提示条、停止钮、自适应网格、列表行、独立状态徽标、叠图说明都还没有生产调用方,第 2 批接入;`Hover Highlight`、`Blob Warp` 维持原状。 diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index a08d4b61..fcc739cc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -47,7 +47,13 @@ mod project_browser; #[cfg(not(target_arch = "wasm32"))] mod project_file; mod recording_mutation; +mod stitch_cache; +mod stitch_state; +mod stitch_kit; +mod stitch_timeline; mod stitch_ui; +#[cfg(test)] +pub(crate) mod test_support; mod template_slots; mod workflow_bridge; mod workflow_export; @@ -415,6 +421,7 @@ fn project_refresh_due(visible: bool, focused: bool, was_visible: bool, was_focu #[cfg(test)] mod project_refresh_tests { + use super::*; fn workspace() -> (Workspace, mpsc::Receiver, mpsc::Sender) { let (tx, requests) = mpsc::channel(); @@ -4785,6 +4792,7 @@ fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &st #[cfg(test)] mod tests { + use crate::jiansun::test_support::SettleUi; #[test] fn agent_ui_callers_use_shared_stitch_controls() { let files = [ @@ -4810,6 +4818,10 @@ mod tests { ("workflow_bridge", include_str!("jiansun/workflow_bridge.rs")), ("workflow_export", include_str!("jiansun/workflow_export.rs")), ("visual_preview_ui", include_str!("jiansun/visual_preview_ui.rs")), + ("stitch_cache", include_str!("jiansun/stitch_cache.rs")), + ("stitch_state", include_str!("jiansun/stitch_state.rs")), + ("stitch_kit", include_str!("jiansun/stitch_kit.rs")), + ("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")), ]; let forbidden = ["egui::Button::", "egui::Separator::", "egui::Spinner::", "egui::Window::", "egui::ComboBox::from_", ".button(", ".small_button(", ".checkbox(", ".radio(", ".selectable_", ".spinner(", ".separator("]; for (name, source) in files { @@ -4821,6 +4833,232 @@ mod tests { } } + /// 生产代码 = 测试模块之前的全部源码(与上面的守卫同一种切分方式)。 + fn production_of(source: &str) -> String { + let normalized = source.replace("\r\n", "\n"); + normalized.split("#[cfg(test)]\nmod tests").next().unwrap_or("").to_owned() + } + + /// `FontId::proportional(<数字>)` 与 `.size(<数字>)` 的出现次数。 + fn size_literals(source: &str) -> usize { + ["FontId::proportional(", ".size("].into_iter().map(|needle| { + source + .match_indices(needle) + .filter(|(index, _)| source[*index + needle.len()..].trim_start().starts_with(|c: char| c.is_ascii_digit())) + .count() + }).sum() + } + + /// `Color32::from_*` 原始颜色构造的出现次数。 + fn raw_colours(source: &str) -> usize { + [ + "Color32::from_rgb(", "Color32::from_black_alpha(", "Color32::from_white_alpha(", "Color32::from_gray(", + "Color32::from_rgba_unmultiplied(", "Color32::from_rgba_premultiplied(", + ].into_iter().map(|needle| source.matches(needle).count()).sum() + } + + /// 外部 QA 脚本与 `jiansun.state` 控制通道读取的 `panel_geometry` 键,按字母序冻结。 + /// 只许原样保留:改名、删除都会让脚本读不到矩形。新增键必须同步外部脚本并登记在这里。 + const PANEL_GEOMETRY_KEYS: [&str; 92] = [ + "agentStatus", + "attachmentRemovals", + "backgroundDocument", + "candidateTraceRect", + "composer", + "composerExpanded", + "composerFocused", + "composerLightMode", + "composerMore", + "composerMorph", + "composerOrb", + "composerOrbMotion", + "composerOrbPhase", + "composerOrbSpeed", + "composerOrbTyping", + "contextIndicator", + "contextPercent", + "conversationBottomGap", + "conversationClip", + "conversationScrollOffset", + "copywritingFields", + "copywritingOptions", + "effectsPaused", + "errorNotice", + "followupPrompts", + "imageGenerate", + "imageResourcesClip", + "input", + "inputCaret", + "inputContentHeight", + "inputFirstRow", + "inputHitRect", + "inputScrollOffset", + "latestMessage", + "materialSearch", + "materialSearchSubmit", + "model", + "notificationCandidates", + "notifications", + "notificationsButton", + "notificationsOpen", + "open", + "page", + "panel", + "piUi", + "processing", + "processingBlob", + "processingBlobMoving", + "processingBlobPhase", + "processingIdentity", + "processingLightMode", + "processingOpacity", + "processingPlaceholder", + "productionCopyCells", + "productionImageCells", + "productionImagesTag", + "productionProgress", + "productionProgressRail", + "productionProgressTag", + "productionShelf", + "productionTitle", + "productionWorkers", + "productionWorkersTag", + "promptLibrary", + "psdReviewCancel", + "psdReviewConfirm", + "quickPrompts", + "reconnect", + "recoverResult", + "referenceAdd", + "referenceChips", + "referenceImage", + "referenceRemove", + "references", + "send", + "settings", + "settingsBody", + "settingsContentHeight", + "settingsGlass", + "settingsMotion", + "stop", + "subject", + "subjectTooltip", + "taskStop", + "thinkingLevel", + "visualPreviewCard", + "workflowAccept", + "workflowCard", + "workflowDismiss", + "workflowReady", + "workspaceReturn", + "workspaceSearch", + ]; + + /// 组件库自己的生产代码不出现字号字面量与原始颜色构造:字号走 `theme::agent_scale::Type`,颜色走 Token。 + #[test] + fn agent_library_takes_sizes_and_colours_from_tokens() { + let library = [ + ("stitch_ui", include_str!("jiansun/stitch_ui.rs")), + ("stitch_kit", include_str!("jiansun/stitch_kit.rs")), + ("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")), + ("agent_stream", include_str!("jiansun/agent_stream.rs")), + ("typing_text", include_str!("jiansun/typing_text.rs")), + ]; + for (name, source) in library { + let production = production_of(source); + assert_eq!(size_literals(&production), 0, "{name} hard-codes a font size"); + assert_eq!(raw_colours(&production), 0, "{name} hard-codes a raw colour"); + } + } + + /// 棘轮:业务代码里残留的字号字面量只许减少、不许增加。清掉一处就把对应的数字调低一格; + /// 第 3 批结束把全部归零并改成硬禁用。 + #[test] + fn agent_callers_never_gain_font_size_literals() { + let baseline = [ + ("agent_panel", include_str!("jiansun/agent_panel.rs"), 33usize), + ("canvas_workspace", include_str!("jiansun/canvas_workspace.rs"), 8), + ("creation", include_str!("jiansun/creation.rs"), 23), + ("jiansun", include_str!("jiansun.rs"), 0), + ("project_browser", include_str!("jiansun/project_browser.rs"), 8), + ("prompt_library_ui", include_str!("jiansun/prompt_library_ui.rs"), 8), + ("workspace_navigation", include_str!("jiansun/workspace_navigation.rs"), 4), + ("operation_error", include_str!("jiansun/operation_error.rs"), 0), + ("pi_ui", include_str!("jiansun/pi_ui.rs"), 2), + ("visual_preview_ui", include_str!("jiansun/visual_preview_ui.rs"), 10), + ("template_slots", include_str!("jiansun/template_slots.rs"), 2), + ("account_dialog", include_str!("jiansun/account_dialog.rs"), 5), + ("copywriting", include_str!("jiansun/copywriting.rs"), 3), + ]; + for (name, source, ceiling) in baseline { + let count = size_literals(&production_of(source)); + assert!( + count <= ceiling, + "{name} grew to {count} hard-coded font sizes (ceiling {ceiling}); take the size from `theme::agent_scale::Type`" + ); + } + } + + /// `panel_geometry` 的字符串键是外部 QA 脚本与 `jiansun.state` 控制通道的契约,只许原样保留。 + #[test] + fn panel_geometry_keys_keep_their_names_for_the_external_qa_contract() { + let writers = [ + include_str!("jiansun.rs"), + include_str!("jiansun/agent_panel.rs"), + include_str!("jiansun/canvas_workspace.rs"), + include_str!("jiansun/composer_attachments.rs"), + include_str!("jiansun/visual_preview_ui.rs"), + include_str!("jiansun/workflow_bridge.rs"), + include_str!("jiansun/workflow_export.rs"), + include_str!("jiansun/workspace_navigation.rs"), + ]; + let marker = "panel_geometry[\""; + let mut found = std::collections::BTreeSet::new(); + for source in writers { + let production = production_of(source); + let mut rest = production.as_str(); + while let Some(at) = rest.find(marker) { + let tail = &rest[at + marker.len()..]; + let Some(end) = tail.find('"') else { break }; + found.insert(tail[..end].to_owned()); + rest = &tail[end..]; + } + } + for key in PANEL_GEOMETRY_KEYS { + assert!(found.remove(key), "panel_geometry key {key:?} was renamed or removed; external scripts read this name"); + } + assert!(found.is_empty(), "new panel_geometry keys are not registered: {found:?}"); + } + + /// 白标:组件库与状态模型里带中文的文案行,不得出现实现方的产品名。 + #[test] + fn agent_library_copy_never_names_the_implementation_products() { + let library = [ + ("stitch_ui", include_str!("jiansun/stitch_ui.rs")), + ("stitch_kit", include_str!("jiansun/stitch_kit.rs")), + ("stitch_timeline", include_str!("jiansun/stitch_timeline.rs")), + ("stitch_state", include_str!("jiansun/stitch_state.rs")), + ("stitch_cache", include_str!("jiansun/stitch_cache.rs")), + ("agent_stream", include_str!("jiansun/agent_stream.rs")), + ("typing_text", include_str!("jiansun/typing_text.rs")), + ("siri_orb", include_str!("jiansun/siri_orb.rs")), + ]; + for (name, source) in library { + for (index, line) in source.replace("\r\n", "\n").lines().enumerate() { + let chinese = line.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)); + if !chinese { + continue; + } + let words: Vec<&str> = line.split(|c: char| !c.is_alphanumeric()).collect(); + assert!( + !line.contains("PhotoCraft") && !line.contains("Pi Agent") && !words.contains(&"Pi"), + "{name}:{} names an implementation product in Chinese copy: {line}", + index + 1 + ); + } + } + } + use super::*; fn slot_workspace() -> (Workspace, PhotocraftApp, mpsc::Receiver, mpsc::Sender) { @@ -4896,7 +5134,7 @@ mod tests { assert_eq!(w.agent_page(&app),"projects"); let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut output=ctx.run_ui(egui::RawInput::default(),|ui|w.workspace_panel(&mut app,ui)); + let mut output=ctx.settle_ui(egui::RawInput::default(),|ui|w.workspace_panel(&mut app,ui)); output.textures_delta.clear(); assert!(w.panel_geometry["composer"].is_null()); assert!(w.panel_geometry["subject"].is_null()); @@ -4935,7 +5173,7 @@ mod tests { PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); let mut seen=Vec::new(); for _ in 0..3 { - let mut output=ctx.run_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(520.0,900.0))), ..Default::default() }, + let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(520.0,900.0))), ..Default::default() }, |ui| w.workspace_panel(&mut app,ui)); seen.clear(); for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } @@ -4972,7 +5210,7 @@ mod tests { PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); let mut seen=Vec::new(); for _ in 0..3 { - let mut output=ctx.run_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(250.0,900.0))), ..Default::default() }, + let mut output=ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::pos2(0.0,0.0),egui::vec2(250.0,900.0))), ..Default::default() }, |ui| w.workspace_panel(&mut app,ui)); seen.clear(); for clipped in &output.shapes { texts(&clipped.shape,&mut seen); } @@ -5006,7 +5244,7 @@ mod tests { fn workspace_frame(w: &mut Workspace, app: &mut PhotocraftApp) { let ctx = egui::Context::default(); w.agent_images.begin_frame(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(app, ui.ctx())); w.agent_images.finish_pins(); for (reference, image) in w.agent_preview_pending.drain(..) { let id = reference["taskId"].as_str().unwrap(); @@ -5313,7 +5551,7 @@ mod tests { workflow["revision"] = json!(4); events.send(Event::Json("slot-append".into(),Ok(json!({"doc":document,"accountId":w.account["id"],"origin":w.origin,"workflow":workflow})))).unwrap(); let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(),|ui| w.tick(&mut app,ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(),|ui| w.tick(&mut app,ui.ctx())); output.textures_delta.clear(); while requests.try_recv().is_ok() {} assert!(w.busy.is_none(),"the real late image receipt releases its own busy flag"); @@ -5349,7 +5587,7 @@ mod tests { .send(Event::Json("slot-generate".into(), Ok(json!({"doc":id,"accountId":w.account["id"],"origin":w.origin,"workflow":snapshot,"pending":true})))) .unwrap(); events.send(Event::Json("slot-read".into(), Ok(json!({"doc":id,"accountId":w.account["id"],"origin":w.origin,"workflow":snapshot})))).unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.busy.is_none(), "the independent image's actual receipt releases its own busy state"); assert!(w.unknown, "an image receipt must preserve the backend's old-copy pending summary"); @@ -5362,7 +5600,7 @@ mod tests { // Deliver the real event rather than calling its continuation directly: // Event::Saved clears saving before it dispatches the queued local apply. events.send(Event::Saved(id, revision, json!({"doc":id,"revision":revision,"status":"draft","syncDirty":true,"time":"test-save"}))).unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.saving.is_none(), "the matching successful save must release the save gate"); assert!(matches!(requests.try_recv().unwrap(),Request::Action(method,_) if method=="slot-apply")); @@ -5370,7 +5608,7 @@ mod tests { events .send(Event::Json("slot-apply".into(), Ok(json!({"doc":id,"accountId":w.account["id"],"origin":w.origin,"workflow":snapshot,"pending":true})))) .unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.busy.is_none() && w.saving.is_none(), "the final assertion must reach the unknown guard, not an unfinished local operation"); assert!(w.unknown); @@ -5450,7 +5688,7 @@ mod tests { assert!(matches!(requests.try_recv().unwrap(), Request::Save(..))); events.send(Event::Json("save".into(), Err("当前人工输出保存失败".into()))).unwrap(); let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.pending_slot_apply.is_none()); assert!(w.busy.is_none()); @@ -5501,7 +5739,7 @@ mod tests { canonical["templateCopy"] = json!({"taskId":"copy-original","fields":[]}); events.send(Event::Json("slot-copy".into(),Ok(json!({"doc":id,"accountId":w.account["id"],"origin":w.origin,"creation":canonical,"workflow":{"revision":4,"copyReady":true},"pending":false})))).unwrap(); let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert_eq!(w.creation["revision"], 7); assert_eq!(w.creation["templateCopy"]["taskId"], "copy-original"); @@ -5525,7 +5763,7 @@ mod tests { events.send(Event::Json(method.into(),Ok(json!({"doc":id,"accountId":w.account["id"],"origin":w.origin,"creation":creation,"workflow":{"revision":revision,"confirmed":true},"pending":false})))).unwrap(); } let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert_eq!(w.template_workflow["revision"], 10, "the delayed worker cannot undo the successful ACK snapshot"); assert_eq!(w.creation["revision"], 7, "workflow and creation revisions are independent clocks"); @@ -5543,7 +5781,7 @@ mod tests { w.template_workflow = json!({"revision":99,"confirmed":true}); app.session.execute("file.new", json!({"width":1440,"height":900})).unwrap(); let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.template_workflow.is_null()); assert!(template_snapshot_not_older(&w.template_workflow, &json!({"revision":1}))); @@ -5564,7 +5802,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let frame = |workspace: &mut Workspace, app: &mut PhotocraftApp, events: Vec| { - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,egui::vec2(800.0,600.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,egui::vec2(800.0,600.0))), events, ..Default::default() }, |ui| { workspace.materials_ui(app, ui); }); }; @@ -5638,7 +5876,7 @@ mod tests { )) .unwrap(); let context = egui::Context::default(); - let mut output = context.run_ui(egui::RawInput::default(), |ui| workspace.tick(&mut app, ui.ctx())); + let mut output = context.settle_ui(egui::RawInput::default(), |ui| workspace.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert_eq!(workspace.material_rows[0]["materialId"], "found"); assert!(workspace.material_search_pending.is_none()); @@ -5733,7 +5971,7 @@ mod tests { let mut painted = Vec::new(); let mut labels = Vec::new(); for _ in 0..4 { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), ..Default::default() }, |ui| { crate::panels::options_bar(&mut app, ui); @@ -5831,7 +6069,7 @@ mod tests { ctx.set_pixels_per_point(scale); let mut output = None; for _ in 0..4 { - output = Some(ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(960.0, 120.0))), ..Default::default() }, |ui| crate::panels::options_bar(&mut app, ui))); + output = Some(ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(960.0, 120.0))), ..Default::default() }, |ui| crate::panels::options_bar(&mut app, ui))); } let mut seen = 0; for clipped in &output.unwrap().shapes { check(&clipped.shape, clipped.clip_rect, &mut seen); } @@ -5957,7 +6195,7 @@ mod tests { let mut value = String::new(); let mut painted = false; for _ in 0..2 { - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { let before = ui.visuals().weak_text_color(); stitch_ui::scope(ui, |ui| { stitch_ui::halo_field(ui, egui::Id::unique("readable-hint"), None, true, |ui| @@ -6187,7 +6425,7 @@ mod tests { Ok(json!({"accountId":"a","origin":w.origin,"doc":id,"revision":revision+99,"phase":"complete","path":"not-applied.png"})), )) .unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert!(w.pending_image.is_none()); assert!(w.ready_image.is_some()); @@ -6207,7 +6445,7 @@ mod tests { let (events, rx) = mpsc::channel(); let mut w = Workspace::new(tx, rx); events.send(Event::Opened(Box::new(doc), json!({"path":"local-project.pcraft"}))).unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert_eq!(app.session.documents().len(), 2); assert_eq!(app.session.active_index(), Some(1)); @@ -6253,7 +6491,7 @@ mod tests { }), )) .unwrap(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); let old = app.session.documents().iter().find(|state| state.doc.id.0 == dirty).unwrap(); assert_eq!(old.revision, dirty_revision, "{scope}"); @@ -6325,7 +6563,7 @@ mod tests { let input = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440., 900.))), ..Default::default() }; let mut account = egui::FullOutput::default(); for _ in 0..3 { - account = ctx.run_ui(input(), |ui| prepare(&mut app, ui)); + account = ctx.settle_ui(input(), |ui| prepare(&mut app, ui)); account.textures_delta.clear(); } let mut workspace = app.jiansun.take().unwrap(); @@ -6334,7 +6572,7 @@ mod tests { workspace.busy = Some("configure".into()); let mut output = egui::FullOutput::default(); for _ in 0..3 { - output = ctx.run_ui(input(), |ui| workspace.right(&mut app, ui)); + output = ctx.settle_ui(input(), |ui| workspace.right(&mut app, ui)); output.textures_delta.clear(); } let mut text = String::new(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_motion.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_motion.rs index 2256e6ce..188e4d4e 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_motion.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_motion.rs @@ -1,4 +1,8 @@ //! Bounded native Stitch light. Only lighting changes; artwork, text and camera stay fixed. +//! +//! 这里也是小壹装饰动画的节拍器:`schedule` 把"要不要下一帧、隔多久"收成一个出口。 +//! 发送脉冲、运行与交互按满帧,纯待机平滑降到半帧,窗口最小化或区域不可见时一帧都不申请。 +use crate::theme::agent_scale::motion as timing; use crate::theme::Tokens; use egui::{Color32, Id, Mesh, Pos2, Rect, Shape, Stroke, Ui, layers::ShapeIdx, pos2, vec2}; use std::{collections::VecDeque, sync::Arc, time::Duration}; @@ -7,12 +11,13 @@ use std::{collections::VecDeque, sync::Arc, time::Duration}; #[path = "blob_warp.rs"] mod blob_warp; -const RIM_SECONDS: f64 = 9.0; -const FIELD_SECONDS: f64 = 6.0; -const SETTLE_SECONDS: f64 = 0.16; -const SUBJECT_SECONDS: f64 = 0.22; -const MESSAGE_SECONDS: f64 = 0.22; -const IMAGE_SECONDS: f64 = 0.30; +const RIM_SECONDS: f64 = timing::RIM_PERIOD; +const FIELD_SECONDS: f64 = timing::FIELD_PERIOD; +/// 停止时的收敛窗口:任务卡的流光、内雾与占位一起在 190ms 内退场。 +const SETTLE_SECONDS: f64 = timing::STOP_SETTLE; +const SUBJECT_SECONDS: f64 = timing::SUBJECT; +const MESSAGE_SECONDS: f64 = timing::MESSAGE; +const IMAGE_SECONDS: f64 = timing::IMAGE; const MAX_SEGMENTS: usize = 320; const GEOMETRY_LIMIT: usize = 24; const SURFACE_LIMIT: usize = 64; @@ -614,9 +619,111 @@ pub(super) fn paint_real_target(ui: &Ui, target: Rect, clip: Rect, _reduce_motio painter.extend(shapes); } +/// 窗口最小化,或这块区域此刻根本不可见:任何装饰动画都不该为它申请重绘。 +pub(super) fn hidden(ui: &Ui, rect: Rect) -> bool { + !rect.is_finite() || !rect.is_positive() || !ui.is_rect_visible(rect) + || ui.input(|input| input.viewport().minimized == Some(true)) +} + +/// 装饰动画申请的帧率档位。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Pace { + /// 发送脉冲、任务运行、悬停聚焦、逐字入场:满帧。 + Full, + /// 纯待机的呼吸与流光:可以降频。 + Idle, +} + +/// 全窗口共用一个节拍器。帧间隔向目标按时间常数平滑靠拢:升档立即到位,交互永远是满血; +/// 降档慢慢来,不出现帧率忽快忽慢。最后一次满帧请求之后 `IDLE_AFTER` 才开始降频, +/// `DEEP_AFTER` 内没有任何输入再降到深待机。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Pacer { + interval: f32, + last_full: Option, + last_input: Option, + last: Option, +} + +impl Default for Pacer { + fn default() -> Self { + Self { interval: 0.0, last_full: None, last_input: None, last: None } + } +} + +impl Pacer { + /// 返回这一帧应申请的重绘延迟(秒)。 + pub(super) fn step(&mut self, now: f64, pace: Pace, input: bool) -> f32 { + let full = timing::FRAME_FULL.as_secs_f32(); + if self.interval <= 0.0 { + self.interval = full; + } + if input || self.last_input.is_none() { + self.last_input = Some(now); + } + let target = match pace { + Pace::Full => { + self.last_full = Some(now); + full + } + Pace::Idle if self.last_full.is_some_and(|at| now - at < timing::IDLE_AFTER) => full, + Pace::Idle if now - self.last_input.unwrap_or(now) > timing::DEEP_AFTER => timing::FRAME_DEEP.as_secs_f32(), + Pace::Idle => timing::FRAME_IDLE.as_secs_f32(), + }; + let elapsed = self.last.map_or(0.0, |last| (now - last).clamp(0.0, 0.25)) as f32; + // 升档(变快)立即到位;降档按时间常数向目标靠拢。 + if target < self.interval { + self.interval = target; + } else if elapsed > 0.0 { + self.interval += (target - self.interval) * (1.0 - (-elapsed / timing::PACER_TAU).exp()); + } + self.last = Some(now); + self.interval + } +} + +/// 装饰动画申请下一帧的唯一出口。最小化或区域不可见时什么都不申请。 +pub(super) fn schedule(ui: &Ui, rect: Rect, pace: Pace) { + if hidden(ui, rect) { + return; + } + let now = ui.input(|input| input.time); + let input = ui.input(|input| { + input.events.iter().any(|event| { + matches!(event, + egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::Key { .. } + | egui::Event::Text(_) | egui::Event::Touch { .. } | egui::Event::MouseWheel { .. }) + }) + }); + let interval = ui.data_mut(|data| { + data.get_temp_mut_or_default::(Id::unique("stitch-repaint-pacer")).step(now, pace, input) + }); + // 落在某一档上就申请那一档的精确时长(`from_secs_f32(0.016)` 会差出 1ns);过渡中才用连续值。 + let near = |target: Duration| (interval - target.as_secs_f32()).abs() <= 0.000_5; + let delay = if interval <= timing::FRAME_FULL.as_secs_f32() { + timing::FRAME_FULL + } else if near(timing::FRAME_IDLE) { + timing::FRAME_IDLE + } else if near(timing::FRAME_DEEP) { + timing::FRAME_DEEP + } else { + // `f32::max` 对 NaN 返回另一个操作数:坏时钟最多只会得到 1ms,不会 panic。 + Duration::from_secs_f32(interval.max(0.001)) + }; + ui.ctx().request_repaint_after(delay); +} + +/// 测试用:这一帧向窗口申请的重绘延迟;`None` 表示一帧都没有申请。 +#[cfg(test)] +pub(super) fn requested_delay(output: &egui::FullOutput) -> Option { + let delay = output.viewport_output.get(&egui::ViewportId::ROOT)?.repaint_delay; + (delay != Duration::MAX).then_some(delay) +} + +/// 一次性过渡(定位信标、采纳波纹、入场淡入)的满帧请求;窗口最小化时不推进。 fn repaint(ui: &Ui, needed: bool) { - if needed { - ui.ctx().request_repaint_after(Duration::from_secs_f64(1.0 / 60.0)); + if needed && ui.input(|input| input.viewport().minimized != Some(true)) { + ui.ctx().request_repaint_after(timing::FRAME_FULL); } } @@ -645,7 +752,10 @@ fn component_light(ui: &Ui, surface: Surface, reduce_motion: bool, state: LightS draw_light(ui, surface, component_phases(ui, reduce_motion), (strength, haze), 1.0, false, false); // The fine rim is itself travelling in both modes; hidden regions return // above and reduced-motion draws the same static edge without a loop. - repaint(ui, !reduce_motion && (settling || strength > 0.0)); + if !reduce_motion { + // 过渡中、悬停与聚焦按满帧;闲置的细边只是慢速巡行,交给待机档平滑降频。 + schedule(ui, surface.rect, if settling || state != LightState::Idle { Pace::Full } else { Pace::Idle }); + } } /// The only production entry for rim/haze. Palette, speed, falloff and state @@ -654,7 +764,10 @@ pub(super) fn role_light(ui: &Ui, surface: Surface, reduce_motion: bool, role: L if let LightRole::Field { focused, hovered: _ } = role { if focused && visible(ui, surface.rect.intersect(surface.clip)) { draw_light(ui, surface, component_phases(ui, reduce_motion), (0.65, 0.0), 1.0, false, false); - repaint(ui, !reduce_motion); + // 聚焦是交互:满帧。被裁掉或最小化时上面已经返回,不申请重绘。 + if !reduce_motion { + schedule(ui, surface.rect, Pace::Full); + } } return if focused { LightMode::Active } else { LightMode::Inactive }; } @@ -776,7 +889,8 @@ fn event_rim(ui: &Ui, surface: Surface, strength: f32, phase: f32) { let band = index / stride; let position = (index % stride) as f32 / geometry.segments as f32; let mix = 0.5 + 0.5 * ((position + phase) * std::f32::consts::TAU).sin(); - let color = Color32::from_rgb(162, 150, 247).lerp_to_gamma(Color32::from_rgb(85, 215, 226), mix); + let colors = Tokens::get(ui.ctx()).agent_light(); + let color = colors[0].lerp_to_gamma(colors[1], mix); vertex.color = color.gamma_multiply(if band == 1 || band == 2 { strength } else { 0.0 }); vertex.pos += rect.min.to_vec2(); } @@ -860,7 +974,7 @@ pub(super) fn adoption_badge_scale(now: f64, started: f64, reduced: bool) -> f32 pub(super) fn hover_amount(ui: &Ui, id: Id, rect: Rect, hovered: bool, reduced: bool) -> f32 { if !visible(ui, rect) { return f32::from(hovered); } - ui.ctx().animate_bool_with_time(id, hovered, if reduced { 0.0 } else { 0.16 }) + ui.ctx().animate_bool_with_time(id, hovered, if reduced { 0.0 } else { timing::HOVER as f32 }) } /// A one-shot visual acknowledgement on the actual related history turn. @@ -1057,6 +1171,7 @@ fn image_entry_blur(mesh: Mesh, opacity: f32) -> Mesh { #[cfg(test)] mod tests { use super::*; + use crate::jiansun::test_support::SettleUi; #[test] fn shared_light_cycle_and_independent_waiting_field_are_stable() { @@ -1097,7 +1212,7 @@ mod tests { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(120.0, 60.0)); let render = |state, id| { - let out = ctx.run_ui(egui::RawInput { time: Some(0.0), ..Default::default() }, |ui| { + let out = ctx.settle_ui(egui::RawInput { time: Some(0.0), ..Default::default() }, |ui| { component_light(ui, Surface::new(Id::unique(id), rect, 12.0), false, state); }); out.shapes.into_iter().filter_map(|shape| match shape.shape { Shape::Mesh(mesh) => Some(mesh), _ => None }).collect::>() @@ -1131,7 +1246,7 @@ mod tests { (3.20, LightState::Idle, false), (4.0, LightState::Focus, true), ] { - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { values.push(component_fade(ui, id, state, reduced)); }); } @@ -1152,7 +1267,7 @@ mod tests { let id = Id::unique("interrupted-component"); let sample = |time, state, reduced| { let mut value = (0.0, 0.0, false); - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { value = component_fade(ui, id, state, reduced); }); value @@ -1176,7 +1291,7 @@ mod tests { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); let render = |time, running| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { interactive(ui, Surface::new(Id::unique("active-tab"), rect, 10.0), false, running, true, 0.0); }); output.shapes.into_iter().filter_map(|shape| match shape.shape { @@ -1210,7 +1325,7 @@ mod tests { let target = Rect::from_min_size(pos2(20.0, 20.0), vec2(50.0, 40.0)); let clip = Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 100.0)); let render = |time, reduced, draw_frame| { - ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { paint_real_target(ui, target, clip, reduced, draw_frame); }).shapes.into_iter().filter(|shape| shape.clip_rect == clip).map(|shape| shape.shape).collect::>() }; @@ -1225,7 +1340,7 @@ mod tests { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); let frames = [0.0, 2.0].map(|time| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { component_light(ui, Surface::new(Id::unique("hovered-component"), rect, 10.0), false, LightState::Hover); }); output.shapes.into_iter().filter_map(|shape| match shape.shape { @@ -1264,7 +1379,7 @@ mod tests { fn painted_capsule_has_one_half_perimeter_band_and_transparent_remainder() { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); - let output = ctx.run_ui(Default::default(), |ui| processing(ui, Surface::new(Id::unique("capsule"), rect, 10.0), false, true, false, false)); + let output = ctx.settle_ui(Default::default(), |ui| processing(ui, Surface::new(Id::unique("capsule"), rect, 10.0), false, true, false, false)); let rim = output .shapes .iter() @@ -1337,7 +1452,7 @@ mod tests { fn actual_rim_vertices_show_purple_cyan_purple_in_band_order() { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); - let output = ctx.run_ui(egui::RawInput { time: Some(0.0), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(0.0), ..Default::default() }, |ui| { component_light(ui, Surface::new(Id::unique("gradient-rim"), rect, 10.0), false, LightState::Idle); }); let rim = output.shapes.iter().find_map(|shape| match &shape.shape { @@ -1387,7 +1502,7 @@ mod tests { let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); let times = [0.0, RIM_SECONDS / 2.0]; let frames = times.map(|time| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { processing(ui, Surface::new(Id::unique("moving-light"), rect, 10.0), false, true, false, false); }); output.shapes.into_iter().filter_map(|shape| match shape.shape { @@ -1454,7 +1569,7 @@ mod tests { fn moving_and_hovering_a_running_surface_keep_its_identity_and_work_clock() { let ctx = egui::Context::default(); for (time, hover) in [(0.0, 0.0), (0.05, 0.5), (0.1, 1.0)] { - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { let rect = Rect::from_min_size(pos2(20.0 + time as f32 * 200.0, 20.0), vec2(64.0, 20.0)); interactive(ui, Surface::new(Id::unique("moving-tab"), rect, 10.0), false, true, true, hover); ui.data(|data| { @@ -1469,7 +1584,7 @@ mod tests { }); }); } - let _ = ctx.run_ui(egui::RawInput { time: Some(0.2), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(0.2), ..Default::default() }, |ui| { let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); let surface = Surface::new(Id::unique("moving-tab"), rect, 10.0); processing(ui, surface, true, true, false, false); @@ -1484,7 +1599,7 @@ mod tests { fn a_fully_hovered_running_tab_still_changes_its_light_colors() { let ctx = egui::Context::default(); let colors = [0.0, 0.1].map(|time| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { let surface = Surface::new(Id::unique("hovered-tab"), Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)), 10.0); interactive(ui, surface, false, true, true, 1.0); }); @@ -1504,7 +1619,7 @@ mod tests { #[test] fn reserved_light_background_stays_below_frame_content() { let ctx = egui::Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let mut content = None; let frame = egui::Frame::NONE.fill(Color32::BLACK).show(ui, |ui| { let background = reserve_background(ui); @@ -1526,8 +1641,9 @@ mod tests { #[test] fn stopped_processing_keeps_its_placeholder_and_cursor_until_the_exit_settles() { let ctx = egui::Context::default(); - let alpha = [(0.0, true), (1.0, true), (1.0, false), (1.08, false), (1.17, false)].map(|(time, running)| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let stop = 1.0; + let alpha = [(0.0, true), (stop, true), (stop, false), (stop + 0.09, false), (stop + SETTLE_SECONDS + 0.01, false)].map(|(time, running)| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { let surface = Surface::new(Id::unique("candidate-task"), Rect::from_min_size(pos2(20.0, 20.0), vec2(200.0, 80.0)), 5.0); processing(ui, surface, false, running, true, true); }); @@ -1545,18 +1661,20 @@ mod tests { }); assert!(alpha[0].0 > 0 && alpha[1].0 > 0 && alpha[0].1 && alpha[1].1); assert_eq!(alpha[2], alpha[1], "stop begins at the preceding opacity at the same light phase"); - assert!(alpha[3].0 > 0 && alpha[3].0 < alpha[2].0 && alpha[3].1); - assert_eq!(alpha[4], (0, false), "placeholder, rim, haze and cursor all leave after 160ms"); + assert!(alpha[3].0 > 0 && alpha[3].0 < alpha[2].0 && alpha[3].1, "still fading at 90ms: the window is longer than the old 160ms"); + assert_eq!(alpha[4], (0, false), "placeholder, rim, haze and cursor all leave once the 190ms stop window has closed"); } #[test] - fn stop_and_resume_are_continuous_and_settle_in_160ms() { + fn stop_and_resume_are_continuous_and_settle_inside_the_stop_window() { + assert!((SETTLE_SECONDS - 0.19).abs() < 1e-9, "the user locked stop convergence to 180-200ms"); let mut fade = Fade { from: 0.0, target: 1.0, started: 0.0, reduced: false }; assert_eq!(fade.value(SETTLE_SECONDS), 1.0); fade.update(1.0, false, Some(false)); assert_eq!(fade.value(1.0), 1.0); let halfway = fade.value(1.0 + SETTLE_SECONDS * 0.5); assert!((halfway - 0.5).abs() < 0.0001); + assert!(fade.changing(1.0 + SETTLE_SECONDS - 0.01)); fade.update(1.0 + SETTLE_SECONDS * 0.5, true, Some(false)); assert!((fade.value(1.0 + SETTLE_SECONDS * 0.5) - halfway).abs() < 0.0001); fade.update(2.0, false, Some(true)); @@ -1564,6 +1682,62 @@ mod tests { assert!(!fade.changing(2.0)); } + #[test] + fn the_pacer_snaps_to_full_on_activity_and_eases_down_when_idle() { + let full = timing::FRAME_FULL.as_secs_f32(); + let idle = timing::FRAME_IDLE.as_secs_f32(); + let deep = timing::FRAME_DEEP.as_secs_f32(); + let mut pacer = Pacer::default(); + let mut delays = Vec::new(); + for frame in 0..180 { + delays.push(pacer.step(frame as f64 / 60.0, Pace::Idle, false)); + } + assert_eq!(delays[0], full, "starts at the full frame rate"); + assert!(delays.windows(2).all(|pair| pair[1] >= pair[0]), "the interval only ever grows while idling: no flicker between rates"); + assert!(delays[179] > full && delays[179] <= idle, "pure idling settles on the idle tier: {:?}", delays[179]); + assert!(delays[30] < delays[179] && delays[30] > full, "the downshift is gradual"); + assert_eq!(pacer.step(3.5, Pace::Full, false), full, "activity snaps straight back to full"); + assert_eq!(pacer.step(3.6, Pace::Idle, false), full, "no downshift right after a full request"); + assert!(pacer.step(3.6 + timing::IDLE_AFTER + 0.4, Pace::Idle, false) > full, "the idle tier resumes once the grace period is over"); + let mut last = 0.0; + for frame in 0..120 { + last = pacer.step(20.0 + frame as f64 / 60.0, Pace::Idle, false); + } + assert!((deep - last).abs() < 0.0005, "with no input for a long time the rest tier goes one step deeper: {last}"); + assert_eq!(pacer.step(22.5, Pace::Full, false), full); + assert_eq!(pacer.step(22.6, Pace::Idle, false), full); + let mut quiet = Pacer::default(); + assert_eq!(quiet.step(30.0, Pace::Idle, false), full, "a fresh pacer starts at full and eases down from there"); + assert!(quiet.step(31.0, Pace::Idle, false) > full); + assert!(Pacer::default().step(f64::NAN, Pace::Idle, false).is_finite(), "a bad clock never poisons the pacer"); + } + + #[test] + fn a_minimized_or_clipped_window_gets_no_repaint_from_the_scheduler() { + let ctx = egui::Context::default(); + ctx.settle_start(); + let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); + let frame = |time, minimized, clip| { + let mut input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0))), + time: Some(time), + ..Default::default() + }; + if minimized { + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(true); + } + let output = ctx.settle_ui(input, |ui| { + ui.set_clip_rect(clip); + schedule(ui, rect, Pace::Full); + }); + requested_delay(&output) + }; + assert_eq!(frame(0.0, false, Rect::EVERYTHING), Some(timing::FRAME_FULL)); + assert_eq!(frame(0.1, true, Rect::EVERYTHING), None, "minimized: zero repaints"); + assert_eq!(frame(0.2, false, Rect::from_min_size(pos2(150.0, 150.0), vec2(10.0, 10.0))), None, "clipped out: zero repaints"); + assert_eq!(frame(0.3, false, Rect::EVERYTHING), Some(timing::FRAME_FULL)); + } + #[test] fn message_and_subject_transitions_have_separate_short_durations() { assert_eq!(amount(0.0, SUBJECT_SECONDS), 1.0); @@ -1580,7 +1754,7 @@ mod tests { let mut frames = Vec::new(); for opacity in [0.1, 1.0] { let mut rects = None; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320.0, 200.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320.0, 200.0))), ..Default::default() }, |ui| { let animated = message_visual(ui, opacity, |ui| ui.label("消息正文")); let following = ui.label("下一条消息"); rects = Some((animated.response.rect, following.rect)); @@ -1610,7 +1784,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let rect = Rect::from_min_size(pos2(30.0, 30.0), vec2(80.0, 60.0)); let screen = Rect::from_min_size(Pos2::ZERO, vec2(180.0, 140.0)); - let render = |time, reduced, adopt| ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| { + let render = |time, reduced, adopt| ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| { if adopt { adoption_ripple(ui, Id::unique("adoption"), rect, 0.0, reduced); } else { target_beacon(ui, Id::unique("locate"), rect, 0.0, reduced); } }); @@ -1632,7 +1806,7 @@ mod tests { let ctx = egui::Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let rect = Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 40.0)); - let output = ctx.run_ui(egui::RawInput { time: Some(0.5), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(0.5), ..Default::default() }, |ui| { let background = reserve_background(ui); ui.label("正文在上层"); trace_highlight(ui, Id::unique("trace"), rect, background, 0.0, false); @@ -1855,7 +2029,7 @@ mod tests { #[test] fn invisible_surfaces_do_not_create_geometry_or_animation_state() { let ctx = egui::Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let offscreen = Rect::from_min_size(ui.clip_rect().max + vec2(100.0, 100.0), vec2(200.0, 80.0)); let surface = Surface::new(Id::unique("offscreen"), offscreen, 18.0); processing(ui, surface, false, true, true, true); @@ -1870,7 +2044,7 @@ mod tests { #[test] fn cached_geometry_is_reused_and_all_cache_sizes_are_bounded() { let ctx = egui::Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(64.0, 20.0)); let first = cached_geometry(ui, rect, 10.0); let again = cached_geometry(ui, rect.translate(vec2(50.0, 50.0)), 10.0); @@ -1909,7 +2083,7 @@ mod tests { history.update(2.0, 1, false); assert_eq!(history.opacity(0, 2.0), 1.0, "replacement history establishes a fresh baseline"); let ctx = egui::Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { for index in 0..=CONVERSATION_LIMIT { assert_eq!(message_enter(ui, Id::unique(index), 99, 100, false), 1.0); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index 9ea2dfe1..330e775d 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -141,63 +141,28 @@ fn final_handoff(ui: &Ui, id: Id, text: &str) -> Option { /// A tool's public label is constructed locally, never from its arguments, /// output, arbitrary summary or error string. Unknown values stay unknown. +/// The name and status tables live in the kit (`stitch_state`), so a tool reads +/// the same here as in its row badge; this only assembles the legacy line. fn tool_activity_label(event: &Value) -> Option<(String, super::stitch_ui::StatusTone)> { - use super::stitch_ui::StatusTone; + use super::stitch_state::{ToolStatus, tool_label}; if event["version"] != 1 || event["type"] != "tool" { return None; } - let tool = match event["toolName"].as_str().unwrap_or("") { - "context_read" => "读取项目规则", "memory_set" => "记录事实", "memory_search" => "检索历史", - "ask_user" => "等待用户回复", - "tool_develop" => "编写并测试工具", "tool_run" => "运行工具", "canvas_read" => "读取画布", "canvas_template_image" => "读取模板原图", - "canvas_edit" => "更新图层", "workflow_read" => "读取创作进度", "workflow_navigate" => "切换创作视图", - "workflow_propose" => "添加待审核建议", "workflow_execute" => "执行创作操作", "native_catalog" => "查询原生命令", - "native_call" => "执行原生操作", "native_reconcile" => "核查原生任务", "canvas_preview" => "预览修改", - "copywriting_options" => "生成卖点选项", "copywriting_fields" => "准备逐格文案", - "bash" => "运行项目终端", - "plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则", - "read_copy_fields" => "读取画布文字格", "read_slot_images" => "查看图位图片", - "generate_slot_image" => "生成候选图片", "delegate_image_slots" => "分派图片图位", - "check_image_slots" => "发起验图", "record_screen_check" => "记录本屏复核", - "await_image_slots" => "等待子代理回执", "review_image_slots" => "查看图位结果", - "adopt_production_image" => "回填候选图片", "reconcile_image_slots" => "核查图片原请求", - "defer_production_output" => "保留当前草稿", - "read_output_screen" => "查看实际画布", "finish_production" => "提交成品导出", - "canvas_candidate_image" => "核对图位和候选", - "produce_current_output" => "制作并验收当前输出", - "save_product_strategy" => "保存商品策划", "review_product_strategy" => "核对卖点证据", - "plan_page_copy" => "规划整页卖点", "write_copy_fields" => "填写画布文案", - "review_page_copy" => "复核整页文案", - "codemode" => "组合画布操作", "tool_search" => "查找工具", _ => "工具", - }; - let (state, tone) = match event["status"].as_str().unwrap_or("") { - "pending" => ("等待", StatusTone::Neutral), - "started" => ("进行中", StatusTone::Neutral), - "completed" => ("已完成", StatusTone::Neutral), - "failed" => ("失败", StatusTone::Error), - "stopped" => ("已停止", StatusTone::Warning), - _ => ("状态未知", StatusTone::Warning), - }; - let mut label = format!("{state} · {tool}"); + let status = ToolStatus::parse(event["status"].as_str().unwrap_or("")); + let tool = tool_label(event["toolName"].as_str().unwrap_or("")); + let mut label = format!("{} · {tool}", status.label()); // Only a terminal event with an upstream-provided duration gets a timer. // There is no local clock estimate or implied completion percentage. - if matches!(event["status"].as_str(), Some("completed" | "failed" | "stopped")) + if status.timed() && let Some(ms) = event["durationMs"].as_u64().filter(|ms| *ms <= 9_007_199_254_740_991) { label.push_str(&format!(" · {}", duration_text(ms))); } - Some((label, tone)) + Some((label, status.tone().into())) } /// People read durations coarsely: milliseconds under a second, tenths below /// ten, whole seconds below a minute, then minutes. fn duration_text(ms: u64) -> String { - match ms { - 0..=999 => format!("耗时 {ms} 毫秒"), - 1000..=9_999 => format!("耗时 {}.{} 秒", (ms + 50) / 100 / 10, (ms + 50) / 100 % 10), - _ => { - let seconds = (ms + 500) / 1000; - if seconds < 60 { format!("耗时 {seconds} 秒") } else { format!("耗时 {} 分 {:02} 秒", seconds / 60, seconds % 60) } - } - } + super::stitch_state::duration_text(ms) } /// Model ids are catalog keys written for machines. Known words become a @@ -491,28 +456,14 @@ fn turns(messages: &[Value]) -> Vec> { /// same right-aligned rectangle at all sidebar widths and DPI scales. #[cfg(test)] fn user_bubble(ui: &mut Ui, text: &str) -> Rect { - user_bubble_with_reveal(ui, text, None) + user_bubble_with_reveal(ui, text, None, true) } -fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option) -> Rect { - let t = Tokens::get(ui.ctx()).agent(); - let max_text = (ui.available_width() - 22.0 - 28.0).max(1.0); - let mut galley = ui.fonts_mut(|fonts| fonts.layout(text.to_owned(), FontId::proportional(14.0), t.text, max_text)); - let mut animating = false; - if let Some(started) = started.filter(|started|ui.input(|input|input.time)-started<0.87) { - let arrivals=super::typing_text::staggered(text,started); - animating=super::stitch_ui::animate_galley(&mut galley,&arrivals,ui.input(|input|input.time),false); - } - let size = galley.size() + vec2(28.0, 24.0); - ui.with_layout(Layout::top_down(Align::Max), |ui| { - let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); - let background=agent_motion::reserve_background(ui); - super::stitch_ui::material(ui,response.id,rect,t.radius,0.0,background); - super::stitch_ui::selectable_galley_at(ui, rect.shrink2(vec2(14.0, 12.0)), galley); - if animating && ui.is_rect_visible(rect) { ui.ctx().request_repaint_after(Duration::from_millis(16)); } - rect - }) - .inner +/// The bubble itself lives in the kit (`stitch_ui::user_bubble_with_reveal`), together with +/// the per-character reveal and its glow. `reduced` is always passed through: reduced motion +/// shows the whole message at once and never starts the reveal or its repaint loop. +fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option, reduced: bool) -> Rect { + super::stitch_ui::user_bubble_with_reveal(ui, text, started, reduced) } fn paint_reference_thumbnail(ui: &mut Ui, texture: &egui::TextureHandle, limit: Vec2) -> Rect { @@ -1723,7 +1674,7 @@ impl Workspace { if let Some(index) = turn.user_index { self.sent_references(ui, &self.messages[index]); } - user_bubble_with_reveal(ui, text, started); + user_bubble_with_reveal(ui, text, started, self.reduce_motion); }); agent_motion::message_repaint(ui, response.response.rect, enter); ui.add_space(18.0); @@ -2423,7 +2374,7 @@ impl Workspace { // One palette for both states of the head: what is filled // but not yet verified is amber, as in the cell rails. let rail = super::stitch_ui::progress_bar_tinted(ui, id, &title, fraction, self.reduce_motion || waiting, - super::agent_stream::CELL_FILLED); + super::agent_stream::cell_filled(&t)); self.panel_geometry["productionProgressRail"] = rect_value(rail.rect); } } @@ -2848,6 +2799,8 @@ impl Workspace { self.panel_geometry["inputHitRect"] = rect_value(editor.response.rect); let response = editor.response.response.accessible_name("小壹消息输入"); let text_end = ui.ctx().graphics(|graphics|graphics.get(ui.layer_id()).map_or(text_start, |list| list.next_idx().0)); + // 输入框的逐字柔光画在光涌玻璃上面、文字光标下面(见 `typing_text::paint_glow`)。 + super::typing_text::paint_glow(ui,typing_owner,editor.galley_pos); let input_focused = response.has_focus(); self.panel_geometry["input"] = rect_value(input_rect); if self.focus_composer && draft_ready { response.request_focus(); self.focus_composer = false; } @@ -2860,8 +2813,7 @@ impl Workspace { let orb_center = egui::pos2(surface_rect.left() + 29.0, surface_rect.center().y + reference_height / 2.0) .lerp(egui::pos2(surface_rect.left() + 35.0, surface_rect.bottom() - 33.0), morph); let orb = Rect::from_center_size(orb_center, Vec2::splat(34.0 - 10.0 * morph + 16.0 * orb_progress)); - let motion = if self.reduce_motion { super::siri_orb::Motion::Still } - else if typing { super::siri_orb::Motion::Thinking } else { super::siri_orb::Motion::Idle }; + let motion = super::siri_orb::Motion::composer(self.reduce_motion, typing); let animation = super::siri_orb::paint(ui, orb_id, orb, motion, self.reduce_motion); self.panel_geometry["composerOrb"] = rect_value(orb); self.panel_geometry["composerOrbTyping"] = json!(typing); @@ -3008,7 +2960,7 @@ impl Workspace { self.reveal_sent_user_text(ui,messages_before_send); self.flush_document_draft(ui.ctx(), self.observed_doc, false); } - super::stitch_ui::sent_glow(ui, Id::unique("composer-sent-glow"), super::stitch_ui::SendSurface {rect:frame.response.rect,radius,background:Some(send_background),text_range:Some(text_start..text_end),flanks:morph}, sent, self.reduce_motion); + super::stitch_ui::sent_glow_paced(ui, Id::unique("composer-sent-glow"), super::stitch_ui::SendSurface {rect:frame.response.rect,radius,background:Some(send_background),text_range:Some(text_start..text_end),flanks:morph}, sent, self.reduce_motion, super::stitch_ui::GlowPace { running: self.pending(), engaged: input_focused }); if self.prompt_library.show(ui, &self.account, &self.origin, &mut self.composer, &self.tx, super::prompt_library_ui::PromptPanelPlacement { can_insert:draft_ready, reduced:self.reduce_motion, anchor:prompt_anchor, composer:frame.response.rect }) { @@ -3572,6 +3524,7 @@ fn show_settings_glass(ui: &mut Ui, mut frame: egui::Frame, base: Color32, op #[cfg(test)] mod tests { + use crate::jiansun::test_support::SettleUi; use crate::jiansun::Event; use std::sync::mpsc; use super::*; @@ -3602,7 +3555,7 @@ mod tests { w.model_settings = true; w.key_settings = true; for time in [0.0, 0.2, 0.6, 1.0, 1.4] { - let mut frame = ctx.run_ui(egui::RawInput { + let mut frame = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, height))), time: Some(time), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); @@ -3624,7 +3577,7 @@ mod tests { let mut result = None; // Popup's first pass measures its position without painting. for _ in 0..2 { - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { let anchor = ui.button("settings"); egui::Popup::from_response(&anchor).frame(egui::Frame::NONE).open_bool(&mut open).show(|ui| { let frame = super::super::stitch_ui::surface_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog); @@ -3654,7 +3607,7 @@ mod tests { use eframe::egui_wgpu::BackdropMarker; for opacity in [1.0_f32, 0.5, 0.1, 0.0] { let ctx = egui::Context::default(); - let output = ctx.run_ui(egui::RawInput::default(), |ui| { + let output = ctx.settle_ui(egui::RawInput::default(), |ui| { let frame = super::super::stitch_ui::overlay_frame(ui.ctx(), super::super::stitch_ui::SurfaceRole::Dialog, opacity); show_settings_glass(ui, frame, Color32::from_rgb(38, 39, 43), opacity, 0.12 + opacity * 0.88, |ui| { ui.label("settings"); }); }); @@ -3683,7 +3636,7 @@ mod tests { fn input_frame(ctx: &egui::Context, text: &mut String, events: Vec) -> bool { let mut submit = false; - let _ = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { events, ..Default::default() }, |ui| { let id = Id::unique("keyboard-acceptance"); ui.memory_mut(|memory| memory.request_focus(id)); submit = composer_enter(ui, id); @@ -3768,7 +3721,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let reply = "保持产品结构和真实花色,让首屏的自然光更柔和,并继续保留文字和其他可编辑图层。"; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 600.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 600.0))), ..Default::default() }, |ui| { ui.set_width(200.0); user_bubble(ui, "你好"); assistant_reply(ui, Id::unique("assistant-reply-test"), reply); @@ -3793,7 +3746,7 @@ mod tests { let message = json!({"role":"user","text":"图里有什么?", "requestScope":{"references":[{"kind":"layer","label":"主图"}]}, "referenceContent":[{"imageId":"ref-frozen"}]}); - let frame = || ctx.run_ui(egui::RawInput { + let frame = || ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 360.0))), ..Default::default() }, |ui| w.sent_references(ui, &message)); @@ -3816,9 +3769,9 @@ mod tests { crate::cjk_fonts::install_system_provider_for_tests(&ctx); let mut bounds = Vec::new(); for time in [0.0, 0.2, 0.5, 1.0] { - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { ui.set_width(240.0); - bounds.push(user_bubble_with_reveal(ui, "保留产品结构,让光线更加柔和。", Some(0.0))); + bounds.push(user_bubble_with_reveal(ui, "保留产品结构,让光线更加柔和。", Some(0.0), false)); }); } assert!(bounds.windows(2).all(|pair| pair[0] == pair[1])); @@ -3833,7 +3786,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); crate::cjk_fonts::install_system_provider_for_tests(&ctx); - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width + 20.0, 600.0))), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width + 20.0, 600.0))), ..Default::default() }, |ui| { ui.set_width(width); let right = ui.available_rect_before_wrap().right(); let short = user_bubble(ui, "你好"); @@ -4043,7 +3996,7 @@ mod tests { let message = json!({"requestScope":{"references":[{"label":"Title"}]}, "referenceContent":[{"imageId":"reference"}]}); let mut heights = Vec::new(); for clip_top in [0.0, 200.0] { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 350.0))), ..Default::default() }, |ui| { @@ -4113,10 +4066,10 @@ mod tests { _ => {} } } - let amber = super::super::agent_stream::CELL_FILLED; + let amber = super::super::agent_stream::cell_filled(&Tokens::get(&ctx).agent()); let mut painted = Vec::new(); for _ in 0..5 { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); @@ -4180,7 +4133,7 @@ mod tests { let mut seen = Vec::new(); let mut dot_centers = Vec::new(); let frame = |app: &mut PhotocraftApp, events: Vec, seen: &mut Vec, dots_out: &mut Vec| { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), events, ..Default::default() }, |ui| crate::panels::right_dock(app, ui)); seen.clear(); @@ -4244,7 +4197,7 @@ mod tests { let hover = Tokens::get(&ctx).agent().hover; let row = std::cell::Cell::new(Rect::NOTHING); let frame = |events: Vec, lit: &mut Vec| { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(600.0, 200.0))), events, ..Default::default() }, |ui| { super::super::stitch_ui::scope_with_motion(ui, true, |ui| { row.set(super::super::agent_stream::event_row(ui, Id::unique("focus-row"), EventRow { @@ -4284,7 +4237,7 @@ mod tests { } } let canvas = crate::theme::Tokens::get(&ctx).agent().canvas; - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), ..Default::default() }, |ui| { @@ -4356,7 +4309,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let mut seen = Vec::new(); let frame = |app: &mut PhotocraftApp, seen: &mut Vec| { - let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| { crate::panels::right_dock(app, ui) }); seen.clear(); @@ -4430,7 +4383,7 @@ mod tests { }).collect(); let mut rails = Vec::new(); for width in [520.0, 250.0] { - ctx.run_ui(egui::RawInput { + ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 400.0))), ..Default::default() }, |ui| { @@ -4577,7 +4530,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let frame = |app:&mut PhotocraftApp,time:f64| { - let _ = ctx.run_ui(egui::RawInput { time:Some(time), + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(960.0,600.0))), ..Default::default() }, |ui| crate::panels::right_dock(app,ui)); }; @@ -4708,7 +4661,7 @@ mod tests { super::super::action_in_ui(&mut app,&ctx,"composer-reference-add", json!({"documentId":doc,"nativeLayerId":layer,"component":"layer"})).unwrap(); let frame = |app:&mut PhotocraftApp,time:f64,events| { - let _ = ctx.run_ui(egui::RawInput { time:Some(time), events, + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(app,ui)); }; @@ -4726,7 +4679,7 @@ mod tests { let render = |progress| { let ctx = egui::Context::default(); let mut result = None; - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(420.0,400.0))), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(420.0,400.0))), ..Default::default() }, |ui| { ui.set_width(320.0); let message = agent_motion::message_visual(ui,progress,|ui| user_bubble(ui,"真实消息")); let next = ui.label("下方消息"); @@ -4749,7 +4702,7 @@ mod tests { let mut w = app.jiansun.take().unwrap(); w.reduce_motion = false; let frame = |w: &mut Workspace, app: &mut PhotocraftApp, time: f64, events| { - let _ = ctx.run_ui(egui::RawInput { time:Some(time), events, + let _ = ctx.settle_ui(egui::RawInput { time:Some(time), events, screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), ..Default::default() }, |ui| { w.composer_ui(app, ui); }); @@ -4833,7 +4786,7 @@ mod tests { crate::panels::request_dock_width(&ctx, dock_width); let mut output = None; for _ in 0..4 { - let mut frame = ctx.run_ui( + let mut frame = ctx.settle_ui( egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 1550.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui), ); @@ -4918,7 +4871,7 @@ mod tests { } } fn frame(ctx: &egui::Context, w: &Workspace, time: f64, events: Vec) -> Vec<(String, Rect)> { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),events,..Default::default() }, |ui| { ui.set_width(520.0); @@ -5014,7 +4967,7 @@ mod tests { json!({"role":"assistant","kind":"activity","text":"工具二","event":{"version":1,"type":"tool","run":"r","toolCallId":"b","toolName":"native_call","status":"started"}})]; let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), ..Default::default() }, |ui| { ui.set_width(520.0); let turn = turns(&w.messages).pop().unwrap(); w.turn_ui(ui, turn, Id::unique("one-loader-test"), w.messages.len(), true); @@ -5047,7 +5000,7 @@ mod tests { } fn frame(ctx: &egui::Context, w: &Workspace, events: Vec) -> Vec<(String, Rect)> { let mut out = Vec::new(); - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(640.0, 900.0))), events, ..Default::default() }, |ui| { ui.set_width(520.0); @@ -5142,7 +5095,7 @@ mod tests { _ => {} } } - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))),time:Some(time),..Default::default() }, |ui| { ui.set_width(520.0); @@ -5187,7 +5140,7 @@ mod tests { assert_eq!(thinking_usage(&w.messages[1]["output"]), (Some("145 tokens · 45 tok/s".to_owned()), "本次输出用量由模型回传。速度从首段输出开始计算。")); let header = finished.iter().find(|(text,_,_,_)| text == "已深度思考").unwrap().1.center(); for pressed in [true, false] { - ctx.run_ui(egui::RawInput { time:Some(0.5), events:vec![egui::Event::PointerMoved(header), + ctx.settle_ui(egui::RawInput { time:Some(0.5), events:vec![egui::Event::PointerMoved(header), egui::Event::PointerButton { pos:header, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE }], screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,900.0))), ..Default::default() }, |ui| { ui.set_width(520.0); @@ -5336,7 +5289,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let frame = |app: &mut PhotocraftApp, time| { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(app, ui)); let mut found = Vec::new(); @@ -5433,7 +5386,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let mut output = None; for _ in 0..3 { - output = Some(ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 1000.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui))); + output = Some(ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 1000.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui))); } let mut text = Vec::new(); for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } @@ -5515,7 +5468,7 @@ mod tests { let screen=Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,400.0)); let id=std::cell::Cell::new(Id::NULL); let rect=std::cell::Cell::new(Rect::NOTHING); let frame=|events| { - let _=ctx.run_ui(egui::RawInput { screen_rect:Some(screen),events,..Default::default() },|ui| { + let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(screen),events,..Default::default() },|ui| { let response=context_meter(ui,None,true,true); id.set(response.id); rect.set(response.rect); }); }; @@ -5538,7 +5491,7 @@ mod tests { PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); ctx.all_styles_mut(|style| style.interaction.tooltip_delay=0.0); let rect=std::cell::Cell::new(Rect::NOTHING); - let frame=|time,events| ctx.run_ui(egui::RawInput { time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,300.0))),events,..Default::default() },|ui| { + let frame=|time,events| ctx.settle_ui(egui::RawInput { time:Some(time),screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(600.0,300.0))),events,..Default::default() },|ui| { rect.set(context_meter(ui,None,true,true).rect); }); frame(0.0,vec![]); @@ -5625,7 +5578,7 @@ mod tests { let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); let (mut app,requests)=dock_fixture();let w=app.jiansun.as_mut().unwrap();w.model_settings=true;w.reduce_motion=false; w.copy_models=vec![json!({"key":"a","id":"文案当前模型"}),json!({"key":"b","id":"文案备选模型"})];w.copy_model="a".into();w.available_models=None; - let frame=|w:&mut Workspace,time:f64,events|ctx.run_ui(egui::RawInput{time:Some(time),events,screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,700.0))),..Default::default()},|ui|{let anchor=ui.button("设置");w.settings_popup(ui,&anchor);}); + let frame=|w:&mut Workspace,time:f64,events|ctx.settle_ui(egui::RawInput{time:Some(time),events,screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,700.0))),..Default::default()},|ui|{let anchor=ui.button("设置");w.settings_popup(ui,&anchor);}); for i in 0..20 {let _=frame(w,f64::from(i)*0.05,vec![]);} let id=ctx.data(|data|data.get_temp::(Id::unique(("agent-model-last-popup",ModelRole::Copy,true)))).unwrap();egui::Popup::open_id(&ctx,id); for i in 20..30 {let _=frame(w,f64::from(i)*0.05,vec![]);} @@ -5699,7 +5652,7 @@ mod tests { let out={ let mut last=None; for n in 0..5 { - last=Some(ctx.run_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(n as f64*0.1),..Default::default()},|ui| {w.notifications_ui(ui);})); + last=Some(ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(n as f64*0.1),..Default::default()},|ui| {w.notifications_ui(ui);})); } last.unwrap() }; @@ -5710,7 +5663,7 @@ mod tests { let at=egui::pos2(rect[0]+rect[2]/2.,rect[1]+rect[3]/2.); let mut clicked=false; for (time,pressed) in [(0.6,true),(0.7,false)] { - let _=ctx.run_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(time),events:vec![egui::Event::PointerMoved(at),egui::Event::PointerButton {pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}],..Default::default()},|ui| {clicked|=w.notifications_ui(ui);}); + let _=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(time),events:vec![egui::Event::PointerMoved(at),egui::Event::PointerButton {pos:at,button:egui::PointerButton::Primary,pressed,modifiers:egui::Modifiers::NONE}],..Default::default()},|ui| {clicked|=w.notifications_ui(ui);}); } assert!(clicked); assert!(requests.try_recv().is_err(),"viewing retained candidates must not call a model or send an operation"); @@ -5718,7 +5671,7 @@ mod tests { assert_eq!(app.session.active().unwrap().revision,revision); w.error.clear(); ctx.data_mut(|data|data.get_temp_mut_or_default::(id).open=true); - let out=ctx.run_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(1.),..Default::default()},|ui| {w.notifications_ui(ui);}); + let out=ctx.settle_ui(egui::RawInput {screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(500.,700.))),time:Some(1.),..Default::default()},|ui| {w.notifications_ui(ui);}); let text=out.shapes.iter().filter_map(|shape|match &shape.shape {egui::Shape::Text(text)=>Some(text.galley.text()),_=>None}).collect::>().join("\n"); assert!(text.contains("历史通知") && !text.contains("当前问题")); assert_eq!(ctx.data(|data|data.get_temp::(id).unwrap().entries.len()),2,"historical records remain available after the active issue ends"); @@ -5731,6 +5684,7 @@ mod tests { json!({"text":"普通回复不会变成通知"}), json!({"text":"保存副本时有导出提示:\n保留工程"}), ]; + history.observe("", true, None, &[]); history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); assert_eq!(history.entries.len(), 4); history.observe("连接暂不可用", true, Some("提示库离线,本机内容已保留"), &receipts); @@ -5760,11 +5714,11 @@ mod tests { ctx.data_mut(|data| data.insert_temp(id, history)); let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 300.0)); for frame in 0..4 { - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(screen), time:Some(frame as f64 * 0.1), ..Default::default() }, |ui| {w.notifications_ui(ui);}); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(frame as f64 * 0.1), ..Default::default() }, |ui| {w.notifications_ui(ui);}); } let rect: [f32; 4] = serde_json::from_value(w.panel_geometry["notifications"].clone()).unwrap(); assert!(screen.contains_rect(Rect::from_min_size(egui::pos2(rect[0],rect[1]),vec2(rect[2],rect[3]))), "long notifications must scroll inside the viewport: {rect:?}"); - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(screen), time:Some(0.5), events:vec![egui::Event::Key { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(screen), time:Some(0.5), events:vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE, }], ..Default::default() }, |ui| { w.notifications_ui(ui); @@ -5789,7 +5743,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let id = notification_id(&w.origin, &w.account, &w.project_context, w.owner_doc).unwrap(); ctx.data_mut(|data| data.insert_temp(id, AgentNotifications { open:true, ..Default::default() })); - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0,600.0))), + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0,600.0))), events:vec![egui::Event::Key { key:egui::Key::Escape, physical_key:Some(egui::Key::Escape), pressed:true, repeat:false, modifiers:egui::Modifiers::NONE }], ..Default::default() }, |ui| w.composer_ui(&mut app, ui)); assert!(!ctx.data(|data| data.get_temp::(id).unwrap().open)); @@ -5822,7 +5776,7 @@ mod tests { fn copy_reply_emits_only_the_exact_visible_reply_on_user_click() { let ctx = egui::Context::default(); let mut rect = Rect::NOTHING; - let render = |time, events, rect: &mut Rect| ctx.run_ui(egui::RawInput { + let render = |time, events, rect: &mut Rect| ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 100.0))), time: Some(time), events, ..Default::default() }, |ui| { *rect = copy_reply(ui, "真实中文回复").rect; }); let idle = render(0.0, vec![], &mut rect); @@ -5891,7 +5845,7 @@ mod tests { json!({"role":"assistant","kind":"image","taskId":"layout-image"}), json!({"role":"assistant","kind":"pi-ui-request","request":{"id":"choose","title":"首屏主图怎么处理"}}), ]; - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(500.0, 800.0))), ..Default::default() }, |ui| { @@ -5910,7 +5864,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let frame = |app: &PhotocraftApp| { let mut bounds = Rect::NOTHING; - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { let start = ui.cursor().min; app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"layout-image"}), 112.0); bounds = Rect::from_min_max(start, ui.cursor().min); @@ -5937,7 +5891,7 @@ mod tests { let texture_id = texture.id(); let w = app.jiansun.as_mut().unwrap(); w.agent_images.insert("result".into(), texture); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| { w.image_result(ui, &json!({"taskId":"result"}), 200.0); }); output.textures_delta.clear(); @@ -5963,13 +5917,13 @@ mod tests { let texture = ctx.load_texture(id, egui::ColorImage::filled([8, 8], Color32::WHITE), egui::TextureOptions::LINEAR); app.jiansun.as_mut().unwrap().agent_images.insert(id.into(), texture); } - ctx.run_ui(egui::RawInput::default(), |ui| { + ctx.settle_ui(egui::RawInput::default(), |ui| { ui.set_clip_rect(Rect::from_min_size(pos2(5000.0, 5000.0), vec2(20.0, 20.0))); app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0); }).textures_delta.clear(); let cache = &app.jiansun.as_ref().unwrap().agent_images; assert_eq!(cache.iter().next().map(|(key, _)| key.as_str()), Some("hidden")); - ctx.run_ui(egui::RawInput::default(), |ui| { + ctx.settle_ui(egui::RawInput::default(), |ui| { app.jiansun.as_ref().unwrap().image_result(ui, &json!({"taskId":"hidden"}), 112.0); }).textures_delta.clear(); assert_eq!(cache.iter().next_back().map(|(key, _)| key.as_str()), Some("hidden")); @@ -5982,7 +5936,7 @@ mod tests { egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| scan(shape, texture, fill, image, frame, label)), egui::Shape::Rect(rect) if rect.fill_texture_id() == texture => *image = Some(rect.rect), egui::Shape::Rect(rect) if rect.fill == fill && rect.corner_radius == egui::CornerRadius::same(8) => *frame = Some(rect.rect), - egui::Shape::Text(text) if text.galley.text() == "查看原图" => *label = Some(Rect::from_min_size(text.pos, text.galley.size())), + egui::Shape::Text(text) if text.galley.text() == "查看大图" => *label = Some(Rect::from_min_size(text.pos, text.galley.size())), _ => {} } } @@ -5999,7 +5953,7 @@ mod tests { let run = |ctx: &egui::Context, app: &PhotocraftApp, events| { let current = time.get(); time.set(current + 0.25); - let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), time: Some(current), events, ..Default::default() }, |ui| { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), time: Some(current), events, ..Default::default() }, |ui| { app.jiansun.as_ref().unwrap().image_result(ui, &value, 112.0); }); output.textures_delta.clear(); @@ -6009,7 +5963,7 @@ mod tests { let mut image = None; let mut frame = None; let mut label = None; - let fill = Tokens::get(&ctx).agent().tab_strip; + let fill = super::super::stitch_ui::menu_base(); for shape in &first.shapes { scan(&shape.shape, texture_id, fill, &mut image, &mut frame, &mut label); } let pos = image.expect("history result contains the actual preview texture").center(); for pressed in [true, false] { @@ -6053,7 +6007,7 @@ mod tests { for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } dock_click(&ctx, &mut app, "chatModel"); for _ in 0..18 { dock_frame(&ctx, &mut app, vec![]); } - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); let mut text = Vec::new(); for shape in &output.shapes { labels(&shape.shape, &mut text); } let unselected = text.iter().find(|(name, _, _)| name == "未选择").expect("the menu renders an unselected option").1; @@ -6079,7 +6033,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let w = app.jiansun.as_mut().unwrap(); let frame = |w: &mut Workspace| { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), ..Default::default() }, |ui| { w.model_picker(ui, ModelRole::Chat, 160.0, true); }); }; let last = Id::unique(("agent-model-last-popup", ModelRole::Chat, true)); @@ -6159,7 +6113,7 @@ mod tests { w.reduce_motion = true; let frame = |w: &mut Workspace, events: Vec| { let mut response_id = None; - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(360.0, 600.0))), events, ..Default::default() }, |ui| { response_id = Some(w.model_picker(ui, ModelRole::Chat, 80.0, true).id); }); @@ -6208,7 +6162,7 @@ mod tests { } let mut output = None; for _ in 0..3 { - let mut frame = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); + let mut frame = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); frame.textures_delta.clear(); output = Some(frame); } @@ -6242,7 +6196,7 @@ mod tests { w.reduce_motion = false; } let frame = |time: f64, app: &mut PhotocraftApp| { - ctx.run_ui(egui::RawInput { + ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0))), time: Some(time), ..Default::default() @@ -6294,7 +6248,7 @@ mod tests { ]}); ctx.data_mut(|d| d.insert_temp(id, "first".to_owned())); let frame = |time:f64, events| { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(800.0,600.0))), time:Some(time), events, ..Default::default() }, |ui| w.artifact_window(ui)); output.textures_delta.clear(); @@ -6342,7 +6296,7 @@ mod tests { w.agent_images.insert("preview".into(), texture); ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); let frame = |time: f64, w: &Workspace| { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0))), time: Some(time), ..Default::default() }, |ui| w.artifact_window(ui)); @@ -6379,7 +6333,7 @@ mod tests { w.agent_images.insert("preview".into(), texture); ctx.data_mut(|d| d.insert_temp(id, "preview".to_owned())); let frame = |time:f64, events| { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(640.0,480.0))), time:Some(time), events, ..Default::default() }, |ui| w.artifact_window(ui)); output.textures_delta.clear(); @@ -6675,7 +6629,7 @@ mod tests { w.busy = pending.then(|| "slot-generate".into()); w.agent_effects_paused = paused; ctx.memory_mut(|memory| memory.request_focus(Id::unique("jiansun-composer-input"))); - let _ = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| { crate::panels::right_dock(&mut app, ui); }); app.jiansun.as_ref().unwrap().panel_geometry.clone() @@ -6720,7 +6674,7 @@ mod tests { w.reduce_motion = true; let mut output = None; for _ in 0..3 { - let mut frame = ctx.run_ui( + let mut frame = ctx.settle_ui( egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui), ); @@ -7450,7 +7404,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); for width in [250.0, 520.0] { - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(650.0, 900.0))), ..Default::default() }, |ui| { @@ -7689,9 +7643,11 @@ mod tests { let (mut app, requests) = dock_fixture(); let mut w = app.jiansun.take().unwrap(); w.composer.clear(); - let subject = json!({"kind":"candidate","label":"主视觉","pageId":"S01","slotId":"slot","productVariantId":"brown","candidateId":"candidate-3"}); - w.template_workflow = json!({"templateId":"pack","slots":[{"id":"slot","variantId":"brown","candidates":[{"id":"candidate-3"}]}]}); + let subject = json!({"kind":"candidate","label":"主视觉","pageId":"S01","slotId":"slot","outputId":"detail","productVariantId":"brown","candidateId":"candidate-3"}); + w.template_workflow = json!({"templateId":"pack","canvasFirst":true,"slots":[{"id":"slot","outputId":"detail","label":"主视觉","variantId":"brown","candidates":[{"id":"candidate-3"}]}]}); w.canvas_workspace.context = Some(subject.clone()); + w.composer_reference_clear(&app); + w.composer_reference_add(&app).expect("attach the selected candidate to the draft"); w.library = false; w.focus_composer = true; w.reduce_motion = true; @@ -7700,19 +7656,20 @@ mod tests { app.jiansun = Some(w); let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); for _ in 0..2 { - let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { let mut workspace = app.jiansun.take().unwrap(); workspace.right(&mut app, ui); app.jiansun = Some(workspace); }); output.textures_delta.clear(); } - let expected_reference = app.jiansun.as_ref().unwrap().composer_reference_list(&app)[0].clone(); + let expected_reference = app.jiansun.as_ref().unwrap().composer_reference_list(&app).into_iter() + .find(|reference| reference["candidateId"] == subject["candidateId"]).expect("the attached candidate remains available"); assert_eq!(expected_reference["candidateId"], subject["candidateId"]); let rect = app.jiansun.as_ref().unwrap().panel_geometry["subject"].as_array().unwrap(); let at = pos2((rect[0].as_f64().unwrap() + 12.0) as f32, (rect[1].as_f64().unwrap() + rect[3].as_f64().unwrap() / 2.0) as f32); - let mut hovered = ctx.run_ui( + let mut hovered = ctx.settle_ui( egui::RawInput { screen_rect: Some(screen), events: vec![egui::Event::PointerMoved(at)], ..Default::default() }, |ui| { let mut workspace = app.jiansun.take().unwrap(); @@ -7722,7 +7679,7 @@ mod tests { ); hovered.textures_delta.clear(); for pressed in [true, false] { - let mut output = ctx.run_ui( + let mut output = ctx.settle_ui( egui::RawInput { screen_rect: Some(screen), events: vec![ @@ -7766,7 +7723,7 @@ mod tests { for (account, doc, text) in [("b", id, "其他账户"), ("a", id + 1, "其他文档"), ("a", id, "正在调整中文")] { events.send(Event::Json("agent-stream".into(), Ok(json!({"doc":doc,"accountId":account,"origin":w.origin,"text":text})))).unwrap(); } - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); + let mut output = ctx.settle_ui(egui::RawInput::default(), |ui| w.tick(&mut app, ui.ctx())); output.textures_delta.clear(); assert_eq!(w.stream_reply, "正在调整中文"); assert!(w.queue.is_empty()); @@ -7864,7 +7821,7 @@ mod tests { let ctx = egui::Context::default(); PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); for _ in 0..3 { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)).drop_without_applying_deltas(); + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)).drop_without_applying_deltas(); } let w = app.jiansun.as_ref().unwrap(); assert!(!w.panel_geometry["composerExpanded"].as_bool().unwrap()); @@ -7885,7 +7842,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 800.0)); let frame = |app: &mut PhotocraftApp, events| { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| crate::panels::right_dock(app, ui)).drop_without_applying_deltas(); }; for _ in 0..3 { frame(&mut app, vec![]); } @@ -7957,7 +7914,7 @@ mod tests { PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); crate::panels::request_dock_width(&ctx, dock_width); for _ in 0..2 { - let mut output = ctx.run_ui(egui::RawInput { + let mut output = ctx.settle_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(960.0, 600.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app, ui)); @@ -7988,7 +7945,7 @@ mod tests { for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] { let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="短句".into();} let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame=|app:&mut PhotocraftApp|{let _=ctx.run_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),..Default::default()},|ui|crate::panels::right_dock(app,ui));}; + let frame=|app:&mut PhotocraftApp|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),..Default::default()},|ui|crate::panels::right_dock(app,ui));}; for _ in 0..4{frame(&mut app);}let short=geometry(app.jiansun.as_ref().unwrap(),"composer").height(); let text="请保留原来的产品结构、字体和字号,分别为本次引用的文字格生成候选文案。\n".repeat(8);app.jiansun.as_mut().unwrap().composer=text.clone(); for _ in 0..4{frame(&mut app);}let w=app.jiansun.as_ref().unwrap();let surface=geometry(w,"composer");assert!(surface.height()>short+48.0);assert!(surface.height()<=size.y*0.5+1.0);assert!(surface.bottom()<=size.y);assert_eq!(w.composer,text); @@ -7998,7 +7955,7 @@ mod tests { fn composer_paste_and_resize_keep_the_focused_caret_visible() { let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer.clear();} let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let frame=|app:&mut PhotocraftApp,size,events|{let _=ctx.run_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),events,..Default::default()},|ui|crate::panels::right_dock(app,ui));}; + let frame=|app:&mut PhotocraftApp,size,events|{let _=ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,size)),events,..Default::default()},|ui|crate::panels::right_dock(app,ui));}; for _ in 0..4 {frame(&mut app,vec2(1518.0,1032.0),vec![]);} frame(&mut app,vec2(1518.0,1032.0),vec![egui::Event::Text("请分别修改引用的文字格,保留字体字号和排版。".repeat(36))]); for size in [vec2(1518.0,1032.0),vec2(1100.0,720.0)] {for _ in 0..4 {frame(&mut app,size,vec![]);}let w=app.jiansun.as_ref().unwrap();let caret=geometry(w,"inputCaret");let input=geometry(w,"input");assert!(input.expand(1.0).contains_rect(caret),"input={input:?}, caret={caret:?}");} @@ -8007,7 +7964,7 @@ mod tests { fn composer_scrolling_input_keeps_the_shared_glass_background() { let (mut app,_requests)=dock_fixture();app.ui.dock_tabs.color=4;{let w=app.jiansun.as_mut().unwrap();w.reduce_motion=true;w.focus_composer=true;w.composer="请保留文字格的原有排版。".repeat(40);} let ctx=egui::Context::default();PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); - let mut output=None;for _ in 0..4 {output=Some(ctx.run_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1100.0,720.0))),..Default::default()},|ui|crate::panels::right_dock(&mut app,ui)));} + let mut output=None;for _ in 0..4 {output=Some(ctx.settle_ui(egui::RawInput{screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1100.0,720.0))),..Default::default()},|ui|crate::panels::right_dock(&mut app,ui)));} let input=geometry(app.jiansun.as_ref().unwrap(),"input");assert!(app.jiansun.as_ref().unwrap().panel_geometry["inputContentHeight"].as_f64().unwrap()>input.height() as f64); fn masks(shape:&egui::Shape,input:Rect)->bool {match shape {egui::Shape::Mesh(mesh)=>{let bounds=mesh.calc_bounds();bounds.width()>input.width()*0.8&&bounds.height()<=24.0&&(bounds.bottom()-input.bottom()).abs()<1.0},egui::Shape::Vec(shapes)=>shapes.iter().any(|shape|masks(shape,input)),_=>false}} assert!(!output.unwrap().shapes.iter().any(|shape|masks(&shape.shape,input)),"scrolling text must not add an opaque edge over the shared glass"); @@ -8051,7 +8008,7 @@ mod tests { let id = super::super::composer_input_id(); ctx.memory_mut(|m| m.request_focus(id)); let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| w.composer_ui(app,ui)); + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| w.composer_ui(app,ui)); }; frame(&mut w,&mut app,vec![]); frame(&mut w,&mut app,vec![egui::Event::Text("不得丢失".into())]); @@ -8077,7 +8034,7 @@ mod tests { ctx.memory_mut(|memory| memory.request_focus(id)); let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events| { let mut leaked = false; - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { w.composer_ui(app,ui); leaked = ui.input(|input| input.key_pressed(egui::Key::Escape)); }); @@ -8116,7 +8073,7 @@ mod tests { let modal = Id::unique("escape-priority-modal"); let frame = |w:&mut Workspace, app:&mut PhotocraftApp, events, show_modal:bool| { let mut closed = false; - let _ = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(520.0,400.0))), events, ..Default::default() }, |ui| { w.composer_ui(app,ui); if show_modal { closed = egui::Modal::new(modal).show(ui.ctx(),|ui| { ui.label("模态内容"); }).should_close(); } }); @@ -8145,7 +8102,7 @@ mod tests { w.reduce_motion=true; w.focus_composer=true; let ctx=egui::Context::default(); PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); ctx.set_pixels_per_point(scale); for _ in 0..4 { - let _=ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(width,500.0))), ..Default::default() }, |ui| { + let _=ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(width,500.0))), ..Default::default() }, |ui| { ui.set_width(width); w.composer_ui(&mut app,ui); }); } @@ -8221,7 +8178,7 @@ mod tests { assert!(geometry(w,"composer").contains_rect(geometry(w,"send"))); assert!(w.panel_geometry["composerMore"].is_array()); dock_click(&ctx,&mut app,"composerMore"); - let output = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); let mut labels = Vec::new(); for shape in &output.shapes { texts(&shape.shape,&mut labels); } assert!(labels.iter().any(|(text,_)| text == "添加本地参考图")); @@ -8266,7 +8223,7 @@ mod tests { for _ in 0..2 { dock_frame(&ctx,&mut app,vec![]); } let popup = Id::unique("jiansun-composer-more-popup"); assert!(egui::Popup::is_id_open(&ctx,popup),"a real click opens the overflow menu with an empty draft"); - let output = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); let mut labels=Vec::new(); for shape in &output.shapes { collect(&shape.shape,&mut labels); } assert!(labels.iter().any(|(text,_)| text=="添加本地参考图")); @@ -8283,7 +8240,7 @@ mod tests { app.jiansun.as_mut().unwrap().focus_composer = true; for _ in 0..3 { dock_frame(&ctx,&mut app,vec![]); } dock_click(&ctx,&mut app,"composerMore"); - let output = ctx.run_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); + let output = ctx.settle_ui(egui::RawInput { screen_rect:Some(Rect::from_min_size(egui::Pos2::ZERO,vec2(1280.0,800.0))), ..Default::default() }, |ui| crate::panels::right_dock(&mut app,ui)); labels.clear(); for shape in &output.shapes { collect(&shape.shape,&mut labels); } let prompt = labels.iter().find(|(text,_)|text=="常用提示词").unwrap().1.center(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs index 4d397b98..35606102 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_stream.rs @@ -2,21 +2,25 @@ //! conversation reads as the same quiet row, production progress is a single //! row of cells, and suggestions are borderless chips. Materials and motion //! stay with `stitch_ui` and `agent_motion`; this module fixes only geometry -//! and typography so the rows cannot drift apart. +//! and typography so the rows cannot drift apart. Sizes and colours come from +//! `theme::agent_scale` and the semantic tokens; nothing here reads copy to decide a state. use super::{agent_panel::rect_value, json, Tokens, RichText, Value}; -use egui::{Color32, FontId, Id, Layout, Rect, Response, Sense, Stroke, Ui, Vec2, vec2}; +use super::stitch_state::{Tone, WorkerStage}; +use crate::theme::agent_scale::{control, Type}; +use egui::{Color32, Id, Layout, Rect, Response, Sense, Stroke, Ui, Vec2, vec2}; /// The agent surface uses three sizes only: 12 for rows and meta, 13 for /// titles and controls, 14 for reply prose (kept by `stitch_ui::reply`). -pub(super) const TEXT_META: f32 = 12.0; -pub(super) const TEXT_TITLE: f32 = 13.0; +pub(super) const TEXT_META: f32 = Type::Meta.size(); +pub(super) const TEXT_TITLE: f32 = Type::Title.size(); /// One timeline row. Every glyph, label and meta line is centred in it. -pub(super) const ROW: f32 = 24.0; +pub(super) const ROW: f32 = control::ROW; /// Reserve the full suggestion row and its gap above the composer. pub(super) const SUGGESTION_ROW_HEIGHT: f32 = 52.0; -/// Waiting cells: amber is filled but unverified, blue is verified. -pub(super) const CELL_FILLED: Color32 = Color32::from_rgb(181, 133, 92); -const CELL_VERIFIED: Color32 = Color32::from_rgb(85, 145, 190); +/// Waiting cells take their colours from the semantic tokens: amber is filled but +/// unverified, blue is verified. +pub(super) fn cell_filled(t: &Tokens) -> Color32 { t.agent_semantic().progress } +pub(super) fn cell_verified(t: &Tokens) -> Color32 { t.agent_semantic().verified } /// One footprint for every sub-agent badge in the open head. A running badge /// is about 49pt wide (three dots, a letter, the padding); a waiting one owns /// no dots. The list gives both the same width so their labels share a column. @@ -34,6 +38,18 @@ pub(super) enum EventTone { Failure, } +/// 统一色调转进事件行:成功、已核验、进度与静止一样走次要色,只有进行、警告、失败有专属颜色。 +impl From for EventTone { + fn from(tone: Tone) -> Self { + match tone { + Tone::Active => Self::Active, + Tone::Warning | Tone::Unknown => Self::Warning, + Tone::Failure => Self::Failure, + Tone::Quiet | Tone::Success | Tone::Verified | Tone::Progress => Self::Quiet, + } + } +} + /// What the whole row does. `Click` rows locate something; `Expand` rows /// disclose a body and carry the chevron. #[derive(Clone, Copy, PartialEq, Eq)] @@ -91,14 +107,14 @@ pub(super) fn event_row(ui: &mut Ui, id: Id, row: EventRow<'_>, reduced: bool) - end -= 18.0; } if let Some(meta) = row.meta.filter(|meta| !meta.is_empty()) { - let galley = painter.layout_no_wrap(meta.to_owned(), FontId::proportional(TEXT_META), t.text_faint); + let galley = painter.layout_no_wrap(meta.to_owned(), Type::Meta.font_id(), t.text_faint); end -= galley.size().x; let top = middle - galley.size().y * 0.5; painter.galley(egui::pos2(end, top), galley, t.text_faint); end -= 8.0; } let start = rect.left() + 26.0; - let mut job = egui::text::LayoutJob::simple_singleline(row.text.to_owned(), FontId::proportional(TEXT_META), tint); + let mut job = egui::text::LayoutJob::simple_singleline(row.text.to_owned(), Type::Meta.font_id(), tint); job.wrap.max_width = (end - start).max(1.0); job.wrap.max_rows = 1; let galley = painter.layout_job(job); @@ -171,8 +187,8 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac return json!({"total":cells.len(),"filled":filled,"verified":verified,"rect":rect_value(rect)}); } let painter = ui.painter_at(rect.intersect(ui.clip_rect())); - let label_galley = painter.layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_META), t.text); - let count_galley = painter.layout_no_wrap(counts, FontId::proportional(TEXT_META), t.text_dim); + let label_galley = painter.layout_no_wrap(label.to_owned(), Type::Meta.font_id(), t.text); + let count_galley = painter.layout_no_wrap(counts, Type::Meta.font_id(), t.text_dim); let counts_left = rect.left() + label_galley.size().x + 6.0; let lead = counts_left - rect.left() + count_galley.size().x + 10.0; painter.galley(egui::pos2(rect.left(), rect.center().y - label_galley.size().y * 0.5), label_galley, t.text); @@ -186,7 +202,7 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac let bar = Rect::from_min_size(egui::pos2(track.left(), rect.center().y - 4.0), vec2(track.width(), 8.0)); painter.rect_filled(bar, 3.0, t.field); response.on_hover_text(summary); - for (total, color) in [(filled, CELL_FILLED), (verified, CELL_VERIFIED)] { + for (total, color) in [(filled, cell_filled(&t)), (verified, cell_verified(&t))] { if total > 0 { let end = bar.left() + bar.width() * total as f32 / count as f32; painter.rect_filled(Rect::from_min_max(bar.min, egui::pos2(end, bar.bottom())), 3.0, color); @@ -198,8 +214,8 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac let square = Rect::from_min_size(origin, vec2(side, 7.0)); let fill = match state { Cell::Empty => t.card_border, - Cell::Filled => CELL_FILLED, - Cell::Verified => CELL_VERIFIED, + Cell::Filled => cell_filled(&t), + Cell::Verified => cell_verified(&t), }; painter.rect_filled(square, 2.0, fill); ui.interact(square, id.with(index), Sense::hover()).on_hover_text(describe(index)); @@ -209,7 +225,7 @@ pub(super) fn cell_rail(ui: &mut Ui, id: Id, label: &str, cells: &[Cell], compac } pub(super) fn suggestion_width(ui: &Ui, label: &str) -> f32 { - let font = FontId::proportional(TEXT_TITLE); + let font = Type::Title.font_id(); ui.painter().layout_no_wrap(label.to_owned(), font, Color32::WHITE).size().x + 38.0 } @@ -269,8 +285,8 @@ pub(super) fn queued_job(ui: &mut Ui, width: f32, label: &str, status: &str) -> 13.0, t.text_dim, ); - let status_galley = painter.layout_no_wrap(status.to_owned(), FontId::proportional(TEXT_META), t.text_dim); - let mut job = egui::text::LayoutJob::simple_singleline(label.to_owned(), FontId::proportional(TEXT_META), t.text); + let status_galley = painter.layout_no_wrap(status.to_owned(), Type::Meta.font_id(), t.text_dim); + let mut job = egui::text::LayoutJob::simple_singleline(label.to_owned(), Type::Meta.font_id(), t.text); job.wrap.max_width = (rect.width() - 30.0 - 12.0 - status_galley.size().x - 12.0).max(1.0); job.wrap.max_rows = 1; let caption = painter.layout_job(job); @@ -288,17 +304,24 @@ pub(super) fn queued_job(ui: &mut Ui, width: f32, label: &str, status: &str) -> /// it or locating it. The badge that reports this stage is still. pub(super) const STAGE_WAITING: &str = "等结果"; -/// The one classification of a sub-agent line. The summary row, the count -/// line and the open list's badge all read it here, so they cannot disagree -/// about whether a sub-agent is generating, reviewing, waiting or preparing. +/// 旧签名垫片:返回阶段的展示文案。阶段本身由 `WorkerStage::infer` 判定一次, +/// 摘要行、计数行与展开列表的徽标都读同一个判定,不会各说各话。 +/// 新代码请直接持有 `WorkerStage`;第 2 批把回执补上结构化阶段字段后, +/// 这层按中文前缀的兜底随调用方一起删除。 pub(super) fn worker_stage(step: &str, review: bool, from_image: bool) -> &'static str { - if review || step.contains("验图") { - "验图" - } else if ["正在等待原", "正在核查原", "正在定位原"].iter().any(|prefix| step.starts_with(prefix)) { - STAGE_WAITING - } else if from_image || step.starts_with("正在生图") || step.starts_with("正在生成图片") { - "生图" - } else { - "准备" + WorkerStage::infer(step, review, from_image).label() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn event_rows_preserve_active_warning_and_failure_tones() { + assert!(matches!(EventTone::from(Tone::Active), EventTone::Active)); + assert!(matches!(EventTone::from(Tone::Warning), EventTone::Warning)); + assert!(matches!(EventTone::from(Tone::Unknown), EventTone::Warning)); + assert!(matches!(EventTone::from(Tone::Failure), EventTone::Failure)); + assert!(matches!(EventTone::from(Tone::Verified), EventTone::Quiet)); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/blob_warp.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/blob_warp.rs index b19e6ebb..e8d18647 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/blob_warp.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/blob_warp.rs @@ -198,6 +198,7 @@ pub(super) fn paint(ui: &Ui, surface: Surface, reduced: bool, running: bool) -> #[cfg(test)] mod tests { + use crate::jiansun::test_support::SettleUi; use super::*; use egui::vec2; @@ -258,7 +259,7 @@ mod tests { let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); let surface = Surface::new(id, Rect::from_min_size(pos2(80.0, 80.0), vec2(100.0, 100.0)), 8.0); let frame = |time: f64, running: bool, reduced: bool| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| { let _ = paint(ui, surface, reduced, running); }); output.shapes.iter().filter_map(|shape| match &shape.shape { @@ -287,7 +288,7 @@ mod tests { let hidden = Surface::new(id, Rect::from_min_size(pos2(900.0, 900.0), vec2(100.0, 100.0)), 8.0); let frame = |time, surface, running| { let mut rendered = false; - let _ = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| { rendered = paint(ui, surface, false, running).is_some(); }); rendered @@ -307,13 +308,13 @@ mod tests { // RawInput without a screen rect defaults to a 10000×10000 // viewport in egui. Use an actual supported window so 9000,9000 // exercises off-screen culling rather than a visible giant UI. - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { assert!(paint(ui, Surface::new(id, rect, 8.0), false, true).is_none(), "invalid/off-screen bounds: {rect:?}"); assert!(ui.data(|data| data.get_temp::(Id::unique("stitch-waiting-blob-clocks"))).is_none()); assert!(ui.data(|data| data.get_temp::(Id::unique("stitch-waiting-blob-meshes"))).is_none()); }); } - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { ui.set_invisible(); assert!(paint(ui, Surface::new(id, Rect::from_min_size(pos2(16.0, 18.0), vec2(400.0, 84.0)), 8.0), false, true).is_none()); assert!(ui.data(|data| data.get_temp::(Id::unique("stitch-waiting-blob-clocks"))).is_none()); @@ -321,7 +322,7 @@ mod tests { }); let mut input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(true); - let _ = ctx.run_ui(input, |ui| { + let _ = ctx.settle_ui(input, |ui| { assert!(paint(ui, Surface::new(id, Rect::from_min_size(pos2(16.0, 18.0), vec2(400.0, 84.0)), 8.0), false, true).is_none()); assert!(ui.data(|data| data.get_temp::(Id::unique("stitch-waiting-blob-clocks"))).is_none()); }); @@ -332,7 +333,7 @@ mod tests { let ctx = egui::Context::default(); let surface = Rect::from_min_size(pos2(16.0, 18.0), vec2(400.0, 84.0)); let mut visual = None; - let output = ctx.run_ui(egui::RawInput::default(), |ui| { + let output = ctx.settle_ui(egui::RawInput::default(), |ui| { visual = paint(ui, Surface::new(Id::unique("request-and-target"), surface, 8.0), true, true); }); assert!(visual.is_some()); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/glow_pill.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/glow_pill.rs index 5891272a..04218009 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/glow_pill.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/glow_pill.rs @@ -105,7 +105,9 @@ pub(super) fn background(ui:&Ui, id:Id, rect:Rect, radius:f32, gain:f32, slot:eg text:Vec::new(),flanks:1.0,gain:gain.clamp(0.0,1.0),background_only:true,frame:ui.ctx().cumulative_frame_nr(), }); ui.painter().set(slot,shape); - if !reduced {ui.ctx().request_repaint_after(std::time::Duration::from_millis(16));} + // 玻璃光场只在悬停、聚焦或任务运行时亮着(gain 归零即停),这些都是交互或运行态:按满帧申请。 + // 窗口最小化或表面不可见时不申请任何重绘。 + if !reduced {super::agent_motion::schedule(ui,rect,super::agent_motion::Pace::Full);} } fn take_text(ui:&Ui,rect:Rect,start:usize,range:Option>)->Vec { fn extract(shape:&mut egui::Shape,text:&mut Vec) { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/operation_error.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/operation_error.rs index 5e3c2a49..b15ae253 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/operation_error.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/operation_error.rs @@ -1,5 +1,9 @@ -use egui::{FontId, RichText, Ui, vec2}; +//! 错误提示的文案与配色。分类只做一次:`ErrorCategory::classify` 是全库唯一读错误原文的地方, +//! 这里只负责把类别排成给人看的一句话、原因和建议;原文只进"技术详情"。 +use super::stitch_state::{ErrorCategory, Severity}; use super::stitch_ui as kit; +use crate::theme::agent_scale::{icon, Type}; +use egui::{RichText, Ui, vec2}; pub(super) struct Message<'a> { pub title: &'a str, @@ -8,49 +12,17 @@ pub(super) struct Message<'a> { pub image_read: bool, } +/// The reader-facing summary of one raw error. A business message that is already +/// plain language keeps its own words as the title. pub(super) fn message(raw:&str)->Message<'_> { - if raw.contains("素材库请求失败(HTTP 503)") { - return Message {title:"素材库暂时不可用",reason:Some("客户端没有收到素材库的可用响应,暂时无法核对账户或读取项目资料。"),guidance:Some("稍后重新核查。已经生成的候选仍保存在项目中。"),image_read:false}; - } - if raw.contains("模型服务暂时限流") { - return Message {title:"模型服务暂时繁忙",reason:Some("模型服务限制了这条回复,已完成的候选仍保留。"),guidance:Some("稍后可以继续发新消息。"),image_read:false}; - } - if raw.contains("结果未知;不会重发") || raw.contains("原请求结果待核查") { - return Message {title:"上一条回复需核查",reason:Some("小壹没有收到原请求的完整结果。"),guidance:Some("请选择核查结果。"),image_read:false}; - } - if raw == "客户端工具配置不匹配,本次未发送模型请求" { - return Message {title:"这次工具调用未发出",reason:Some("客户端在发送前拒绝了此次工具声明。前面已完成的操作仍会保留。"),guidance:None,image_read:false}; - } - let source_read=raw.starts_with("can't read smart source within the preview budget:"); - let source_size=source_read && (raw.contains("limit exceeded: canvas") || raw.contains("smart source canvas budget") || raw.contains("exceeds encoded byte budget")); - let placed=raw=="the placed smart source exceeds the preview budget" || raw=="smart filter working area exceeds the preview budget"; - if source_read || placed || raw=="the source file is empty or exceeds the 20 MiB limit" { - return Message { - title:"图片暂时无法读取", - reason:Some(if source_size {"客户端读取这张图片时,超出了预览的尺寸限制。"} - else if placed {"图片放置后的范围或效果超出了当前预览可处理的范围。"} - else {"客户端未能读取原图,当前操作没有完成。"}), - guidance:Some("如果已有生成结果,请先保留候选,不必重新生成;仍无法采纳时,可复制问题详情反馈。"), - image_read:true, - }; - } - if raw=="the linked file cannot be read" { - return Message {title:"原图文件无法读取",reason:Some("请确认关联的原图文件仍在原位置,并且可以正常打开。"),guidance:Some("保留当前项目;如果问题仍存在,可复制详情反馈。"),image_read:true}; - } - if raw.starts_with("本地SDK操作失败") { - return Message {title:"画布操作没有完成",reason:Some("请先核对原请求的处理结果,再继续操作。"),guidance:Some("不要重复提交;可复制问题详情反馈。"),image_read:false}; - } - if raw.is_ascii() { - Message {title:"这次操作没有完成",reason:Some("请查看问题详情,确认原因后再继续。"),guidance:None,image_read:false} - } else { - Message {title:raw,reason:None,guidance:None,image_read:false} - } + let category=ErrorCategory::classify(raw); + Message {title:category.title(raw),reason:category.reason(),guidance:category.guidance(),image_read:category.image_unreadable()} } fn dimensions(ui:&Ui,raw:&str,available_width:f32)->(f32,f32) { - let button=ui.painter().layout_no_wrap("查看详情".into(),FontId::proportional(13.0),egui::Color32::WHITE).size().x+ui.spacing().button_padding.x*2.0; + let button=ui.painter().layout_no_wrap("查看详情".into(),Type::Title.font_id(),egui::Color32::WHITE).size().x+ui.spacing().button_padding.x*2.0; let width=(available_width-14.0-button-ui.spacing().item_spacing.x*2.0).max(1.0); - let text=ui.painter().layout(message(raw).title.into(),FontId::proportional(14.0),egui::Color32::WHITE,width); + let text=ui.painter().layout(message(raw).title.into(),Type::Body.font_id(),egui::Color32::WHITE,width); (width,text.size().y.max(34.0)) } @@ -59,10 +31,11 @@ pub(super) fn inline_height(ui:&Ui,raw:&str,available_width:f32)->f32 {dimension pub(super) fn inline(ui:&mut Ui,raw:&str)->egui::Response { let t=crate::theme::Tokens::get(ui.ctx()).agent(); let (width,height)=dimensions(ui,raw,ui.available_width()); - let label=ui.painter().layout(message(raw).title.into(),FontId::proportional(14.0),t.text,width); + let label=ui.painter().layout(message(raw).title.into(),Type::Body.font_id(),t.text,width); + // 待核查与未发出是告警,不是失败:用警告色;其余仍是危险色。严重级别由类别给出,不再比对原文。 + let color=match ErrorCategory::classify(raw).severity() {Severity::Warning=>t.warning,Severity::Failure=>t.danger}; ui.horizontal_top(|ui| { - let color = if raw == "客户端工具配置不匹配,本次未发送模型请求" { t.warning } else { t.danger }; - ui.add(crate::icons::image("triangle-alert",14.0,color)); + ui.add(crate::icons::image("triangle-alert",icon::MD,color)); ui.add_sized(vec2(width,height),egui::Label::new(label).halign(egui::Align::Min)); kit::action_button(ui,"查看详情",kit::ButtonRole::Quiet,true) }).inner @@ -71,11 +44,11 @@ pub(super) fn inline(ui:&mut Ui,raw:&str)->egui::Response { pub(super) fn details(ui:&mut Ui,id:egui::Id,raw:&str,reduced:bool)->egui::Response { let t=crate::theme::Tokens::get(ui.ctx()).agent(); let text=message(raw); - ui.add(egui::Label::new(RichText::new(text.title).size(13.0).color(t.text)).wrap()); - if let Some(reason)=text.reason {ui.add(egui::Label::new(RichText::new(reason).size(12.0).color(t.text_dim)).wrap());} - if let Some(guidance)=text.guidance {ui.add(egui::Label::new(RichText::new(guidance).size(12.0).color(t.text)).wrap());} + ui.add(egui::Label::new(RichText::new(text.title).font(Type::Title.font_id()).color(t.text)).wrap()); + if let Some(reason)=text.reason {ui.add(egui::Label::new(RichText::new(reason).font(Type::Meta.font_id()).color(t.text_dim)).wrap());} + if let Some(guidance)=text.guidance {ui.add(egui::Label::new(RichText::new(guidance).font(Type::Meta.font_id()).color(t.text)).wrap());} if text.title!=raw { - kit::disclosure(ui,id,"技术详情",false,reduced,|ui| {kit::selectable_text(ui,RichText::new(raw).size(12.0).color(t.text_dim));}); + kit::disclosure(ui,id,"技术详情",false,reduced,|ui| {kit::selectable_text(ui,RichText::new(raw).font(Type::Meta.font_id()).color(t.text_dim));}); } let copy=kit::action_button(ui,"复制问题详情",kit::ButtonRole::Quiet,true); if copy.clicked() { @@ -89,6 +62,7 @@ pub(super) fn details(ui:&mut Ui,id:egui::Id,raw:&str,reduced:bool)->egui::Respo #[cfg(test)] mod tests { use super::*; + use crate::jiansun::test_support::SettleUi; #[test] fn template_limit_explains_the_local_failure_without_blame_or_regeneration() { @@ -113,12 +87,67 @@ mod tests { assert_eq!(message(business).title,business,"a partial success keeps its actual business meaning"); } + /// 文案与配色由类别一次决定:同一句原文,行内提示、详情页和复制出去的说明说的是同一件事。 + #[test] + fn a_notice_reads_the_same_category_inline_in_details_and_on_the_clipboard() { + for (raw, category) in [ + ("素材库请求失败(HTTP 503)", ErrorCategory::LibraryUnavailable), + ("模型服务暂时限流", ErrorCategory::ModelBusy), + ("结果未知;不会重发", ErrorCategory::UnknownResult), + ("原请求结果待核查", ErrorCategory::UnknownResult), + ("客户端工具配置不匹配,本次未发送模型请求", ErrorCategory::ToolRejected), + ("the linked file cannot be read", ErrorCategory::ImageLinkedMissing), + ("本地SDK操作失败:x", ErrorCategory::CanvasOperationFailed), + ("the placed smart source exceeds the preview budget", ErrorCategory::ImagePlacementExceeded), + ("the source file is empty or exceeds the 20 MiB limit", ErrorCategory::ImageUnreadable), + ] { + let notice = message(raw); + assert_eq!(ErrorCategory::classify(raw), category, "{raw}"); + assert_eq!(notice.title, category.title(raw), "{raw}"); + assert_eq!(notice.reason, category.reason(), "{raw}"); + assert_eq!(notice.guidance, category.guidance(), "{raw}"); + assert_eq!(notice.image_read, category.image_unreadable(), "{raw}"); + assert_ne!(notice.title, raw, "a raw technical message never becomes the headline"); + } + } + + /// 待核查与未发出画成警告而不是错误;行内提示的颜色由类别的严重级别决定,不再比对原文。 + #[test] + fn inline_color_follows_the_category_severity() { + fn painted(shape: &egui::Shape, color: egui::Color32) -> usize { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().map(|shape| painted(shape, color)).sum(), + egui::Shape::Rect(rect) if rect.fill == color => 1, + _ => 0, + } + } + let ctx=egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); + let t=crate::theme::Tokens::get(&ctx).agent(); + let paints=|raw:&str,color:egui::Color32| { + let mut output=ctx.settle_ui(egui::RawInput {screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(480.0,400.0))),..Default::default()},|ui| { + kit::scope_with_motion(ui,true,|ui| { + let response=inline(ui,raw); + assert!(response.rect.right()<=ui.max_rect().right()+0.1); + }); + }); + output.textures_delta.clear(); + output.shapes.iter().map(|clipped|painted(&clipped.shape,color)).sum::() + }; + let warned="客户端工具配置不匹配,本次未发送模型请求"; + assert_eq!(ErrorCategory::classify(warned).severity(),Severity::Warning); + assert!(paints(warned,t.warning)>0 && paints(warned,t.danger)==0,"a tool call that was never sent is a warning, not a failure"); + let unreachable="素材库请求失败(HTTP 503)"; + assert_eq!(ErrorCategory::classify(unreachable).severity(),Severity::Failure); + assert!(paints(unreachable,t.danger)>0 && paints(unreachable,t.warning)==0,"an unreachable library stays a failure"); + } + #[test] fn error_banner_wraps_inside_narrow_width_and_reserves_its_full_height() { let ctx=egui::Context::default(); crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); for width in [240.0,480.0] { - let mut output=ctx.run_ui(egui::RawInput {screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(width,400.0))),..Default::default()},|ui| { + let mut output=ctx.settle_ui(egui::RawInput {screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(width,400.0))),..Default::default()},|ui| { kit::scope_with_motion(ui,true,|ui| { let raw="当前项目或画布已有变化,候选已保留,未覆盖你的编辑。请切回对应的项目后再继续。"; let expected=inline_height(ui,raw,ui.available_width()); @@ -138,7 +167,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); let raw="can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side"; let mut rect=egui::Rect::NOTHING; - let render=|time,events,rect:&mut egui::Rect|ctx.run_ui(egui::RawInput {screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(420.,600.))),time:Some(time),events,..Default::default()},|ui| { + let render=|time,events,rect:&mut egui::Rect|ctx.settle_ui(egui::RawInput {screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(420.,600.))),time:Some(time),events,..Default::default()},|ui| { kit::scope_with_motion(ui,true,|ui| {*rect=details(ui,egui::Id::unique("copy-error"),raw,true).rect;}); }); let mut initial=render(0.,vec![],&mut rect); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/siri_orb.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/siri_orb.rs index 8c1c1ce1..ac30b37f 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/siri_orb.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/siri_orb.rs @@ -1,162 +1,305 @@ -//! Native Siri-style orb for the 小壹 panel. +//! 小壹的液态微光核心:原生网格,没有音频输入,也不暗示语音能力。 //! -//! Adapted visually from SmoothUI's MIT-licensed Siri Orb by Eduardo Calvo: -//! . The original license is retained in -//! `licenses/LICENSE-SmoothUI-MIT.txt`. This native mesh has no audio input. -use egui::{Color32, Id, Mesh, Rect, Shape, Ui}; +//! 2026-11-26 按用户定稿升级为小壹自己的材质:暖玉白基底上,琥珀、冷月青、暖玉白与月芯四层 +//! 液态微光缓缓绕行,球外一圈冷月青柔光。待机极柔慢呼吸,输入轻柔响应,运行平稳流动; +//! 暂停时在 190ms 内平滑减速、微微变暗并定格。最小化、被裁掉或不可见时不安排任何重绘。 +//! 球面形态仍参考 SmoothUI 的 Siri Orb(MIT,Eduardo Calvo, +//! ),许可证保留在 `licenses/LICENSE-SmoothUI-MIT.txt`。 +use crate::theme::agent_scale::motion as timing; +use crate::theme::AGENT_SEMANTIC; +use egui::{Color32, Id, Mesh, Rect, Shape, Ui, Vec2, pos2, vec2}; use std::collections::VecDeque; +use super::agent_motion::{Pace, schedule}; + const TAU: f32 = std::f32::consts::TAU; const BASE_PHASE: f32 = 22.0 / 24.0; -const LOOP_SECONDS: f64 = 20.0; +const LOOP_SECONDS: f64 = timing::ORB_LOOP; +const BREATH_SECONDS: f64 = timing::ORB_BREATH; +/// 速度平滑过渡的时间常数(秒)。暂停不用它:暂停走定长的减速窗口,到点恰好静止。 +const SPEED_TAU: f32 = 0.24; +/// 暂停时减速、变暗并恰好静止所用的窗口,180–200ms。 +const STOP_SETTLE: f64 = timing::STOP_SETTLE; +/// 暂停定格后暗下去的幅度。 +const REST_DIM: f32 = 0.22; const STATIC_CACHE_LIMIT: usize = 32; const MOTION_SAMPLES: u16 = 128; -const BACKGROUND: [f32; 3] = [231.0, 225.0, 246.0]; -const PINK: [f32; 3] = [241.0, 83.0, 170.0]; -const CYAN: [f32; 3] = [0.0, 185.0, 219.0]; -const VIOLET: [f32; 3] = [138.0, 121.0, 255.0]; -const MAGENTA: [f32; 3] = [222.0, 116.0, 229.0]; +/// 缓存网格的边长。尺寸只是变换:身份入口变大不重建网格,也不为每种尺寸各缓存一份。 +const CANONICAL: f32 = 48.0; +const SEGMENTS: u32 = 64; +const BODY_RINGS: u32 = 16; +/// 球外柔光共四圈,先画,垫在球体边缘下面:半径相对球体,强度逐圈递减,最外一圈透明。 +const HALO_REACH: [f32; 4] = [0.88, 1.0, 1.3, 1.6]; +const HALO_LEVEL: [f32; 4] = [1.0, 1.0, 0.42, 0.0]; +const HALO_ALPHA: f32 = 0.30; +const HALO_VERTEXES: usize = HALO_REACH.len() * SEGMENTS as usize; +/// 球体半径:在分配区域里四周留两个逻辑点。 +const BODY_RADIUS: f32 = CANONICAL * 0.5 - 2.0; -// CSS conic-gradient layer order from the reference, back to front: center, -// color, transparent interval and angle multiplier. The native version uses a -// small, fixed kernel to soften the field; no drawn rings or discrete dots. -type GradientLayer = ([f32; 2], [f32; 3], f32, f32, f32); -const LAYERS: [GradientLayer; 7] = [ - ([0.85, 0.10], VIOLET, 0.20, 0.80, -2.0), - ([0.20, 0.80], PINK, 0.10, 0.90, 1.0), - ([0.15, 0.05], CYAN, 0.10, 0.90, 2.0), - ([0.60, 0.35], MAGENTA, 0.25, 0.75, 1.5), - ([0.80, 0.20], PINK, 0.40, 0.60, -3.0), - ([0.45, 0.75], CYAN, 0.30, 0.60, 2.0), - ([0.25, 0.70], VIOLET, 0.20, 0.80, 2.0), -]; - -#[derive(Clone, Copy, PartialEq, Eq)] -pub(super) enum Motion { Still, Idle, Thinking } +/// 身份入口的节奏档位。调用方按真实状态选择,光球自己不判断任务是否在跑。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Motion { + /// 完全静止:历史头像、减少动态。 + Still, + /// 待机:极柔慢呼吸。 + Idle, + /// 输入中:轻柔响应。 + Listening, + /// 运行中:平稳流动。 + Thinking, + /// 等结果:比运行慢一档的巡视。 + #[allow(dead_code, reason = "第 2 批由 RunState::WaitingResume 接入")] + Waiting, + /// 暂停或停止:190ms 内减速、微微变暗并定格。 + #[allow(dead_code, reason = "第 2 批由 RunState::Stopped 接入")] + Paused, +} impl Motion { pub(super) fn label(self) -> &'static str { - match self { Self::Still => "still", Self::Idle => "idle", Self::Thinking => "thinking" } + match self { + Self::Still => "still", + Self::Idle => "idle", + Self::Listening => "listening", + Self::Thinking => "thinking", + Self::Waiting => "waiting", + Self::Paused => "paused", + } + } + + fn speed(self) -> f32 { + match self { + Self::Still | Self::Paused => 0.0, + Self::Idle => 0.45, + Self::Listening => 1.5, + Self::Thinking => 2.2, + Self::Waiting => 1.4, + } + } + + /// 输入框里的身份入口:减少动态冻结;输入时轻柔响应;其余时间待机呼吸。 + pub(super) fn composer(reduced: bool, typing: bool) -> Self { + if reduced { + Self::Still + } else if typing { + Self::Listening + } else { + Self::Idle + } } - fn speed(self) -> f32 { match self { Self::Still => 0.0, Self::Idle => 1.0, Self::Thinking => 2.2 } } } #[derive(Clone, Copy)] -pub(super) struct Animation { pub(super) phase: f32, pub(super) speed: f32, scale: f32 } +pub(super) struct Animation { + pub(super) phase: f32, + pub(super) speed: f32, + scale: f32, + /// 0 是正常亮度,1 是暂停定格后的暗度。 + dim: f32, + /// 正处在暂停的减速窗口内。 + settling: bool, +} #[derive(Clone)] struct PhaseClock { phase: f32, breath: f32, speed: f32, + energy: f32, + brake: Option<(f64, f32, f32)>, last: Option, } impl Default for PhaseClock { - fn default() -> Self { Self { phase: BASE_PHASE, breath: 0.0, speed: 0.0, last: None } } + fn default() -> Self { + Self { phase: BASE_PHASE, breath: 0.0, speed: 0.0, energy: 1.0, brake: None, last: None } + } } impl PhaseClock { fn update(&mut self, now: f64, motion: Motion, reduced: bool) -> Animation { + let target = motion.speed(); + let lit = f32::from(motion != Motion::Paused); if now.is_finite() { - if reduced { self.speed = 0.0; } - else if let Some(last) = self.last { - // The same clock survives focus, input growth and task state - // changes. Hidden time is not replayed when the orb reappears. - let elapsed = (now - last).clamp(0.0, 0.25); + if reduced { + // 减少动态:色场与呼吸一起冻结,保留当前画面。 + self.speed = 0.0; + self.energy = lit; + self.brake = None; + } else if let Some(last) = self.last { + // 同一个时钟贯穿聚焦、输入与任务状态变化;隐藏期间的时间不在重新出现时补播。 + let elapsed = (now - last).clamp(0.0, 0.25) as f32; let old_speed = self.speed; - self.speed += (motion.speed() - self.speed) * (1.0 - (-elapsed as f32 / 0.24).exp()); - if motion == Motion::Still && self.speed < 0.005 { self.speed = 0.0; } - self.phase = (self.phase + (elapsed / LOOP_SECONDS) as f32 * (old_speed + self.speed) * 0.5).rem_euclid(1.0); - self.breath = (self.breath + elapsed as f32 / 5.5 * self.speed.min(1.2)).rem_euclid(1.0); + if target > 0.0 { + self.brake = None; + let ease = 1.0 - (-elapsed / SPEED_TAU).exp(); + self.speed += (target - self.speed) * ease; + self.energy += (lit - self.energy) * ease; + } else if self.speed > 0.0 || (self.energy - lit).abs() > 0.002 || self.brake.is_some() { + // 暂停:在一个 190ms 窗口里平滑减速、变暗,窗口结束恰好静止,不拖泥带水。 + let (started, from_speed, from_energy) = *self.brake.get_or_insert((now, self.speed, self.energy)); + let progress = ((now - started) / STOP_SETTLE) as f32; + let eased = if progress >= 1.0 { + self.brake = None; + 1.0 + } else { + progress * progress * (3.0 - 2.0 * progress) + }; + self.speed = from_speed * (1.0 - eased); + self.energy = from_energy + (lit - from_energy) * eased; + } else { + // 本来就静止且亮度已到位:没有东西需要收敛,不安排任何重绘。 + self.speed = 0.0; + self.energy = lit; + } + self.phase = (self.phase + (elapsed / LOOP_SECONDS as f32) * (old_speed + self.speed) * 0.5).rem_euclid(1.0); + self.breath = (self.breath + elapsed / BREATH_SECONDS as f32 * self.speed.min(1.2)).rem_euclid(1.0); + } else if motion == Motion::Paused { + self.energy = lit; } self.last = Some(now); - } else { self.last = None; } - Animation { phase: self.phase, speed: self.speed, - scale: 1.0 + 0.035 * self.speed.min(1.0) * (1.0 - (self.breath * TAU).cos()) * 0.5 } - } -} - -fn field(x: f32, y: f32, phase: f32) -> [f32; 3] { - let mut color = BACKGROUND; - for (center, layer, low, high, speed) in LAYERS { - let angle = ((x - center[0]).atan2(center[1] - y) / TAU - phase * speed).rem_euclid(1.0); - let opacity = if angle < low { 1.0 - angle / low } else if angle > high { (angle - high) / (1.0 - high) } else { 0.0 }; - for (component, source) in color.iter_mut().zip(layer) { - *component += (source - *component) * opacity; + } else { + self.last = None; + } + Animation { + phase: self.phase, + speed: self.speed, + scale: 1.0 + 0.035 * self.speed.min(1.0) * (1.0 - (self.breath * TAU).cos()) * 0.5, + dim: 1.0 - self.energy, + settling: self.brake.is_some() || (target > 0.0 && (self.energy - lit).abs() > 0.002), } } - color } +/// 暖玉白基底的五个色阶:从左上高光处的暖白过渡到右下的冷灰青。 +const BASE_STOPS: [(f32, [f32; 3]); 5] = [ + (0.0, [251.0, 248.0, 241.0]), + (0.26, [241.0, 235.0, 224.0]), + (0.48, [228.0, 221.0, 207.0]), + (0.70, [207.0, 215.0, 210.0]), + (1.0, [185.0, 201.0, 197.0]), +]; +const BASE_REACH: f32 = 2.6; + +/// 四层液态微光:驻点、柔度 σ、颜色与强度(单位圆坐标,x 向右、y 向下)。 +/// 依次是琥珀(偏左)、冷月青(右上)、暖玉白(下)与月芯(中央);颜色取自语义 Token。 +const LAYERS: [(f32, f32, f32, Color32, f32); 4] = [ + (-0.80, -0.08, 0.42, AGENT_SEMANTIC.amber, 0.92), + (0.73, -0.41, 0.34, AGENT_SEMANTIC.jade, 0.94), + (0.02, 0.82, 0.22, AGENT_SEMANTIC.ivory, 0.95), + (0.04, 0.04, 0.11, AGENT_SEMANTIC.moon, 0.82), +]; + +fn channels(color: Color32) -> [f32; 3] { + [f32::from(color.r()), f32::from(color.g()), f32::from(color.b())] +} + +fn blend(color: &mut [f32; 3], source: [f32; 3], amount: f32) { + for (channel, value) in color.iter_mut().zip(source) { + *channel += (value - *channel) * amount; + } +} + +/// 第 `index` 层在相位 `angle`(弧度)时的中心与柔度倍率。只用整数倍谐波,整圈 20 秒首尾相接。 +fn layer_place(index: usize, angle: f32) -> (Vec2, f32) { + let (home_x, home_y, ..) = LAYERS[index]; + let (sin, cos) = angle.sin_cos(); + let (sin2, cos2) = (angle * 2.0).sin_cos(); + let (dx, dy, scale) = match index { + 0 => (0.33 * sin, 0.27 * cos2, 1.0 + 0.12 * sin2), + 1 => (-0.33 * cos, -0.27 * (angle * 2.0 + 1.0).sin(), 1.0 + 0.10 * cos2), + 2 => (0.20 * (angle + 2.0).sin(), 0.20 * cos2 - 0.13, 1.0), + _ => (0.17 * cos2, 0.17 * (angle * 3.0).sin(), 1.0), + }; + (vec2(home_x + dx, home_y + dy), scale) +} + +/// 单位圆上一点的颜色:暖玉白基底、四层液态微光、固定在左上的球面高光,以及下缘的冷青阴影。 fn orb_color(x: f32, y: f32, phase: f32) -> [u8; 3] { - // A small, symmetric field sampling kernel produces broad cloud-like - // transitions. The final specular highlight and shaded lower edge remain - // fixed in the sphere's coordinates while the colors move underneath. - let u = (x + 1.0) * 0.5; - let v = (y + 1.0) * 0.5; - let mut color = [0.0_f32; 3]; - for (dx, dy, weight) in [(0.0, 0.0, 0.28), (-0.04, 0.0, 0.18), (0.04, 0.0, 0.18), (0.0, -0.04, 0.18), (0.0, 0.04, 0.18)] { - for (sum, value) in color.iter_mut().zip(field(u + dx, v + dy, phase)) { *sum += value * weight; } - } - // A blue-cyan cloud stays visible through the top conic layers, matching - // the reference's cool right-hand half. It moves with the color field, - // while the glass highlight stays anchored to the sphere. - let rotation = (phase - BASE_PHASE) * TAU; - let cloud_x = 0.52 + 0.10 * rotation.sin(); - let cloud_y = -0.06 + 0.10 * rotation.cos(); - let cloud = (-((x - cloud_x).powi(2) + (y - cloud_y).powi(2)) / 0.36).exp() * 0.88; - for (component, source) in color.iter_mut().zip([47.0, 199.0, 246.0]) { *component += (source - *component) * cloud; } - let pink_x = -0.55 + 0.08 * rotation.cos(); - let pink_y = 0.45 + 0.08 * rotation.sin(); - let pink_cloud = (-((x - pink_x).powi(2) + (y - pink_y).powi(2)) / 0.30).exp() * 0.90; - for (component, source) in color.iter_mut().zip([232.0, 31.0, 220.0]) { *component += (source - *component) * pink_cloud; } - let light_cloud = (-((x + 0.18).powi(2) + (y + 0.12).powi(2)) / 0.14).exp() * 0.65; - for (component, source) in color.iter_mut().zip([245.0, 231.0, 255.0]) { *component += (source - *component) * light_cloud; } - let distance = ((x + 0.10).powi(2) + (y + 0.30).powi(2)).sqrt(); - let sheen = (1.0 - distance / 0.82).clamp(0.0, 1.0).powi(2) * 0.48; - let radius = (x * x + y * y).sqrt(); - let shade = (y.max(0.0) * 0.05 + (radius - 0.80).max(0.0) * 0.16).clamp(0.0, 0.12); - color.map(|value| (value * (1.0 - shade) * (1.0 - sheen) + 255.0 * sheen).round().clamp(0.0, 255.0) as u8) -} - -/// Builds a circle-clipped, self-contained mesh, with a transparent fringe for -/// antialiasing. `rect` is the entire layout allocation, not the orb's crop. -/// Returns nothing for invalid bounds. No document pixels or state are touched. -fn orb_mesh(rect: Rect, p: f32) -> Option { - if !rect.is_finite() || !rect.is_positive() { return None; } - let diameter = rect.width().min(rect.height()); - if diameter < 2.0 { return None; } - let center = rect.center(); - // Leave two logical points around a 20px orb in a 24px allocation. - let radius = (diameter * 0.5 - 2.0).max(0.5); - let rings = 16_u32; - let segments = 64_u32; - let mut mesh = Mesh::default(); - let center_color = orb_color(0.0, 0.0, p); - mesh.colored_vertex(center, Color32::from_rgb(center_color[0], center_color[1], center_color[2])); - for ring in 1..=rings { - let fraction = ring as f32 / rings as f32; - for segment in 0..segments { - let angle = TAU * segment as f32 / segments as f32; - let x = fraction * angle.cos(); - let y = fraction * angle.sin(); - let color = orb_color(x, y, p); - // A subpixel transparent edge keeps the circle crisp at 20px and - // avoids a dark outline on either native surface theme. - let opacity = if ring == rings { 0 } else { 255 }; - mesh.colored_vertex(center + egui::vec2(x * radius, y * radius), Color32::from_rgba_unmultiplied(color[0], color[1], color[2], opacity)); + let reach = ((x + 0.72) * (x + 0.72) + (y + 0.96) * (y + 0.96)).sqrt() / BASE_REACH; + let mut color = BASE_STOPS[4].1; + for pair in BASE_STOPS.windows(2).rev() { + if reach >= pair[0].0 { + color = pair[0].1; + blend(&mut color, pair[1].1, ((reach - pair[0].0) / (pair[1].0 - pair[0].0)).clamp(0.0, 1.0)); + break; } } - for segment in 0..segments { - let next = (segment + 1) % segments; - mesh.add_triangle(0, 1 + segment, 1 + next); + let angle = phase * TAU; + for (index, &(_, _, sigma, tint, strength)) in LAYERS.iter().enumerate() { + let (center, scale) = layer_place(index, angle); + let sigma = sigma * scale; + let (dx, dy) = (x - center.x, y - center.y); + blend(&mut color, channels(tint), strength * (-(dx * dx + dy * dy) / (2.0 * sigma * sigma)).exp()); } - for ring in 1..rings { - let outer = 1 + ring * segments; - let inner = outer - segments; - for segment in 0..segments { - let next = (segment + 1) % segments; + // 球面高光固定在球体左上,色层在它下面流动。 + let (dx, dy) = (x + 0.56, y + 0.76); + let (rx, ry) = (dx * 0.91 + dy * 0.41, dy * 0.91 - dx * 0.41); + blend(&mut color, [255.0; 3], 0.85 * (-(rx * rx / 0.23 + ry * ry / 0.08)).exp()); + // 上缘一线内光;下缘与轮廓内沉一层冷青阴影,球体才有体积。 + let top = ((-y - 0.80) / 0.20).clamp(0.0, 1.0); + blend(&mut color, [255.0; 3], 0.30 * top * top); + let shade = ((y - 0.30) / 0.70).clamp(0.0, 1.0); + let rim = ((x * x + y * y).sqrt() - 0.88).max(0.0) / 0.12; + blend(&mut color, [64.0, 82.0, 78.0], (0.36 * shade * shade + 0.10 * rim).clamp(0.0, 1.0)); + color.map(|value| value.round().clamp(0.0, 255.0) as u8) +} + +/// Builds a circle-clipped, self-contained mesh: a feathered halo first, then the pearl. `rect` is the +/// entire layout allocation, not the orb's crop. Returns nothing for invalid bounds. No document +/// pixels or state are touched. +fn orb_mesh(rect: Rect, p: f32) -> Option { + if !rect.is_finite() || !rect.is_positive() { + return None; + } + let diameter = rect.width().min(rect.height()); + if diameter < 2.0 { + return None; + } + let center = rect.center(); + let radius = (diameter * 0.5 - 2.0).max(0.5); + let mut mesh = Mesh::default(); + let halo = AGENT_SEMANTIC.glow_agent; + for (ring, (reach, level)) in HALO_REACH.into_iter().zip(HALO_LEVEL).enumerate() { + let tint = halo.gamma_multiply(HALO_ALPHA * level); + for segment in 0..SEGMENTS { + let angle = TAU * segment as f32 / SEGMENTS as f32; + mesh.colored_vertex(center + vec2(angle.cos(), angle.sin()) * radius * reach, tint); + } + if ring == 0 { + continue; + } + let (inner, outer) = ((ring - 1) as u32 * SEGMENTS, ring as u32 * SEGMENTS); + for segment in 0..SEGMENTS { + let next = (segment + 1) % SEGMENTS; + mesh.add_triangle(inner + segment, inner + next, outer + segment); + mesh.add_triangle(inner + next, outer + next, outer + segment); + } + } + let body = HALO_VERTEXES as u32; + let core = orb_color(0.0, 0.0, p); + mesh.colored_vertex(center, Color32::from_rgb(core[0], core[1], core[2])); + for ring in 1..=BODY_RINGS { + let fraction = ring as f32 / BODY_RINGS as f32; + for segment in 0..SEGMENTS { + let angle = TAU * segment as f32 / SEGMENTS as f32; + let color = orb_color(fraction * angle.cos(), fraction * angle.sin(), p); + // 最外一圈透明,留出亚像素抗锯齿边;20px 的球在任何宿主表面上都没有深色描边。 + let opacity = if ring == BODY_RINGS { 0 } else { 255 }; + mesh.colored_vertex( + center + vec2(angle.cos(), angle.sin()) * radius * fraction, + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], opacity), + ); + } + } + for segment in 0..SEGMENTS { + let next = (segment + 1) % SEGMENTS; + mesh.add_triangle(body, body + 1 + segment, body + 1 + next); + } + for ring in 1..BODY_RINGS { + let (inner, outer) = (body + 1 + (ring - 1) * SEGMENTS, body + 1 + ring * SEGMENTS); + for segment in 0..SEGMENTS { + let next = (segment + 1) % SEGMENTS; mesh.add_triangle(inner + segment, outer + segment, outer + next); mesh.add_triangle(inner + segment, outer + next, inner + next); } @@ -173,7 +316,7 @@ struct StaticMeshes { } impl StaticMeshes { - fn get(&mut self, size: egui::Vec2, phase: f32) -> Option { + fn get(&mut self, size: Vec2, phase: f32) -> Option { let key = (size.x.to_bits(), size.y.to_bits(), phase.to_bits()); if let Some(index) = self.meshes.iter().position(|(candidate, _)| *candidate == key) && let Some(item) = self.meshes.remove(index) @@ -182,15 +325,17 @@ impl StaticMeshes { self.meshes.push_back(item); return Some(mesh); } - let mesh = orb_mesh(Rect::from_min_size(egui::Pos2::ZERO, size), phase)?; - if self.meshes.len() >= STATIC_CACHE_LIMIT { self.meshes.pop_front(); } + let mesh = orb_mesh(Rect::from_min_size(pos2(0.0, 0.0), size), phase)?; + if self.meshes.len() >= STATIC_CACHE_LIMIT { + self.meshes.pop_front(); + } self.meshes.push_back((key, mesh.clone())); Some(mesh) } } // Only two color-field samples per moving orb. Interpolating their vertex -// colors every frame avoids recomputing every blurred conic layer at 60 Hz. +// colors every frame avoids recomputing every blurred light layer at 60 Hz. #[derive(Clone, Default)] struct MovingMeshes { samples: Option<(u16, Mesh, Mesh)> } @@ -199,10 +344,12 @@ impl MovingMeshes { let sample = phase.rem_euclid(1.0) * f32::from(MOTION_SAMPLES); let index = sample.floor() as u16; if self.samples.as_ref().is_none_or(|(old, _, _)| *old != index) { - let rect = Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::splat(48.0)); - self.samples = Some((index, + let rect = Rect::from_min_size(pos2(0.0, 0.0), Vec2::splat(CANONICAL)); + self.samples = Some(( + index, orb_mesh(rect, f32::from(index) / f32::from(MOTION_SAMPLES))?, - orb_mesh(rect, f32::from((index + 1) % MOTION_SAMPLES) / f32::from(MOTION_SAMPLES))?)); + orb_mesh(rect, f32::from((index + 1) % MOTION_SAMPLES) / f32::from(MOTION_SAMPLES))?, + )); } let (_, first, next) = self.samples.as_ref()?; let mut mesh = first.clone(); @@ -213,33 +360,42 @@ impl MovingMeshes { } } -/// Draw the decorative assistant identity. The live composer rests in a -/// gently flowing idle state; historical avatars remain still. Reduced motion -/// freezes both color and scale. Neither mode implies an audio capability. -/// The caller owns layout, accessibility labels, and the actual task state. +/// Draw the decorative assistant identity. The caller owns layout, accessibility labels, and the +/// actual task state. Hidden, clipped or minimized orbs draw nothing and schedule no repaint. pub(super) fn paint(ui: &Ui, id: Id, rect: Rect, motion: Motion, reduced: bool) -> Option { if !rect.is_finite() || !rect.is_positive() || !ui.is_rect_visible(rect) - || ui.input(|i| i.viewport().minimized == Some(true)) { return None; } + || ui.input(|i| i.viewport().minimized == Some(true)) + { + return None; + } let time = ui.input(|input| input.time); let animation = ui.data_mut(|data| data.get_temp_mut_or_default::(id.with("siri-orb-phase")).update(time, motion, reduced)); - let moving = !reduced && (motion != Motion::Still || animation.speed > 0.0); - // Size is only a transform. Never rebuild/switch tessellation when the - // composer's identity expands, and never cache a new mesh for every size. - let canonical = egui::Vec2::splat(48.0); - let mesh = ui.data_mut(|data| if moving { - data.get_temp_mut_or_default::(id.with("siri-orb-moving-mesh")).get(animation.phase) - } else { - data.get_temp_mut_or_default::(Id::unique("siri-orb-static-meshes")).get(canonical, animation.phase) + let moving = !reduced && animation.speed > 0.0; + let scale = rect.width().min(rect.height()) / CANONICAL * if reduced { 1.0 } else { animation.scale }; + let body_light = 1.0 - REST_DIM * animation.dim; + let halo = if motion == Motion::Still { 0.0 } else { 1.0 - 0.5 * animation.dim }; + let origin = pos2(CANONICAL * 0.5, CANONICAL * 0.5); + let mesh = ui.data_mut(|data| { + if moving { + data.get_temp_mut_or_default::(id.with("siri-orb-moving-mesh")).get(animation.phase) + } else { + data.get_temp_mut_or_default::(Id::unique("siri-orb-static-meshes")).get(Vec2::splat(CANONICAL), animation.phase) + } }).map(|mut mesh| { - let scale = rect.width().min(rect.height()) / 48.0 * if reduced { 1.0 } else { animation.scale }; - for vertex in &mut mesh.vertices { - vertex.pos = rect.center() + (vertex.pos - egui::pos2(24.0, 24.0)) * scale; + for (index, vertex) in mesh.vertices.iter_mut().enumerate() { + vertex.pos = rect.center() + (vertex.pos - origin) * scale; + vertex.color = vertex.color.gamma_multiply(if index < HALO_VERTEXES { halo } else { body_light }); } mesh }); if let Some(mesh) = mesh { - ui.painter().with_clip_rect(rect).add(Shape::mesh(mesh)); - if moving { ui.ctx().request_repaint_after(std::time::Duration::from_millis(if motion == Motion::Thinking { 16 } else { 32 })); } + // 柔光铺到球体之外,但不超出分配区域外 (柔光半径 − 分配半径)。 + let reach = (BODY_RADIUS * HALO_REACH[HALO_REACH.len() - 1] - CANONICAL * 0.5).max(0.0) * scale; + ui.painter().with_clip_rect(rect.expand(reach)).add(Shape::mesh(mesh)); + if !reduced && (animation.speed > 0.0 || animation.settling || motion.speed() > 0.0) { + let full = animation.settling || motion == Motion::Thinking || motion == Motion::Listening; + schedule(ui, rect, if full { Pace::Full } else { Pace::Idle }); + } } Some(animation) } @@ -247,38 +403,90 @@ pub(super) fn paint(ui: &Ui, id: Id, rect: Rect, motion: Motion, reduced: bool) #[cfg(test)] mod tests { use super::*; - use egui::{Pos2, pos2, vec2}; + use crate::jiansun::test_support::SettleUi; + use super::super::agent_motion::requested_delay; + use egui::{Context, Pos2, pos2, vec2}; + use std::time::Duration; #[test] - fn circular_mesh_stays_in_allocation_and_has_soft_transparent_boundary() { + fn the_pearl_stays_in_its_allocation_and_feathers_a_halo_around_it() { for size in [24.0, 120.0] { let rect = Rect::from_min_size(pos2(7.0, 11.0), vec2(size, size)); let mesh = orb_mesh(rect, BASE_PHASE).unwrap(); assert!(mesh.is_valid()); - assert!(mesh.vertices.iter().all(|v| rect.contains(v.pos))); - assert!(mesh.vertices.iter().any(|v| v.color.a() == 0)); - assert!(mesh.vertices.iter().any(|v| v.color.a() == 255)); - let c = mesh.vertices[0].color; + let body = &mesh.vertices[HALO_VERTEXES..]; + assert!(body.iter().all(|v| rect.contains(v.pos)), "the pearl itself never leaves its allocation"); + assert!(body.iter().any(|v| v.color.a() == 0), "transparent antialiased rim"); + assert!(body.iter().any(|v| v.color.a() == 255)); + assert_eq!(mesh.vertices[3 * SEGMENTS as usize].color.a(), 0, "the outermost halo ring is transparent"); + let inner = mesh.vertices[0].color.a(); + assert!(inner > 0 && inner < 90, "a restrained halo: alpha {inner}"); + let radius = (size * 0.5 - 2.0).max(0.5); + let span = vec2(radius * 2.0 * HALO_REACH[3] + 0.01, radius * 2.0 * HALO_REACH[3] + 0.01); + let reach = Rect::from_center_size(rect.center(), span); + assert!(mesh.vertices.iter().all(|v| reach.contains(v.pos))); + let c = mesh.vertices[HALO_VERTEXES].color; assert!(c.r() > 100 && c.g() > 100 && c.b() > 100, "the center must not be a dark icon"); } assert!(orb_mesh(Rect::NOTHING, BASE_PHASE).is_none()); } + #[test] + fn the_palette_reads_as_warm_ivory_with_amber_and_jade_layers() { + assert_eq!(LAYERS[0].3, AGENT_SEMANTIC.amber, "the orb's palette comes from the semantic tokens"); + assert_eq!(LAYERS[1].3, AGENT_SEMANTIC.jade); + assert_eq!(LAYERS[3].3, AGENT_SEMANTIC.moon); + for phase in [0.0, 0.25, 0.5, 0.75, BASE_PHASE] { + let angle = phase * TAU; + let (amber, _) = layer_place(0, angle); + let amber = orb_color(amber.x, amber.y, phase); + assert!(i32::from(amber[0]) > i32::from(amber[2]) + 40, "the left blob carries amber: {amber:?}"); + let (jade, _) = layer_place(1, angle); + let jade = orb_color(jade.x, jade.y, phase); + assert!(i32::from(jade[1]) > i32::from(jade[0]) + 20, "the upper-right blob carries the cool moon-teal: {jade:?}"); + let ivory = orb_color(0.02, 0.70, phase); + assert!(ivory.iter().all(|channel| *channel > 175), "the lower body stays warm ivory: {ivory:?}"); + let highlight = orb_color(-0.56, -0.76, phase); + assert!(highlight.iter().all(|channel| *channel > 215), "a fixed specular highlight sits top-left: {highlight:?}"); + let shade = orb_color(0.0, 0.96, phase); + assert!(i32::from(shade[0]) < 185 && shade[1] > shade[0], "the lower rim sinks into a cool shade: {shade:?}"); + } + let still = orb_color(0.2, 0.1, BASE_PHASE); + let moved = orb_color(0.2, 0.1, BASE_PHASE + 0.2); + assert_ne!(still, moved, "the liquid layers travel under the fixed highlight"); + } + + #[test] + fn motion_names_carry_their_own_pace_and_the_composer_uses_them() { + assert_eq!(Motion::Still.label(), "still"); + assert_eq!(Motion::Idle.label(), "idle"); + assert_eq!(Motion::Thinking.label(), "thinking"); + assert!(Motion::Still.speed() == 0.0 && Motion::Paused.speed() == 0.0); + assert!(Motion::Idle.speed() < Motion::Waiting.speed() && Motion::Waiting.speed() < Motion::Listening.speed()); + assert!(Motion::Listening.speed() < Motion::Thinking.speed(), "typing answers more softly than a running task"); + assert_eq!(Motion::composer(true, false), Motion::Still); + assert_eq!(Motion::composer(false, true), Motion::Listening, "typing is a soft response, not a sprint"); + assert_eq!(Motion::composer(false, false), Motion::Idle); + } + #[test] fn live_idle_flows_while_history_and_reduced_motion_stay_still() { let rect = Rect::from_min_size(Pos2::ZERO, vec2(24.0, 24.0)); let mut clock = PhaseClock::default(); assert_eq!(clock.update(0.0, Motion::Still, false).phase, clock.update(8.0, Motion::Still, false).phase); - let first = orb_mesh(rect, clock.update(8.1, Motion::Idle, false).phase).unwrap(); - let next = orb_mesh(rect, clock.update(8.2, Motion::Idle, false).phase).unwrap(); + clock.update(8.1, Motion::Idle, false); + let first = orb_mesh(rect, clock.update(8.5, Motion::Idle, false).phase).unwrap(); + let next = orb_mesh(rect, clock.update(8.9, Motion::Idle, false).phase).unwrap(); assert_ne!(first.vertices, next.vertices, "the visible mini composer must move without any model request"); - assert!(first.vertices.iter().zip(&next.vertices).all(|(a,b)| a.pos == b.pos), "motion must not shift the orb geometry"); + assert!(first.vertices.iter().zip(&next.vertices).all(|(a, b)| a.pos == b.pos), "motion must not shift the orb geometry"); assert_eq!(first.indices, next.indices); - let frozen = clock.update(8.3, Motion::Thinking, true); + let frozen = clock.update(8.95, Motion::Thinking, true); let later = clock.update(30.0, Motion::Idle, true); assert_eq!(frozen.phase, later.phase); assert_eq!(later.scale, 1.0); assert_eq!(later.speed, 0.0); + assert_eq!(later.dim, 0.0); + assert!(!later.settling); } #[test] @@ -295,11 +503,115 @@ mod tests { assert!((reappeared.phase - settled.phase).rem_euclid(1.0) < 0.028, "never replay hundreds of hidden seconds"); let old = clock.phase; assert_eq!(clock.update(f64::NAN, Motion::Idle, false).phase, old); - for index in 0..100 { clock.update(501.0 + f64::from(index) / 60.0, Motion::Still, false); } + for index in 0..100 { + clock.update(501.0 + f64::from(index) / 60.0, Motion::Still, false); + } assert_eq!(clock.speed, 0.0); assert_eq!(clock.update(510.0, Motion::Still, false).phase, clock.update(520.0, Motion::Still, false).phase); } + #[test] + fn pausing_decelerates_and_settles_exactly_within_the_stop_window() { + assert!((timing::STOP_SETTLE - 0.190).abs() < 1e-9, "the stop window is locked to 190ms"); + let mut clock = PhaseClock::default(); + clock.update(0.0, Motion::Thinking, false); + clock.update(0.5, Motion::Thinking, false); + let running = clock.update(1.0, Motion::Thinking, false); + assert!(running.speed > 1.5 && running.dim == 0.0 && !running.settling); + let phase_at_stop = running.phase; + let mut previous = running.speed; + let mut samples = Vec::new(); + for frame in 1..=14 { + let sample = clock.update(1.0 + frame as f64 / 120.0, Motion::Paused, false); + assert!(sample.speed <= previous + 1e-4, "speed only ever falls while braking"); + assert!(sample.phase >= phase_at_stop - 1e-6, "braking never rewinds the colour field"); + previous = sample.speed; + samples.push(sample); + } + // 减速从第一个暂停帧起算;窗口关闭后的那一帧恰好静止,之后的帧不再有变化。 + let settled = clock.update(1.0 + 1.0 / 120.0 + timing::STOP_SETTLE + 0.004, Motion::Paused, false); + assert_eq!(settled.speed, 0.0); + assert!(!settled.settling, "nothing is left to animate once the window closes"); + assert!((settled.dim - 1.0).abs() < 1e-6, "a paused orb rests a little dimmer"); + assert!(samples[13].speed < running.speed * 0.5, "by 117ms more than half of the speed is gone"); + assert!(samples[13].dim > 0.3 && samples[13].dim < 0.95, "dimming follows the same window"); + let still = clock.update(3.0, Motion::Paused, false); + assert_eq!((still.phase, still.speed, still.dim), (settled.phase, settled.speed, settled.dim)); + assert!(!still.settling, "an orb that is already at rest never opens a new window"); + // 停下之后再启动:从当前速度平滑回升,不跳变。 + let resumed = clock.update(3.02, Motion::Idle, false); + assert!(resumed.speed > 0.0 && resumed.speed < Motion::Idle.speed()); + assert!(resumed.dim < 1.0); + } + + #[test] + fn a_plain_stop_also_settles_in_the_window_without_dimming() { + let mut clock = PhaseClock::default(); + clock.update(0.0, Motion::Listening, false); + clock.update(0.6, Motion::Listening, false); + let mut last = clock.update(1.0, Motion::Still, false); + for frame in 1..=30 { + last = clock.update(1.0 + frame as f64 / 120.0, Motion::Still, false); + assert_eq!(last.dim, 0.0, "a resting avatar keeps its brightness"); + } + assert_eq!(last.speed, 0.0); + let bright = clock.update(1.0, Motion::Paused, true); + assert_eq!((bright.speed, bright.dim), (0.0, 1.0)); + assert!(!bright.settling, "reduced motion reaches the resting state immediately"); + } + + fn render(ctx: &Context, time: f64, motion: Motion, minimized: bool, visible: bool) -> (Option, Option) { + let mut input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0))), time: Some(time), ..Default::default() }; + if minimized { + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(true); + } + let (rect, mut animation) = (Rect::from_min_size(pos2(20.0, 20.0), vec2(34.0, 34.0)), None); + let output = ctx.settle_ui(input, |ui| { + ui.set_clip_rect(if visible { ui.clip_rect() } else { Rect::from_min_size(pos2(400.0, 400.0), vec2(10.0, 10.0)) }); + animation = paint(ui, Id::unique("orb"), rect, motion, false); + }); + (animation, requested_delay(&output)) + } + + #[test] + fn hidden_or_minimized_orbs_never_schedule_a_repaint() { + let ctx = Context::default(); + ctx.settle_start(); + let (animation, delay) = render(&ctx, 0.0, Motion::Idle, true, true); + assert!(animation.is_none() && delay.is_none(), "a minimized window gets zero repaints from the orb"); + let (animation, delay) = render(&ctx, 1.0, Motion::Thinking, false, false); + assert!(animation.is_none() && delay.is_none(), "a clipped-out orb gets zero repaints"); + let (animation, delay) = render(&ctx, 1.0, Motion::Thinking, false, true); + assert!(animation.is_some() && delay.is_some(), "the same orb repaints as soon as it is on screen"); + let (animation, delay) = render(&ctx, 2.0, Motion::Still, false, true); + assert!(animation.is_some() && delay.is_none(), "a still avatar never asks for another frame"); + } + + #[test] + fn running_and_typing_hold_the_full_frame_rate_while_pure_idle_downshifts_smoothly() { + let ctx = Context::default(); + ctx.settle_start(); + let full = timing::FRAME_FULL; + for motion in [Motion::Thinking, Motion::Listening] { + let (animation, delay) = render(&ctx, 10.0, motion, false, true); + assert!(animation.is_some()); + assert_eq!(delay, Some(full), "{motion:?} keeps 60fps"); + } + let mut idle_delays = Vec::new(); + for frame in 0..240 { + let (animation, delay) = render(&ctx, 10.0 + frame as f64 / 60.0, Motion::Idle, false, true); + assert!(animation.is_some()); + idle_delays.push(delay.unwrap_or(Duration::MAX)); + } + assert_eq!(idle_delays[0], full, "the idle orb still animates, at full rate right after the last full request"); + assert_eq!(idle_delays[89], full, "no downshift inside the 1.5s grace period"); + assert!(idle_delays.windows(2).all(|pair| pair[1] >= pair[0]), "the frame interval only ever grows while resting: no jumps back and forth"); + assert!(idle_delays[239] > full, "pure idling ends up below 60fps"); + assert!(idle_delays[239] <= timing::FRAME_IDLE + Duration::from_millis(1), "and never coarser than the idle tier"); + let (_, delay) = render(&ctx, 30.0, Motion::Listening, false, true); + assert_eq!(delay, Some(full), "any interaction snaps straight back to the full frame rate"); + } + #[test] fn moving_mesh_interpolates_between_two_samples_and_keeps_the_same_bounds() { let mut cache = MovingMeshes::default(); @@ -309,11 +621,13 @@ mod tests { assert_eq!(cache.samples.as_ref().unwrap().0, old_index, "subframe changes reuse the expensive color-field pair"); assert_ne!(first.vertices, next.vertices); assert_eq!(first.indices, next.indices); - assert!(first.vertices.iter().zip(&next.vertices).all(|(a,b)| a.pos == b.pos)); + assert!(first.vertices.iter().zip(&next.vertices).all(|(a, b)| a.pos == b.pos)); assert!(cache.get(0.999).unwrap().is_valid()); assert!(cache.get(0.001).unwrap().is_valid(), "wrap retains a valid sphere"); let start = std::time::Instant::now(); - for index in 0..120 { cache.get(0.30 + index as f32 / 600.0).unwrap(); } + for index in 0..120 { + cache.get(0.30 + index as f32 / 600.0).unwrap(); + } eprintln!("orb mesh CPU / 120 frames: {:?}; two retained samples, not a per-frame history cache", start.elapsed()); } @@ -325,7 +639,7 @@ mod tests { let second = cache.get(size, BASE_PHASE).unwrap(); assert_eq!(cache.meshes.len(), 1); assert_eq!(first.vertices, second.vertices); - assert!(first.vertices.iter().all(|vertex| Rect::from_min_size(Pos2::ZERO, size).contains(vertex.pos))); + assert!(first.vertices[HALO_VERTEXES..].iter().all(|vertex| Rect::from_min_size(Pos2::ZERO, size).contains(vertex.pos))); for index in 0..(STATIC_CACHE_LIMIT + 7) { cache.get(size, index as f32 / 100.0).unwrap(); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_cache.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_cache.rs new file mode 100644 index 00000000..fade2eed --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_cache.rs @@ -0,0 +1,272 @@ +//! 已定稿文字的排版缓存。 +//! +//! egui 自己只在同一帧内记住相同的 LayoutJob。历史回复每一帧仍然要重新解析 Markdown、重建 +//! LayoutJob 并整段哈希,带代码块的回复还要把那些行再深拷贝一遍。这里把已经定稿的排版结果按 +//! 内容键留住,重绘期直接复用,省掉这部分 CPU。字体定义、缩放或字体图集尺寸一变,缓存整体作废。 +use egui::{FontDefinitions, Galley, Id, Ui}; +use std::{collections::VecDeque, hash::{Hash, Hasher}, sync::Arc}; + +/// 每种缓存最多留住多少条。 +const ENTRY_LIMIT: usize = 32; +/// 每种缓存最多留住的字符总数,大约二十几 MB 的字形网格;更长的文本不缓存,照常排版。 +const CHAR_LIMIT: usize = 131_072; + +/// 决定排版的字体环境:任何一项变了,旧 Galley 里的字形坐标就不再可信。 +#[derive(Clone)] +pub(super) struct FontEnvironment { + definitions: FontDefinitions, + options: egui::epaint::text::TextOptions, + pixels_per_point: f32, + atlas: [usize; 2], +} + +pub(super) fn environment(ui: &Ui) -> FontEnvironment { + let pixels_per_point = ui.ctx().pixels_per_point(); + ui.fonts(|fonts| FontEnvironment { + definitions: fonts.definitions().clone(), + options: *fonts.options(), + pixels_per_point, + atlas: fonts.font_image_size(), + }) +} + +/// 字体定义只在字体数据被替换时才算变化;共享同一份字体数据的两个定义等价。 +pub(super) fn same_font_definitions(a: &FontDefinitions, b: &FontDefinitions) -> bool { + a.families == b.families + && a.font_data.len() == b.font_data.len() + && a.font_data.iter().all(|(name, font)| b.font_data.get(name).is_some_and(|other| Arc::ptr_eq(font, other))) +} + +impl FontEnvironment { + fn matches(&self, ui: &Ui) -> bool { + let pixels_per_point = ui.ctx().pixels_per_point(); + ui.fonts(|fonts| { + same_font_definitions(&self.definitions, fonts.definitions()) + && self.options == *fonts.options() + && self.pixels_per_point == pixels_per_point + && self.atlas == fonts.font_image_size() + }) + } +} + +/// 一组按内容键留住的排版结果,最近使用的排在最后。 +#[derive(Clone)] +pub(super) struct Settled { + environment: Option>, + entries: VecDeque<(Id, u64, usize, Arc)>, +} + +impl Default for Settled { + fn default() -> Self { + Self { environment: None, entries: VecDeque::new() } + } +} + +impl Settled { + /// 缓存此刻记住的字体环境。核对环境要读字体,而 `ui.fonts` 与 `ui.data` 取的是同一把锁, + /// 写锁里再读就是死锁,所以要先在锁外用 [`changed_environment`] 核对,再把结论交给 [`Self::get`]。 + pub(super) fn held(&self) -> Option> { + self.environment.clone() + } + + /// 命中条件:同一个归属、同一个内容键,并且字体环境没变。 + /// `fresh` 是进锁之前核对出的新字体环境,`None` 表示没变。 + pub(super) fn get(&mut self, owner: Id, key: u64, fresh: Option<&FontEnvironment>) -> Option> { + self.refresh(fresh); + let index = self.entries.iter().position(|(id, stamp, ..)| *id == owner && *stamp == key)?; + let entry = self.entries.remove(index)?; + let value = Arc::clone(&entry.3); + self.entries.push_back(entry); + Some(value) + } + + /// 留住一条排版结果;超过字符总量上限的长文本不留,照常排版。 + pub(super) fn insert(&mut self, owner: Id, key: u64, chars: usize, value: Arc) { + if chars > CHAR_LIMIT { + return; + } + self.entries.retain(|(id, stamp, ..)| !(*id == owner && *stamp == key)); + // 条数或字符总量超了,就从最久没用的那条开始让位;每让一条都重新量一遍。 + while self.entries.len() >= ENTRY_LIMIT + || self.entries.iter().map(|entry| entry.2).sum::() + chars > CHAR_LIMIT + { + if self.entries.pop_front().is_none() { + break; + } + } + self.entries.push_back((owner, key, chars, value)); + } + + /// 只留这一条:给同一时刻只有一条的"正在流式变化的回复"用。 + pub(super) fn replace(&mut self, owner: Id, key: u64, chars: usize, value: Arc) { + self.entries.clear(); + self.insert(owner, key, chars, value); + } + + /// 撤掉某个归属的全部排版结果(它定稿了,或换了作用域)。 + pub(super) fn retire(&mut self, owner: Id) { + self.entries.retain(|(id, ..)| *id != owner); + } + + #[cfg(test)] + pub(super) fn len(&self) -> usize { + self.entries.len() + } + + fn refresh(&mut self, fresh: Option<&FontEnvironment>) { + if let Some(fresh) = fresh { + self.entries.clear(); + self.environment = Some(Arc::new(fresh.clone())); + } + } +} + +/// 在 `ui.data` 的锁之外核对字体环境:`held` 是缓存记住的那份,返回此刻的环境,没变则为 `None`。 +/// 只能在锁外调用——`ui.fonts` 取的就是 `ui.data` 那把锁。环境没变时只是借用比较,不复制字体定义。 +pub(super) fn changed_environment(held: Option<&FontEnvironment>, ui: &Ui) -> Option { + held.is_none_or(|held| !held.matches(ui)).then(|| environment(ui)) +} + +/// 取出某个缓存记住的字体环境(一次读锁),交给 [`changed_environment`] 核对。 +fn held_environment(ui: &Ui, cache: Id) -> Option> { + ui.data(|data| data.get_temp::>(cache).and_then(|cache| cache.held())) +} + +/// 把决定排版的输入压成一个缓存键。 +pub(super) fn content_key(parts: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + parts.hash(&mut hasher); + hasher.finish() +} + +fn galleys() -> Id { + Id::unique("stitch-settled-galleys") +} + +/// 已定稿文本的 Galley:同一个 `owner`、`key` 与字体环境直接复用,不再排版。 +/// `key` 是调用方对"能唯一决定排版结果的输入"(文本、换行宽度、字号、颜色)用 `content_key` 算出的键, +/// `chars` 是文本长度,用来给缓存设总量上限。 +pub(super) fn settled_galley( + ui: &Ui, + owner: Id, + key: u64, + chars: usize, + layout: impl FnOnce(&mut egui::epaint::text::FontsView<'_>) -> Arc, +) -> Arc { + let fresh = changed_environment(held_environment::(ui, galleys()).as_deref(), ui); + if let Some(galley) = ui.data_mut(|data| data.get_temp_mut_or_default::>(galleys()).get(owner, key, fresh.as_ref())) { + return galley; + } + let galley = ui.fonts_mut(layout); + ui.data_mut(|data| { + data.get_temp_mut_or_default::>(galleys()).insert(owner, key, chars, Arc::clone(&galley)); + }); + galley +} + +/// 测试与诊断用:此刻缓存留住了多少条 Galley。 +#[cfg(test)] +pub(super) fn settled_galleys(ui: &Ui) -> usize { + ui.data(|data| data.get_temp::>(galleys()).map_or(0, |cache| cache.entries.len())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::jiansun::test_support::SettleUi; + use egui::{Color32, FontId}; + + fn laid_out(ui: &Ui, text: &str, width: f32) -> Arc { + let key = content_key((text, width.to_bits())); + settled_galley(ui, Id::unique("bubble"), key, text.chars().count(), |fonts| { + fonts.layout(text.to_owned(), FontId::proportional(14.0), Color32::WHITE, width) + }) + } + + #[test] + fn a_settled_text_is_laid_out_once_and_reused_until_its_content_changes() { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut seen = Vec::new(); + for (frame, width) in [240.0, 240.0, 260.0, 260.0, 240.0].into_iter().enumerate() { + let _ = ctx.settle_ui(egui::RawInput { time: Some(frame as f64 / 60.0), ..Default::default() }, |ui| { + seen.push(laid_out(ui, "settled text", width)); + if frame == 4 { + assert_eq!(settled_galleys(ui), 2, "both wrap widths are held"); + } + }); + } + assert!(Arc::ptr_eq(&seen[0], &seen[1]), "unchanged text reuses the same galley instead of laying it out again"); + assert!(!Arc::ptr_eq(&seen[1], &seen[2]), "a new wrap width is a new layout"); + assert!(Arc::ptr_eq(&seen[2], &seen[3])); + assert!(Arc::ptr_eq(&seen[4], &seen[0]), "the earlier layout is still held"); + } + + #[test] + fn a_changed_font_environment_invalidates_every_settled_galley() { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let mut seen = Vec::new(); + for (frame, scale) in [(0, 1.0), (1, 2.0), (2, 2.0)] { + ctx.set_pixels_per_point(scale); + let _ = ctx.settle_ui(egui::RawInput { time: Some(frame as f64 / 60.0), ..Default::default() }, |ui| { + seen.push(laid_out(ui, "environment", 240.0)); + }); + } + assert!(!Arc::ptr_eq(&seen[0], &seen[1]), "a new scale must not reuse a galley laid out for the old one"); + assert!(Arc::ptr_eq(&seen[1], &seen[2]), "the new scale settles on its own galley"); + assert_eq!(seen[0].pixels_per_point, 1.0); + assert_eq!(seen[2].pixels_per_point, 2.0); + } + + #[test] + fn the_settled_cache_is_bounded_by_entry_count_and_total_characters() { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { + for index in 0..(ENTRY_LIMIT * 3) { + let text = format!("entry {index}"); + settled_galley(ui, Id::unique(("bounded", index)), content_key(&text), text.chars().count(), |fonts| { + fonts.layout(text.clone(), FontId::proportional(14.0), Color32::WHITE, 120.0) + }); + } + assert_eq!(settled_galleys(ui), ENTRY_LIMIT); + let long = "x".repeat(CHAR_LIMIT / 4 + 1); + for index in 0..8 { + settled_galley(ui, Id::unique(("long", index)), content_key((&long, index)), long.chars().count(), |fonts| { + fonts.layout(long.clone(), FontId::proportional(14.0), Color32::WHITE, 120.0) + }); + } + ui.data(|data| { + let cache = data.get_temp::>(galleys()).unwrap(); + let held: usize = cache.entries.iter().map(|entry| entry.2).sum(); + assert!(cache.entries.len() <= 3, "entries over a quarter of the budget cannot pile up: {}", cache.entries.len()); + assert!(held <= CHAR_LIMIT, "total held characters stay within the budget: {held}"); + }); + }); + } + + #[test] + fn content_keys_separate_text_and_widths() { + assert_eq!(content_key(("a", 240_f32.to_bits())), content_key(("a", 240.0_f32.to_bits()))); + assert_ne!(content_key(("a", 240_f32.to_bits())), content_key(("a", 260.0_f32.to_bits()))); + assert_ne!(content_key("ab"), content_key("ba")); + assert_ne!(content_key(("ab", 1_u8)), content_key("ab")); + } + + #[test] + fn font_definitions_compare_shared_identity_and_detect_replaced_data() { + let ctx = egui::Context::default(); + let _ = ctx.settle_ui(Default::default(), |ui| { + ui.fonts(|view| { + let fonts = view.definitions(); + let same = fonts.clone(); + assert!(same_font_definitions(fonts, &same)); + let mut replaced = fonts.clone(); + let data = replaced.font_data.values_mut().next().expect("installed font"); + *data = Arc::new((**data).clone()); + assert!(!same_font_definitions(fonts, &replaced)); + }); + }); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs new file mode 100644 index 00000000..30834162 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs @@ -0,0 +1,533 @@ +//! 组件库补齐的缺失原语:语义化排版、统一提示条、停止钮、等待卡、自适应图片网格、列表行、 +//! 状态徽标与叠图说明。 +//! +//! 这些原语只接收类型化输入;颜色、字号、间距与动效时长全部取 Token,不读文案、不读 JSON。 +//! 第 1 批先在库内建好并通过单测;第 2、3 批把业务代码迁上来,在那之前它们还没有生产调用方。 +#![allow(dead_code, reason = "第 2、3 批把业务代码迁到这些原语上;库内先行并通过单测")] + +use super::agent_motion::{Pace, schedule}; +use super::stitch_state::{ToolStatus, Tone, WaitingState}; +use super::stitch_ui::{self as kit, material_frame, surface_frame, SurfaceRole}; +use crate::theme::agent_scale::motion as timing; +use crate::theme::agent_scale::{control, icon, radius, space, Type}; +use crate::theme::{Tokens, AGENT_SEMANTIC}; +use egui::{Margin, Rect, Response, RichText, Stroke, Ui, Vec2, vec2}; + +/// 语义化排版:字号取字体阶梯,颜色取色调。业务代码不再手写 `.size(..)` 和颜色。 +pub(super) fn label(ui: &mut Ui, text: impl Into, kind: Type, tone: Tone) -> Response { + let color = tone.color(&Tokens::get(ui.ctx()).agent()); + ui.add(egui::Label::new(text.into().color(color).size(kind.size())).wrap()) +} + +/// 元信息:时间线行旁的补充说明、字段说明。 +pub(super) fn caption(ui: &mut Ui, text: impl Into) -> Response { + label(ui, text, Type::Meta, Tone::Quiet) +} + +/// 页面标题。 +pub(super) fn page_title(ui: &mut Ui, text: &str) -> Response { + let color = Tokens::get(ui.ctx()).agent().text; + ui.add(egui::Label::new(RichText::new(text).font(Type::Display.semibold()).color(color)).wrap()) +} + +/// 分区标题。 +pub(super) fn section_heading(ui: &mut Ui, text: &str) -> Response { + let color = Tokens::get(ui.ctx()).agent().text; + ui.add(egui::Label::new(RichText::new(text).font(Type::Heading.semibold()).color(color)).wrap()) +} + +/// 空状态:一个图标、一句标题、几行说明,以及可选的下一步操作。不用文字项目符号,不堆解释墙。 +pub(super) fn empty_state(ui: &mut Ui, glyph: &str, title: &str, lines: &[&str], action: impl FnOnce(&mut Ui)) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + ui.vertical_centered(|ui| { + ui.add_space(space::XL); + ui.add(crate::icons::image(glyph, icon::LG * 2.0, t.text_dim)); + ui.add_space(space::SM); + section_heading(ui, title); + for line in lines { + caption(ui, *line); + } + ui.add_space(space::SM); + action(ui); + ui.add_space(space::XL); + }).response +} + +/// 统一提示条:一个图标、一句说明、右侧可选的一个操作。错误、待核查、保存完成都走这里, +/// 图标与色调由调用方按结构化状态给出。说明文字用正文色保持可读,状态靠图标与色调表达。 +pub(super) fn inline_notice(ui: &mut Ui, glyph: &str, tone: Tone, title: &str, action: impl FnOnce(&mut Ui)) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let frame = surface_frame(ui.ctx(), SurfaceRole::Task).stroke(Stroke::NONE).inner_margin(Margin::same(space::SM as i8)); + material_frame(ui, frame, |ui| { + // 行高交给内容:直接嵌一块不限定高度的横排区域,egui 会把它算作用掉了下面全部剩余高度。 + ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + action(ui); + let text_width = (ui.available_width() - icon::MD - space::SM).max(1.0); + let text = ui.painter().layout(title.to_owned(), Type::Body.font_id(), t.text, text_width); + ui.add(egui::Label::new(text)); + ui.add(crate::icons::image(glyph, icon::MD, tone.color(&t))) + }).inner + }).response +} + +/// 停止钮的尺寸档位:时间线里的 26pt,输入浮层工具栏里的 30pt。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum StopSize { Compact, Standard } + +/// 停止钮的提示文案只有这一处:停止的是本地自动操作,原请求始终保留。 +pub(super) const STOP_HINT: &str = "停止小壹,保留原请求"; + +pub(super) fn stop_button(ui: &mut Ui, size: StopSize) -> Response { + let side = match size { StopSize::Compact => control::COMPACT, StopSize::Standard => control::SEND }; + kit::icon_button(ui, "square", side, false, STOP_HINT) +} + +/// 生图等待卡的内容:图位此刻的状态、可选的真实耗时,以及是否提供停止钮。 +pub(super) struct WaitingCard<'a> { + pub state: WaitingState, + pub caption: Option<&'a str>, + pub elapsed: Option<&'a str>, + pub stop: bool, +} + +#[derive(Debug)] +pub(super) struct WaitingCardResponse { + pub rect: Rect, + pub stop: Option, + pub orb: Option, +} + +/// 生图等待卡:玻璃光涌打底,光球与状态左对齐成一行,右侧是停止钮,图位说明压在左下角的衬底上。 +/// 只表达真实的等待:排队时光球静止、光涌不起伏;最小化或不可见时不安排任何重绘。 +pub(super) fn waiting_card(ui: &mut Ui, id: egui::Id, size: Vec2, card: WaitingCard<'_>, reduced: bool) -> WaitingCardResponse { + let now = ui.input(|input| input.time); + let active = card.state.active(); + let elapsed = ui.data_mut(|data| { + // 光涌按参考短语的节奏起伏;从排队转为进行的那一刻重新起算。 + let clock = data.get_temp_mut_or_default::<(bool, f64)>(id.with("waiting-clock")); + if !active || clock.0 != active { + *clock = (active, now); + } + if active { (now - clock.1) * timing::GLOW_WAIT_SCALE } else { 0.0 } + }); + let activity = if reduced { 0.0 } else { + ui.ctx().animate_bool_with_time(id.with("working"), active, timing::MATERIAL as f32) + }; + let mut pulse = if reduced { super::glow_pill::Pulse::default() } else { super::glow_pill::waiting(elapsed) }; + pulse.surge *= activity; + pulse.warp *= activity; + let motion = match card.state { + WaitingState::Generating => super::siri_orb::Motion::Thinking, + WaitingState::Reviewing => super::siri_orb::Motion::Waiting, + WaitingState::Queued => super::siri_orb::Motion::Still, + }; + let mut stop = None; + let mut orb = None; + let surface = kit::surface(ui, SurfaceRole::Task, |ui| { + let background = super::agent_motion::reserve_background(ui); + ui.set_min_size(size); + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(control::DEFAULT, control::DEFAULT), egui::Sense::hover()); + orb = super::siri_orb::paint(ui, id.with("identity"), rect, motion, reduced).map(|_| rect); + label(ui, card.state.label(), Type::Title, if active { Tone::Active } else { Tone::Quiet }); + if let Some(elapsed) = card.elapsed { + caption(ui, elapsed); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if card.stop && active { + stop = Some(stop_button(ui, StopSize::Compact)); + } + }); + }); + background + }); + let rect = surface.response.rect; + if ui.is_rect_visible(rect) { + if let Some(caption) = card.caption { + on_image_caption(ui.painter(), rect, caption); + } + super::glow_pill::paint(ui, super::glow_pill::Surface { + id, rect, radius: radius::CHIP, time: if reduced { 2.4 } else { elapsed }, pulse, opacity: 1.0, + background: Some(surface.inner), text_range: None, flanks: 0.0, + }); + if active && !reduced { + schedule(ui, rect, Pace::Full); + } + } + WaitingCardResponse { rect, stop, orb } +} + +/// 自适应网格的列规则:每列最窄 `min_cell`、最宽 `max_cell`,最多 `most` 列。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct GridColumns { + pub min_cell: f32, + pub max_cell: f32, + pub most: usize, +} + +impl GridColumns { + /// 按可用宽度决定列数:至少一列,放得下才加列,不超过条目数。 + pub(super) fn count(self, available: f32, gap: f32, items: usize) -> usize { + let fit = ((available + gap) / (self.min_cell + gap)).floor().max(1.0) as usize; + fit.min(self.most).min(items.max(1)) + } + + /// 列数与每列宽度:先按最宽的单元格均分,放不下就减列。 + pub(super) fn measure(self, available: f32, gap: f32, items: usize) -> (usize, f32) { + let columns = self.count(available, gap, items); + let width = ((available - gap * columns.saturating_sub(1) as f32) / columns as f32).clamp(1.0, self.max_cell); + (columns, width) + } +} + +/// 自适应网格:按可用宽度决定列数,每格等宽,按行依次排入。代替业务代码里手排的裸网格。 +/// `cell` 对每个条目调用一次,返回值按条目顺序收集。 +pub(super) fn adaptive_grid( + ui: &mut Ui, + id: egui::Id, + columns: GridColumns, + gap: f32, + items: usize, + mut cell: impl FnMut(&mut Ui, usize) -> R, +) -> egui::InnerResponse> { + let (count, width) = columns.measure(ui.available_width().max(1.0), gap, items); + egui::Grid::new(id).num_columns(count).min_col_width(width).max_col_width(width).spacing(vec2(gap, gap)).show(ui, |ui| { + let mut results = Vec::with_capacity(items); + for index in 0..items { + results.push(cell(ui, index)); + if (index + 1) % count == 0 { + ui.end_row(); + } + } + results + }) +} + +/// 列表里的一行("最近的项目"这类):图标、文字、右侧补充信息。选中时压一层底。 +pub(super) fn list_row(ui: &mut Ui, id: egui::Id, glyph: &str, text: &str, meta: Option<&str>, selected: bool, reduced: bool) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let background = super::agent_motion::reserve_background(ui); + let tone = if selected { Tone::Active } else { Tone::Quiet }; + let row = super::agent_stream::event_row(ui, id, super::agent_stream::EventRow { + glyph, text, meta, tone: tone.into(), hint: None, action: super::agent_stream::RowAction::Click, + }, reduced); + if selected && ui.is_rect_visible(row.rect) { + ui.painter().set(background, egui::Shape::rect_filled(row.rect, radius::MENU, t.pressed)); + } + row +} + +/// 工具状态徽标:图标加规范文案,静态不动。进行中的旋转动画只在工具行里。 +pub(super) fn status_badge(ui: &mut Ui, status: ToolStatus) -> Response { + let t = Tokens::get(ui.ctx()).agent(); + let tint = status.tone().color(&t); + let text = status.label(); + let galley = ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), tint); + let size = vec2(space::SM + icon::SM + space::XS + galley.size().x + space::SM, galley.size().y.max(12.0) + space::SM); + let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); + if ui.is_rect_visible(rect) { + let painter = ui.painter_at(rect.intersect(ui.clip_rect())); + painter.rect_filled(rect, radius::CONTROL, t.field); + let color = match status { + ToolStatus::Completed => t.agent_semantic().success, + ToolStatus::Failed => t.danger, + ToolStatus::Stopped => t.warning, + _ => t.text_dim, + }; + crate::icons::image(status.glyph(), icon::SM, color) + .paint_at(ui, egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), vec2(icon::SM, icon::SM))); + painter.galley(egui::pos2(rect.left() + 24.0, rect.center().y - galley.size().y * 0.5), galley, tint); + } + response +} + +/// 叠在图片左下角的一行说明:白字压在黑色衬底上,不随宿主主题变化;一行放不下就截断。 +pub(super) fn on_image_caption(painter: &egui::Painter, rect: Rect, text: &str) { + if !(rect.width() >= 64.0 && rect.height() >= 34.0) { + return; + } + let mut job = egui::text::LayoutJob::simple_singleline(text.to_owned(), Type::Meta.font_id(), AGENT_SEMANTIC.on_image_text); + job.wrap.max_width = (rect.width() - 22.0).max(1.0); + job.wrap.max_rows = 1; + let caption = painter.layout_job(job); + let pos = rect.left_bottom() + vec2(10.0, -space::SM - caption.size().y); + painter.rect_filled(Rect::from_min_size(pos, caption.size()).expand2(vec2(5.0, 3.0)), radius::ROW, AGENT_SEMANTIC.on_image_scrim); + painter.galley(pos, caption, AGENT_SEMANTIC.on_image_text); +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::agent_motion::requested_delay; + use crate::jiansun::test_support::SettleUi; + use crate::theme::AGENT_SEMANTIC; + use egui::pos2; + + /// 渲染一帧并处理掉字体纹理增量:本文件的测试都从这里走,不把未应用的增量丢给 epaint。 + /// 画布比常见的测试窗口高:字号样张、各级标题和空状态竖着排下来,要给最下面的按钮留出位置。 + fn render(ctx: &egui::Context, time: f64, ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(420.0, 760.0))), + time: Some(time), + ..Default::default() + }; + let mut output = ctx.run_ui(input, ui); + output.textures_delta.clear(); + output + } + + fn texts(output: &egui::FullOutput) -> Vec { + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &output.shapes { + walk(&clipped.shape, &mut out); + } + out + } + + fn fonts(ctx: &egui::Context) { + crate::PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + } + + #[test] + fn typography_takes_its_size_from_the_ladder_and_its_color_from_the_tone() { + let ctx = egui::Context::default(); + fonts(&ctx); + let mut sizes = Vec::new(); + let mut colors = Vec::new(); + let output = render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + for kind in [Type::Caption, Type::Meta, Type::Title, Type::Body, Type::Subheading, Type::Heading, Type::TitleLg, Type::Display] { + let response = label(ui, "文字", kind, Tone::Quiet); + let _ = response.rect.height(); + sizes.push(kind.size()); + } + for tone in [Tone::Quiet, Tone::Active, Tone::Success, Tone::Verified, Tone::Progress, Tone::Warning, Tone::Failure, Tone::Unknown] { + colors.push(tone.color(&Tokens::get(ui.ctx()).agent())); + } + page_title(ui, "页面标题"); + section_heading(ui, "分区标题"); + caption(ui, "元信息"); + empty_state(ui, "image", "还没有图片", &["这一轮还没有返回的图"], |ui| { + kit::action_button(ui, "开始制作", kit::ButtonRole::Secondary, true); + }); + }); + }); + assert_eq!(sizes, [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0]); + let unique: std::collections::HashSet<_> = colors.iter().collect(); + assert!(unique.len() >= 6, "tones stay distinguishable: {colors:?}"); + let drawn = texts(&output); + for expected in ["文字", "页面标题", "分区标题", "元信息", "还没有图片", "这一轮还没有返回的图", "开始制作"] { + assert!(drawn.iter().any(|text| text == expected), "{expected} is drawn"); + } + let shown: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.galley.job.sections.first().map(|section| section.format.font_id.size)), + _ => None, + }).collect(); + assert!(shown.iter().flatten().any(|size| *size == 20.0) && shown.iter().flatten().any(|size| *size == 16.0), "titles use the ladder too"); + } + + #[test] + fn inline_notice_keeps_its_action_on_the_right_and_wraps_in_a_narrow_dock() { + let ctx = egui::Context::default(); + fonts(&ctx); + for width in [240.0, 480.0] { + let mut clicked = false; + let mut notice = Rect::NOTHING; + let mut button = Rect::NOTHING; + let output = render(&ctx, 0.0, |ui| { + ui.set_width(width); + kit::scope(ui, |ui| { + notice = inline_notice(ui, "triangle-alert", Tone::Failure, + "当前项目或画布已有变化,候选已保留,未覆盖你的编辑。请切回对应的项目后再继续。", |ui| { + let response = kit::action_button(ui, "查看详情", kit::ButtonRole::Quiet, true); + button = response.rect; + clicked = response.clicked(); + }).rect; + }); + }); + assert!(notice.width() <= width + 0.1, "{notice:?} within {width}"); + assert!(notice.height() < 160.0, "the notice uses content height: {notice:?}"); + assert!((button.right() - notice.right()).abs() < 12.0, "the action sits at the right edge: {button:?} in {notice:?}"); + assert!(!clicked); + let drawn = texts(&output); + assert!(drawn.iter().any(|text| text.starts_with("当前项目")), "the explanation is drawn: {drawn:?}"); + assert!(drawn.iter().any(|text| text == "查看详情")); + } + } + + #[test] + fn stop_button_has_one_hint_and_two_sizes() { + let ctx = egui::Context::default(); + fonts(&ctx); + let (mut compact, mut standard) = (Rect::NOTHING, Rect::NOTHING); + render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + compact = stop_button(ui, StopSize::Compact).rect; + standard = stop_button(ui, StopSize::Standard).rect; + }); + }); + assert_eq!((compact.width(), compact.height()), (control::COMPACT, control::COMPACT)); + assert_eq!((standard.width(), standard.height()), (control::SEND, control::SEND)); + assert!(STOP_HINT.contains("保留原请求") && !STOP_HINT.is_empty()); + } + + #[test] + fn waiting_card_flows_while_generating_rests_while_queued_and_offers_a_stop() { + let ctx = egui::Context::default(); + fonts(&ctx); + ctx.settle_start(); + let size = vec2(300.0, 120.0); + let frame = |_time: f64, state: WaitingState, stop: bool, ui: &mut Ui| { + kit::scope(ui, |ui| { + waiting_card(ui, egui::Id::unique("card"), size, WaitingCard { state, caption: Some("主图 1 · 主视觉"), elapsed: Some("耗时 3 秒"), stop }, false) + }).inner + }; + let mut stop_rect = Rect::NOTHING; + let output = render(&ctx, 0.0, |ui| { + let card = frame(0.0, WaitingState::Generating, true, ui); + assert!(card.orb.is_some() && card.stop.is_some()); + stop_rect = card.stop.map(|stop| stop.rect).unwrap_or(Rect::NOTHING); + }); + assert_eq!(requested_delay(&output), Some(timing::FRAME_FULL), "a generating card keeps the full frame rate"); + assert!(stop_rect.left() > 300.0 - 60.0 && stop_rect.width() == control::COMPACT, "the stop sits at the right edge"); + let drawn = texts(&output); + assert!(drawn.iter().any(|text| text == "生图中") && drawn.iter().any(|text| text == "主图 1 · 主视觉") && drawn.iter().any(|text| text == "耗时 3 秒")); + // 停止钮是真实控件:按下再松开才算一次点击,只按下不算。 + let mut clicked = false; + for pressed in [true, false] { + let mut input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(420.0, 420.0))), time: Some(1.0), ..Default::default() }; + input.events.push(egui::Event::PointerMoved(stop_rect.center())); + input.events.push(egui::Event::PointerButton { pos: stop_rect.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + let mut output = ctx.run_ui(input, |ui| { + clicked = frame(1.0, WaitingState::Generating, true, ui).stop.is_some_and(|stop| stop.clicked()); + }); + output.textures_delta.clear(); + assert_eq!(clicked, !pressed, "a click is a press followed by a release"); + } + let mut quiet = None; + let mut output = None; + // 从进行中切到排队后的 180ms 是淡出过渡,过渡结束后才完全静止。 + for time in [2.0, 2.1, 2.3] { + output = Some(render(&ctx, time, |ui| { + quiet = Some(frame(time, WaitingState::Queued, true, ui)); + })); + } + let quiet = quiet.expect("queued card renders"); + let output = output.expect("queued frames render"); + assert!(quiet.stop.is_none(), "a queued slot offers nothing to stop"); + assert!(requested_delay(&output).is_none(), "a settled queued card schedules no repaint"); + let mut reviewed = None; + let output = render(&ctx, 3.0, |ui| { + reviewed = Some(frame(3.0, WaitingState::Reviewing, false, ui)); + }); + let reviewed = reviewed.expect("reviewing card renders"); + assert!(reviewed.orb.is_some() && reviewed.stop.is_none()); + assert!(requested_delay(&output).is_some(), "reviewing keeps the light moving"); + let reduced = egui::Context::default(); + fonts(&reduced); + reduced.settle_start(); + let output = render(&reduced, 4.0, |ui| { + let card = kit::scope_with_motion(ui, true, |ui| { + waiting_card(ui, egui::Id::unique("card"), size, WaitingCard { state: WaitingState::Generating, caption: None, elapsed: None, stop: false }, true) + }).inner; + assert!(card.stop.is_none() && card.orb.is_some(), "reduced motion keeps the identity, drops the loop"); + }); + assert!(requested_delay(&output).is_none(), "reduced motion never schedules a repaint"); + } + + #[test] + fn adaptive_grid_adds_columns_only_when_they_fit() { + let columns = GridColumns { min_cell: 150.0, max_cell: 420.0, most: 2 }; + assert_eq!(columns.measure(520.0, 8.0, 2), (2, 256.0)); + assert_eq!(columns.count(520.0, 8.0, 3), 2, "never more columns than the rule allows"); + assert_eq!(columns.measure(200.0, 8.0, 2), (1, 200.0)); + assert_eq!(columns.measure(2000.0, 8.0, 2), (2, 420.0), "cells never exceed the maximum"); + assert_eq!(columns.measure(520.0, 8.0, 1), (1, 420.0)); + assert_eq!(columns.measure(520.0, 8.0, 0), (1, 420.0)); + let ctx = egui::Context::default(); + fonts(&ctx); + for (width, expected) in [(240.0, 1), (520.0, 2)] { + let mut rects = Vec::new(); + // egui 的网格按上一帧记下的列宽给下一列留位:宽度刚变的那一帧先立即重绘一次,下一帧才按新列宽排。 + for pass in 0..2 { + render(&ctx, pass as f64 / 60.0, |ui| { + ui.set_width(width); + kit::scope(ui, |ui| { + let grid = adaptive_grid(ui, egui::Id::unique("grid"), columns, space::SM, 5, |ui, _index| { + ui.allocate_exact_size(vec2(ui.available_width(), 60.0), egui::Sense::hover()).1.rect + }); + rects = grid.inner; + }); + }); + } + assert_eq!(rects.len(), 5); + let first_row: Vec<_> = rects.iter().take(expected).copied().collect(); + assert!(first_row.windows(2).all(|pair| (pair[0].top() - pair[1].top()).abs() < 0.01 && pair[0].right() < pair[1].left()), "{expected} columns share a row: {rects:?}"); + assert!(rects.get(expected).is_none_or(|rect| rect.top() > first_row[0].top()), "the rest wrap to the next row"); + } + } + + #[test] + fn list_row_and_status_badge_read_their_look_from_the_state() { + let ctx = egui::Context::default(); + fonts(&ctx); + let selected_fill = std::cell::Cell::new(0usize); + let output = render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + list_row(ui, egui::Id::unique("row"), "folder-open", "边几详情", Some("昨天"), false, true); + list_row(ui, egui::Id::unique("row"), "folder-open", "边几详情", Some("昨天"), true, true); + for status in [ToolStatus::Pending, ToolStatus::Started, ToolStatus::Completed, ToolStatus::Failed, ToolStatus::Stopped, ToolStatus::Unknown] { + status_badge(ui, status); + } + }); + }); + let t = Tokens::get(&ctx).agent(); + selected_fill.set(output.shapes.iter().filter(|shape| matches!(&shape.shape, + egui::Shape::Rect(rect) if rect.fill == t.pressed && rect.rect.height() == 24.0)).count()); + assert_eq!(selected_fill.get(), 1, "only the selected row is pressed"); + let drawn = texts(&output); + for expected in ["边几详情", "昨天", "等待", "进行中", "已完成", "失败", "已停止", "状态未知"] { + assert!(drawn.iter().filter(|text| *text == expected).count() >= if expected == "边几详情" { 2 } else { 1 }, "{expected} is drawn"); + } + let failed = output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "失败" => Some(text.galley.job.sections.first().map(|section| section.format.color)), + _ => None, + }).flatten().next(); + assert_eq!(failed, Some(t.danger), "a failed tool reads as a failure"); + } + + #[test] + fn on_image_caption_needs_room_and_never_follows_the_host_theme() { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProLight); + let output = render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + let painter = ui.painter().clone(); + on_image_caption(&painter, Rect::from_min_size(pos2(10.0, 10.0), vec2(40.0, 40.0)), "太小的图位"); + on_image_caption(&painter, Rect::from_min_size(pos2(10.0, 60.0), vec2(200.0, 120.0)), "主图 1 · 暖光客厅场景"); + }); + }); + let scrims: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) if rect.fill == AGENT_SEMANTIC.on_image_scrim => Some(rect.rect), + _ => None, + }).collect(); + assert_eq!(scrims.len(), 1, "a caption too small for its image draws nothing"); + assert_eq!(texts(&output), ["主图 1 · 暖光客厅场景"]); + let caption_text = output.shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "主图 1 · 暖光客厅场景" => Some(text.clone()), + _ => None, + }).unwrap(); + assert_eq!(caption_text.galley.job.sections.first().map(|section| section.format.color), Some(AGENT_SEMANTIC.on_image_text), "white on a scrim, even under a light host theme"); + let scrim = scrims[0]; + assert!(scrim.bottom() <= 180.0 && scrim.left() >= 10.0, "the caption sits in the bottom-left corner: {scrim:?}"); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs new file mode 100644 index 00000000..25ba06dd --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -0,0 +1,641 @@ +//! 结构化状态:时间流、目标面板与工具行只读这些枚举,不再拿中文文案判状态。 +//! +//! 每个类型自带规范文案、色调与图标,文案与色调从此只有一处定义。 +//! 线上字符串(工具状态、图位状态、错误原文)只在本文件的 `parse`、`infer`、`classify` 里解析一次; +//! 第 2 批把结构化字段补进回执后,这些解析函数随之删除。 +#![allow(dead_code, reason = "第 2 批把 agent_panel 迁到这些类型上;库内先行并通过单测")] + +use crate::theme::Tokens; +use egui::Color32; + +/// 统一色调:所有状态枚举都映射到它,再由它向 Token 取色。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Tone { Quiet, Active, Success, Verified, Progress, Warning, Failure, Unknown } + +impl Tone { + pub(super) fn color(self, t: &Tokens) -> Color32 { + let semantic = t.agent_semantic(); + match self { + Self::Quiet => t.text_dim, + Self::Active => t.text, + Self::Success => semantic.success, + Self::Verified => semantic.verified, + Self::Progress => semantic.progress, + Self::Warning | Self::Unknown => t.warning, + Self::Failure => t.danger, + } + } +} + +/// 严重级别:提示条用警告色还是危险色。待核查、未发出是告警,不是失败。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Severity { Warning, Failure } + +/// 工具调用的状态。线上是 pending / started / completed / failed / stopped,只在桥接处解析一次。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum ToolStatus { Pending, Started, Completed, Failed, Stopped, Unknown } + +impl ToolStatus { + pub(super) fn parse(wire: &str) -> Self { + match wire { + "pending" => Self::Pending, + "started" => Self::Started, + "completed" => Self::Completed, + "failed" => Self::Failed, + "stopped" => Self::Stopped, + _ => Self::Unknown, + } + } + + pub(super) fn label(self) -> &'static str { + match self { + Self::Pending => "等待", + Self::Started => "进行中", + Self::Completed => "已完成", + Self::Failed => "失败", + Self::Stopped => "已停止", + Self::Unknown => "状态未知", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Pending | Self::Started | Self::Completed => Tone::Quiet, + Self::Failed => Tone::Failure, + Self::Stopped | Self::Unknown => Tone::Unknown, + } + } + + pub(super) fn glyph(self) -> &'static str { + match self { + Self::Pending => "circle", + Self::Started => "circle-dashed", + Self::Completed => "check", + Self::Failed | Self::Stopped => "triangle-alert", + Self::Unknown => "circle", + } + } + + pub(super) fn running(self) -> bool { + matches!(self, Self::Pending | Self::Started) + } + + /// 只有带上游时长的终态才显示计时;本地不估算,也不暗示完成比例。 + pub(super) fn timed(self) -> bool { + matches!(self, Self::Completed | Self::Failed | Self::Stopped) + } +} + +/// 子代理所处的阶段。摘要行、计数行与展开列表的徽标都读它,三处不会各说各话。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum WorkerStage { Preparing, Generating, Reviewing, WaitingResult } + +impl WorkerStage { + pub(super) fn label(self) -> &'static str { + match self { + Self::Preparing => "准备", + Self::Generating => "生图", + Self::Reviewing => "验图", + Self::WaitingResult => "等结果", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Generating | Self::Reviewing => Tone::Active, + Self::Preparing | Self::WaitingResult => Tone::Quiet, + } + } + + /// 这一步是仍在等上游回执:徽标保持静止,不转圈。 + pub(super) fn waiting(self) -> bool { + self == Self::WaitingResult + } + + /// 桥接兜底:回执还没有结构化的阶段字段,按步骤文案的前缀推断一次。 + /// 这是全库唯一允许读中文步骤文案的地方,第 2 批补齐字段后删除。 + pub(super) fn infer(step: &str, review: bool, from_image: bool) -> Self { + if review || step.contains("验图") { + Self::Reviewing + } else if ["正在等待原", "正在核查原", "正在定位原"].iter().any(|prefix| step.starts_with(prefix)) { + Self::WaitingResult + } else if from_image || step.starts_with("正在生图") || step.starts_with("正在生成图片") { + Self::Generating + } else { + Self::Preparing + } + } +} + +/// 子代理的字母代号:A 到 D。摘要行、计数行与展开列表共用。 +pub(super) fn worker_letter(number: u64) -> Option { + (1..=4).contains(&number).then(|| char::from(b'A' + number as u8 - 1)) +} + +/// 时间流里的通知类别。失败、待核查、未执行不再共用一个图标只靠颜色区分。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum NoticeKind { Saved, Produced, Waiting, NeedsCheck, Failed, Info } + +impl NoticeKind { + pub(super) fn label(self) -> &'static str { + match self { + Self::Saved => "已保存", + Self::Produced => "已制作", + Self::Waiting => "等待中", + Self::NeedsCheck => "待核查", + Self::Failed => "失败", + Self::Info => "提示", + } + } + + pub(super) fn glyph(self) -> &'static str { + match self { + Self::Saved => "check", + Self::Produced => "sparkles", + Self::Waiting => "clock", + Self::NeedsCheck | Self::Info => "info", + Self::Failed => "triangle-alert", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Saved => Tone::Success, + Self::Produced | Self::Waiting => Tone::Active, + Self::NeedsCheck => Tone::Warning, + Self::Failed => Tone::Failure, + Self::Info => Tone::Quiet, + } + } +} + +/// 一轮任务的运行状态。停止、待核查、失败、完成各不相同,不会混成同一个空闲。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum RunState { Idle, Running, WaitingResume, WaitingUser, Stopped, NeedsCheck, Failed, Completed } + +impl RunState { + pub(super) fn label(self) -> &'static str { + match self { + Self::Idle => "空闲", + Self::Running => "进行中", + Self::WaitingResume => "等待恢复", + Self::WaitingUser => "等待你的回复", + Self::Stopped => "已停止", + Self::NeedsCheck => "待核查", + Self::Failed => "失败", + Self::Completed => "已完成", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Idle => Tone::Quiet, + Self::Running | Self::WaitingUser => Tone::Active, + Self::WaitingResume | Self::Stopped | Self::NeedsCheck => Tone::Warning, + Self::Failed => Tone::Failure, + Self::Completed => Tone::Success, + } + } + + pub(super) fn glyph(self) -> &'static str { + match self { + Self::Idle => "circle", + Self::Running => "circle-dashed", + Self::WaitingResume => "clock", + Self::WaitingUser => "pause", + Self::Stopped => "square", + Self::NeedsCheck => "info", + Self::Failed => "triangle-alert", + Self::Completed => "check", + } + } + + /// 本地还在推进:可以停止。 + pub(super) fn running(self) -> bool { + matches!(self, Self::Running | Self::WaitingResume) + } + + /// 任务没有结束,但卡在等待:运行中的动效要缓下来。 + pub(super) fn waiting(self) -> bool { + matches!(self, Self::WaitingResume | Self::WaitingUser) + } +} + +/// 错误类别:决定给用户的标题、原因、建议与严重级别。原文只进"技术详情"与兜底。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum ErrorCategory { + LibraryUnavailable, + ModelBusy, + UnknownResult, + ToolRejected, + ImageBudgetExceeded, + ImagePlacementExceeded, + ImageUnreadable, + ImageLinkedMissing, + CanvasOperationFailed, + Unknown, + /// 业务侧已经写成给人看的说明,原样显示。 + Business, +} + +impl ErrorCategory { + /// 桥接兜底:回执只有错误原文时分类一次。这是全库唯一允许读错误原文的地方。 + pub(super) fn classify(raw: &str) -> Self { + if raw.contains("素材库请求失败(HTTP 503)") { + return Self::LibraryUnavailable; + } + if raw.contains("模型服务暂时限流") { + return Self::ModelBusy; + } + if raw.contains("结果未知;不会重发") || raw.contains("原请求结果待核查") { + return Self::UnknownResult; + } + if raw == "客户端工具配置不匹配,本次未发送模型请求" { + return Self::ToolRejected; + } + let source_read = raw.starts_with("can't read smart source within the preview budget:"); + let budget = source_read + && (raw.contains("limit exceeded: canvas") || raw.contains("smart source canvas budget") || raw.contains("exceeds encoded byte budget")); + let placed = raw == "the placed smart source exceeds the preview budget" + || raw == "smart filter working area exceeds the preview budget"; + if source_read || placed || raw == "the source file is empty or exceeds the 20 MiB limit" { + return if budget { + Self::ImageBudgetExceeded + } else if placed { + Self::ImagePlacementExceeded + } else { + Self::ImageUnreadable + }; + } + if raw == "the linked file cannot be read" { + return Self::ImageLinkedMissing; + } + if raw.starts_with("本地SDK操作失败") { + return Self::CanvasOperationFailed; + } + if raw.is_ascii() { Self::Unknown } else { Self::Business } + } + + pub(super) fn title(self, raw: &str) -> &str { + match self { + Self::LibraryUnavailable => "素材库暂时不可用", + Self::ModelBusy => "模型服务暂时繁忙", + Self::UnknownResult => "上一条回复需核查", + Self::ToolRejected => "这次工具调用未发出", + Self::ImageBudgetExceeded | Self::ImagePlacementExceeded | Self::ImageUnreadable => "图片暂时无法读取", + Self::ImageLinkedMissing => "原图文件无法读取", + Self::CanvasOperationFailed => "画布操作没有完成", + Self::Unknown => "这次操作没有完成", + Self::Business => raw, + } + } + + pub(super) fn reason(self) -> Option<&'static str> { + match self { + Self::LibraryUnavailable => Some("客户端没有收到素材库的可用响应,暂时无法核对账户或读取项目资料。"), + Self::ModelBusy => Some("模型服务限制了这条回复,已完成的候选仍保留。"), + Self::UnknownResult => Some("小壹没有收到原请求的完整结果。"), + Self::ToolRejected => Some("客户端在发送前拒绝了此次工具声明。前面已完成的操作仍会保留。"), + Self::ImageBudgetExceeded => Some("客户端读取这张图片时,超出了预览的尺寸限制。"), + Self::ImagePlacementExceeded => Some("图片放置后的范围或效果超出了当前预览可处理的范围。"), + Self::ImageUnreadable => Some("客户端未能读取原图,当前操作没有完成。"), + Self::ImageLinkedMissing => Some("请确认关联的原图文件仍在原位置,并且可以正常打开。"), + Self::CanvasOperationFailed => Some("请先核对原请求的处理结果,再继续操作。"), + Self::Unknown => Some("请查看问题详情,确认原因后再继续。"), + Self::Business => None, + } + } + + pub(super) fn guidance(self) -> Option<&'static str> { + match self { + Self::LibraryUnavailable => Some("稍后重新核查。已经生成的候选仍保存在项目中。"), + Self::ModelBusy => Some("稍后可以继续发新消息。"), + Self::UnknownResult => Some("请选择核查结果。"), + Self::ToolRejected | Self::Unknown | Self::Business => None, + Self::ImageBudgetExceeded | Self::ImagePlacementExceeded | Self::ImageUnreadable => { + Some("如果已有生成结果,请先保留候选,不必重新生成;仍无法采纳时,可复制问题详情反馈。") + } + Self::ImageLinkedMissing => Some("保留当前项目;如果问题仍存在,可复制详情反馈。"), + Self::CanvasOperationFailed => Some("不要重复提交;可复制问题详情反馈。"), + } + } + + pub(super) fn image_unreadable(self) -> bool { + matches!(self, Self::ImageBudgetExceeded | Self::ImagePlacementExceeded | Self::ImageUnreadable | Self::ImageLinkedMissing) + } + + pub(super) fn severity(self) -> Severity { + match self { + Self::UnknownResult | Self::ToolRejected => Severity::Warning, + _ => Severity::Failure, + } + } +} + +/// 画布上一个字段(图位)的处理状态。文案只用于显示,判定一律读枚举。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum FieldState { Original, Processed, Changed } + +impl FieldState { + pub(super) fn label(self) -> &'static str { + match self { + Self::Original => "原稿 · 未处理", + Self::Processed => "小壹已处理", + Self::Changed => "已修改", + } + } + + /// 稳定的 ASCII 几何键,外部脚本按它取矩形,不再依赖中文文案。 + pub(super) fn key(self) -> &'static str { + match self { + Self::Original => "original", + Self::Processed => "processed", + Self::Changed => "changed", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Original => Tone::Quiet, + Self::Processed => Tone::Success, + Self::Changed => Tone::Active, + } + } +} + +/// 一个图位此刻的等待状态。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum WaitingState { Queued, Generating, Reviewing } + +impl WaitingState { + pub(super) fn label(self) -> &'static str { + match self { + Self::Queued => "排队中", + Self::Generating => "生图中", + Self::Reviewing => "验图中", + } + } + + pub(super) fn tone(self) -> Tone { + match self { + Self::Queued => Tone::Quiet, + Self::Generating | Self::Reviewing => Tone::Active, + } + } + + /// 还在本地或上游推进:光球流动、光涌起伏。 + pub(super) fn active(self) -> bool { + self != Self::Queued + } +} + +/// 工具的公开名称由本地给出,绝不来自它的参数、输出或错误原文;不认识的一律叫"工具"。 +pub(super) fn tool_label(tool: &str) -> &'static str { + match tool { + "context_read" => "读取项目规则", + "memory_set" => "记录事实", + "memory_search" => "检索历史", + "ask_user" => "等待用户回复", + "tool_develop" => "编写并测试工具", + "tool_run" => "运行工具", + "canvas_read" => "读取画布", + "canvas_template_image" => "读取模板原图", + "canvas_edit" => "更新图层", + "workflow_read" => "读取创作进度", + "workflow_navigate" => "切换创作视图", + "workflow_propose" => "添加待审核建议", + "workflow_execute" => "执行创作操作", + "native_catalog" => "查询原生命令", + "native_call" => "执行原生操作", + "native_reconcile" => "核查原生任务", + "canvas_preview" => "预览修改", + "copywriting_options" => "生成卖点选项", + "copywriting_fields" => "准备逐格文案", + "bash" => "运行项目终端", + "plan_production" => "读取制作进度", + "read_production_knowledge" => "读取制作规则", + "read_copy_fields" => "读取画布文字格", + "read_slot_images" => "查看图位图片", + "generate_slot_image" => "生成候选图片", + "delegate_image_slots" => "分派图片图位", + "check_image_slots" => "发起验图", + "record_screen_check" => "记录本屏复核", + "await_image_slots" => "等待子代理回执", + "review_image_slots" => "查看图位结果", + "adopt_production_image" => "回填候选图片", + "reconcile_image_slots" => "核查图片原请求", + "defer_production_output" => "保留当前草稿", + "read_output_screen" => "查看实际画布", + "finish_production" => "提交成品导出", + "canvas_candidate_image" => "核对图位和候选", + "produce_current_output" => "制作并验收当前输出", + "save_product_strategy" => "保存商品策划", + "review_product_strategy" => "核对卖点证据", + "plan_page_copy" => "规划整页卖点", + "write_copy_fields" => "填写画布文案", + "review_page_copy" => "复核整页文案", + "codemode" => "组合画布操作", + "tool_search" => "查找工具", + _ => "工具", + } +} + +/// 工具行的图标:按工具类别,不按状态。 +pub(super) fn tool_glyph(tool: &str) -> &'static str { + match tool { + "canvas_read" | "canvas_edit" | "native_call" => "layers", + "context_read" | "workflow_read" | "workflow_navigate" | "workflow_propose" => "folder-open", + "memory_search" | "native_catalog" | "tool_search" => "search", + "memory_set" => "type", + _ => "settings", + } +} + +/// 人读耗时读个大概:一秒以内给毫秒,十秒以内给一位小数,一分钟以内给整秒,再往上给分秒。 +pub(super) fn duration_text(ms: u64) -> String { + match ms { + 0..=999 => format!("耗时 {ms} 毫秒"), + 1000..=9_999 => format!("耗时 {}.{} 秒", (ms + 50) / 100 / 10, (ms + 50) / 100 % 10), + _ => { + let seconds = (ms + 500) / 1000; + if seconds < 60 { + format!("耗时 {seconds} 秒") + } else { + format!("耗时 {} 分 {:02} 秒", seconds / 60, seconds % 60) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tokens() -> Tokens { + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProLight); + Tokens::get(&ctx).agent() + } + + #[test] + fn every_state_glyph_exists_in_the_shared_icon_set() { + let mut glyphs = vec!["info", "clock", "check", "sparkles", "triangle-alert", "pause", "square", "settings"]; + glyphs.extend([ToolStatus::Pending, ToolStatus::Started, ToolStatus::Completed, ToolStatus::Failed, + ToolStatus::Stopped, ToolStatus::Unknown].map(ToolStatus::glyph)); + glyphs.extend([RunState::Idle, RunState::Running, RunState::WaitingResume, RunState::WaitingUser, RunState::Stopped, + RunState::NeedsCheck, RunState::Failed, RunState::Completed].map(RunState::glyph)); + glyphs.extend([NoticeKind::Saved, NoticeKind::Produced, NoticeKind::Waiting, NoticeKind::NeedsCheck, + NoticeKind::Failed, NoticeKind::Info].map(NoticeKind::glyph)); + for tool in ["canvas_read", "context_read", "memory_search", "memory_set", "something-new"] { + glyphs.push(tool_glyph(tool)); + } + for glyph in glyphs { + assert!(crate::icons::exists(glyph), "{glyph} must be a real icon, never a hand-drawn substitute"); + } + } + + #[test] + fn tones_resolve_to_tokens_in_every_host_theme() { + let mut t = tokens(); + let semantic = t.agent_semantic(); + assert_eq!(Tone::Quiet.color(&t), t.text_dim); + assert_eq!(Tone::Active.color(&t), t.text); + assert_eq!(Tone::Success.color(&t), semantic.success); + assert_eq!(Tone::Verified.color(&t), semantic.verified); + assert_eq!(Tone::Progress.color(&t), semantic.progress); + assert_eq!(Tone::Warning.color(&t), t.warning); + assert_eq!(Tone::Unknown.color(&t), t.warning); + assert_eq!(Tone::Failure.color(&t), t.danger); + // 宿主换成浅色主题,小壹的语义色一个字节都不变。 + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let dark = Tokens::get(&ctx).agent(); + for tone in [Tone::Quiet, Tone::Active, Tone::Success, Tone::Verified, Tone::Progress, Tone::Warning, Tone::Failure, Tone::Unknown] { + assert_eq!(tone.color(&t), tone.color(&dark)); + } + t.kind = crate::theme::ThemeKind::ProLight; + assert_eq!(t.agent().chrome, Color32::from_rgb(18, 19, 21), "agent surfaces never inherit a light host's chrome"); + assert_eq!(t.agent().scrim, t.agent_semantic().backdrop); + assert_eq!(t.agent().separator, t.agent().card_border); + assert_eq!(t.agent().row_selected, t.agent().pressed); + } + + #[test] + fn tool_status_parses_once_and_keeps_label_tone_and_glyph_together() { + let cases = [ + ("pending", ToolStatus::Pending, "等待", Tone::Quiet, "circle", true), + ("started", ToolStatus::Started, "进行中", Tone::Quiet, "circle-dashed", true), + ("completed", ToolStatus::Completed, "已完成", Tone::Quiet, "check", false), + ("failed", ToolStatus::Failed, "失败", Tone::Failure, "triangle-alert", false), + ("stopped", ToolStatus::Stopped, "已停止", Tone::Unknown, "triangle-alert", false), + ]; + for (wire, status, label, tone, glyph, running) in cases { + assert_eq!(ToolStatus::parse(wire), status); + assert_eq!(status.label(), label); + assert_eq!(status.tone(), tone); + assert_eq!(status.glyph(), glyph); + assert_eq!(status.running(), running); + } + for junk in ["", "done", "COMPLETED", "已完成", "completed "] { + assert_eq!(ToolStatus::parse(junk), ToolStatus::Unknown); + } + assert_eq!(ToolStatus::Unknown.label(), "状态未知"); + assert_eq!(ToolStatus::Unknown.tone(), Tone::Unknown); + } + + #[test] + fn worker_stage_infers_once_at_the_bridge_and_names_sub_agents_consistently() { + assert_eq!(WorkerStage::infer("正在生图", false, false), WorkerStage::Generating); + assert_eq!(WorkerStage::infer("", false, true), WorkerStage::Generating); + assert_eq!(WorkerStage::infer("正在等待原图片结果", false, false), WorkerStage::WaitingResult); + assert_eq!(WorkerStage::infer("正在核查原请求", false, false), WorkerStage::WaitingResult); + assert_eq!(WorkerStage::infer("正在定位原图", false, false), WorkerStage::WaitingResult); + assert_eq!(WorkerStage::infer("验图中", false, false), WorkerStage::Reviewing); + assert_eq!(WorkerStage::infer("任意步骤", true, false), WorkerStage::Reviewing); + assert_eq!(WorkerStage::infer("准备素材", false, false), WorkerStage::Preparing); + assert_eq!(WorkerStage::WaitingResult.label(), "等结果"); + assert!(WorkerStage::WaitingResult.waiting() && !WorkerStage::Generating.waiting()); + assert_eq!((1..=4).filter_map(worker_letter).collect::(), "ABCD"); + assert_eq!((worker_letter(0), worker_letter(5), worker_letter(99)), (None, None, None)); + } + + #[test] + fn notices_failures_and_checks_no_longer_share_one_glyph() { + assert_ne!(NoticeKind::Failed.glyph(), NoticeKind::NeedsCheck.glyph()); + assert_ne!(NoticeKind::Failed.tone(), NoticeKind::NeedsCheck.tone()); + assert_eq!(NoticeKind::Failed.tone(), Tone::Failure); + assert_eq!(NoticeKind::NeedsCheck.tone(), Tone::Warning); + assert_eq!(NoticeKind::Saved.tone(), Tone::Success); + assert_eq!(NoticeKind::Saved.glyph(), "check"); + } + + #[test] + fn run_states_stay_distinct_and_only_running_work_can_be_stopped() { + let all = [RunState::Idle, RunState::Running, RunState::WaitingResume, RunState::WaitingUser, RunState::Stopped, + RunState::NeedsCheck, RunState::Failed, RunState::Completed]; + let labels: std::collections::HashSet<_> = all.iter().map(|state| state.label()).collect(); + assert_eq!(labels.len(), all.len(), "no two run states read the same"); + assert!(RunState::Running.running() && RunState::WaitingResume.running()); + assert!(!RunState::Stopped.running() && !RunState::WaitingUser.running() && !RunState::Completed.running()); + assert!(RunState::Stopped.tone() != RunState::Completed.tone() && RunState::Failed.tone() != RunState::Stopped.tone()); + assert!(RunState::WaitingUser.waiting() && RunState::WaitingResume.waiting() && !RunState::Running.waiting()); + } + + #[test] + fn error_categories_carry_their_explanation_and_never_paint_a_check_as_a_failure() { + let image = "can't read smart source within the preview budget: pcraft: limit exceeded: canvas 1440x35827 exceeds 8192 pixels per side"; + assert_eq!(ErrorCategory::classify(image), ErrorCategory::ImageBudgetExceeded); + assert!(ErrorCategory::ImageBudgetExceeded.reason().is_some_and(|reason| reason.contains("尺寸限制"))); + assert!(ErrorCategory::ImageBudgetExceeded.image_unreadable()); + assert_eq!(ErrorCategory::classify("素材库请求失败(HTTP 503)"), ErrorCategory::LibraryUnavailable); + assert_eq!(ErrorCategory::classify("模型服务暂时限流"), ErrorCategory::ModelBusy); + assert_eq!(ErrorCategory::classify("结果未知;不会重发"), ErrorCategory::UnknownResult); + assert_eq!(ErrorCategory::classify("原请求结果待核查"), ErrorCategory::UnknownResult); + assert_eq!(ErrorCategory::classify("客户端工具配置不匹配,本次未发送模型请求"), ErrorCategory::ToolRejected); + assert_eq!(ErrorCategory::classify("the linked file cannot be read"), ErrorCategory::ImageLinkedMissing); + assert_eq!(ErrorCategory::classify("本地SDK操作失败:x"), ErrorCategory::CanvasOperationFailed); + assert_eq!(ErrorCategory::classify("engine operation failed"), ErrorCategory::Unknown); + // 待核查与未发出是告警,不是失败;其余仍是失败色。 + assert_eq!(ErrorCategory::UnknownResult.severity(), Severity::Warning); + assert_eq!(ErrorCategory::ToolRejected.severity(), Severity::Warning); + assert_eq!(ErrorCategory::Unknown.severity(), Severity::Failure); + assert_eq!(ErrorCategory::LibraryUnavailable.severity(), Severity::Failure); + let business = "图片已在本机采纳;记录尚未保存,请保留工程"; + assert_eq!(ErrorCategory::classify(business), ErrorCategory::Business); + assert_eq!(ErrorCategory::Business.title(business), business); + assert!(ErrorCategory::Business.reason().is_none() && ErrorCategory::Business.guidance().is_none()); + assert_eq!(ErrorCategory::classify("can't read smart source within the preview budget: invalid file"), ErrorCategory::ImageUnreadable); + assert!(!ErrorCategory::ImageUnreadable.reason().is_some_and(|reason| reason.contains("尺寸限制")), + "a decode error must not acquire an invented size diagnosis"); + assert_eq!(ErrorCategory::classify("the placed smart source exceeds the preview budget"), ErrorCategory::ImagePlacementExceeded); + for category in [ErrorCategory::ImageBudgetExceeded, ErrorCategory::ImagePlacementExceeded, ErrorCategory::ImageUnreadable] { + assert_eq!(category.title("x"), "图片暂时无法读取"); + } + } + + #[test] + fn field_states_have_stable_ascii_keys_and_readable_labels() { + assert_eq!(FieldState::Original.label(), "原稿 · 未处理"); + assert_eq!(FieldState::Processed.label(), "小壹已处理"); + assert_eq!(FieldState::Changed.label(), "已修改"); + assert_eq!([FieldState::Original.key(), FieldState::Processed.key(), FieldState::Changed.key()].join(","), "original,processed,changed"); + assert_ne!(FieldState::Original.tone(), FieldState::Processed.tone()); + assert_eq!(WaitingState::Queued.label(), "排队中"); + assert!(!WaitingState::Queued.active() && WaitingState::Generating.active() && WaitingState::Reviewing.active()); + } + + #[test] + fn tool_names_and_durations_come_from_one_table() { + assert_eq!(tool_label("canvas_read"), "读取画布"); + assert_eq!(tool_label("tool_search"), "查找工具"); + assert_eq!(tool_label("never-heard-of"), "工具"); + assert_eq!(tool_label(""), "工具"); + assert_eq!(tool_glyph("memory_set"), "type"); + assert_eq!(tool_glyph("workflow_propose"), "folder-open"); + assert_eq!(tool_glyph("anything-else"), "settings"); + assert_eq!(duration_text(27), "耗时 27 毫秒"); + assert_eq!(duration_text(1300), "耗时 1.3 秒"); + assert_eq!(duration_text(27_400), "耗时 27 秒"); + assert_eq!(duration_text(61_600), "耗时 1 分 02 秒"); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs new file mode 100644 index 00000000..e3b7e816 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -0,0 +1,1060 @@ +//! 时间流的 11 块语义外壳与目标驾驶舱(`GoalProgressPanel`)。 +//! +//! 每一块只接收类型化的展示模型,输出 `Response` 与几何;不读 JSON、不嗅探文案、不决定任务是否在跑。 +//! 第 2 批由归约层把消息归约成这些模型后直接调用;在那之前它们还没有生产调用方。 +#![allow(dead_code, reason = "第 2 批把 agent_panel 的时间流迁到这些外壳上;库内先行并通过单测")] + +use super::agent_stream::{self, Cell, EventRow, EventTone, RowAction, WORKER_BADGE_WIDTH}; +use super::stitch_kit::{adaptive_grid, caption, inline_notice, label, stop_button, GridColumns, StopSize}; +use super::stitch_state::{tool_glyph, worker_letter, ErrorCategory, NoticeKind, RunState, Tone, ToolStatus, WorkerStage}; +use super::stitch_ui::{self as kit}; +use crate::theme::agent_scale::{control, icon, space, Type}; +use crate::theme::{Tokens, AGENT_SEMANTIC}; +use egui::{Color32, Layout, Rect, Response, RichText, Stroke, Ui, vec2}; +use serde_json::{Value, json}; +use std::time::Duration; + +/// 1. 用户消息:气泡靠右;`reveal` 给出时从那一刻逐字扩散入场,气泡尺寸取全文排版、入场不变形。 +pub(super) fn user_message(ui: &mut Ui, text: &str, reveal: Option, reduced: bool) -> Rect { + kit::user_bubble_with_reveal(ui, text, reveal, reduced) +} + +/// 2. 本轮处理对象:一行安静的事件行;点击由调用方去定位目标。 +pub(super) fn target_row(ui: &mut Ui, id: egui::Id, text: &str, reduced: bool) -> Response { + agent_stream::event_row(ui, id, EventRow { + glyph: "square-dashed", text, meta: None, tone: EventTone::Quiet, hint: Some("定位本轮处理对象"), action: RowAction::Click, + }, reduced) +} + +/// 3. 思考状态。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ThinkingStatus { Active, Interrupted, Done } + +impl ThinkingStatus { + pub(super) fn label(self) -> &'static str { + match self { + Self::Active => "正在深度思考…", + Self::Interrupted => "思考已中断", + Self::Done => "已深度思考", + } + } + + fn tone(self) -> Tone { + match self { Self::Active => Tone::Active, Self::Interrupted | Self::Done => Tone::Quiet } + } +} + +pub(super) fn thinking_row(ui: &mut Ui, id: egui::Id, status: ThinkingStatus, usage_hint: Option<&str>, reduced: bool) -> Response { + agent_stream::event_row(ui, id, EventRow { + glyph: "sparkles", text: status.label(), meta: None, tone: status.tone().into(), hint: usage_hint, action: RowAction::None, + }, reduced) +} + +/// 4. 工具调用组:计数与成败由数字给出,标题文案由库里拼,调用方不必先拼文案再让库拆回去。 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ToolGroupHead { pub total: usize, pub completed: usize, pub failed: usize, pub active: bool } + +impl ToolGroupHead { + pub(super) fn tone(self) -> Tone { + if self.failed > 0 { Tone::Failure } else if self.active { Tone::Active } else { Tone::Quiet } + } + + pub(super) fn count(self) -> String { + let mut count = format!("{}/{} 已完成", self.completed, self.total); + if self.failed > 0 { + count.push_str(&format!(" · {} 项失败", self.failed)); + } + count + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ToolRow<'a> { pub tool: &'a str, pub name: &'a str, pub status: ToolStatus, pub elapsed: Option<&'a str> } + +pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, head: ToolGroupHead, rows: &[ToolRow<'_>], reduced: bool) { + kit::tool_group_head(ui, id, "工具调用", Some(&head.count()), head.tone(), reduced, |ui| { + for (index, row) in rows.iter().enumerate() { + kit::task_status_row(ui, id.with(("tool", index)), tool_glyph(row.tool), row.name, row.status, row.elapsed, reduced); + } + }); +} + +// 5. 过程说明沿用 `agent_stream::narration`。 + +/// 6. 通知:图标与色调取自 `NoticeKind`,失败、待核查、未执行不再共用一个图标。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Notice<'a> { pub kind: NoticeKind, pub text: &'a str, pub hint: Option<&'a str> } + +pub(super) fn notice_row(ui: &mut Ui, id: egui::Id, notice: Notice<'_>, reduced: bool) -> Response { + agent_stream::event_row(ui, id, EventRow { + glyph: notice.kind.glyph(), text: notice.text, meta: None, tone: notice.kind.tone().into(), + hint: notice.hint.or(Some(notice.text)), action: RowAction::None, + }, reduced) +} + +/// 7. 回复正文:沿用 `stitch_ui::streaming_reply`(含逐字扩散与流式光标)。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Reply<'a> { pub text: &'a str, pub streaming: bool } + +pub(super) fn reply(ui: &mut Ui, id: egui::Id, model: Reply<'_>, reduced: bool) -> Response { + kit::streaming_reply(ui, id, model.text, model.streaming, reduced) +} + +/// 8. 图片集:标题行加自适应网格;每一格画什么由调用方的闭包决定。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct ImageSet<'a> { + pub heading: &'a str, + pub meta: Option<&'a str>, + pub items: usize, + pub columns: GridColumns, +} + +impl<'a> ImageSet<'a> { + /// 对话里图片结果的列规则:侧栏放得下两张才分两列,单格最宽 420。 + pub(super) fn conversation(heading: &'a str, meta: Option<&'a str>, items: usize) -> Self { + Self { heading, meta, items, columns: GridColumns { min_cell: 146.0, max_cell: 420.0, most: 2 } } + } +} + +pub(super) fn image_set(ui: &mut Ui, id: egui::Id, set: ImageSet<'_>, reduced: bool, item: impl FnMut(&mut Ui, usize) -> R) -> (Response, Vec) { + let heading = agent_stream::event_row(ui, id.with("heading"), EventRow { + glyph: "image", text: set.heading, meta: set.meta, tone: EventTone::Quiet, hint: None, action: RowAction::None, + }, reduced); + ui.add_space(space::XS); + let grid = adaptive_grid(ui, id.with("result-grid"), set.columns, space::SM, set.items, item); + (heading, grid.inner) +} + +/// 9. 待审核卡。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ApprovalState<'a> { + Awaiting, + /// 暂时不能决定(例如目标已在别处改动);携带原因。 + Blocked(&'a str), + /// 已经选定:0 是执行,1 是放弃。 + Decided(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ApprovalCard<'a> { + pub title: &'a str, + pub scope: Option<&'a str>, + pub instruction: Option<&'a str>, + pub action: &'a str, + pub opt_out: &'a str, + pub state: ApprovalState<'a>, +} + +#[derive(Debug)] +pub(super) struct ApprovalResponse { pub action: Response, pub opt_out: Option } + +pub(super) fn approval_card(ui: &mut Ui, id: egui::Id, card: ApprovalCard<'_>, enabled: bool, reduced: bool) -> ApprovalResponse { + let mut answers = Vec::new(); + kit::surface(ui, kit::SurfaceRole::Task, |ui| { + label(ui, card.title, Type::Title, Tone::Active); + if let Some(scope) = card.scope { + caption(ui, scope); + } + if let Some(instruction) = card.instruction { + label(ui, instruction, Type::Body, Tone::Quiet); + } + let (resolved, live, blocked) = match card.state { + ApprovalState::Awaiting => (None, enabled, None), + ApprovalState::Blocked(reason) => (None, false, Some(reason)), + ApprovalState::Decided(choice) => (Some(choice), false, None), + }; + if let Some(reason) = blocked { + inline_notice(ui, "info", Tone::Warning, reason, |_| {}); + } + answers = kit::approval_options(ui, id, &[card.action, card.opt_out], resolved, live, reduced); + }); + let mut answers = answers.into_iter(); + ApprovalResponse { + action: answers.next().unwrap_or_else(|| ui.allocate_response(vec2(0.0, 0.0), egui::Sense::hover())), + opt_out: answers.next(), + } +} + +/// 10. 交互卡(问询、文案选项、逐格文案):外壳统一,内容由调用方的闭包给出。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct InteractionCard<'a> { pub title: &'a str, pub note: Option<&'a str> } + +pub(super) fn interaction_card(ui: &mut Ui, card: InteractionCard<'_>, body: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { + kit::surface(ui, kit::SurfaceRole::Task, |ui| { + label(ui, card.title, Type::Title, Tone::Active); + if let Some(note) = card.note { + caption(ui, note); + } + ui.add_space(space::XS); + body(ui) + }) +} + +/// 11. 停止态 / 结果反馈卡。停止、待核查、失败、完成、等待各自不同,不混成同一个空闲。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum RunOutcome<'a> { + Stopped { request_kept: bool }, + NeedsCheck, + Failed { category: ErrorCategory }, + Completed { summary: &'a str }, + Waiting { reason: &'a str }, +} + +impl RunOutcome<'_> { + pub(super) fn state(self) -> RunState { + match self { + Self::Stopped { .. } => RunState::Stopped, + Self::NeedsCheck => RunState::NeedsCheck, + Self::Failed { .. } => RunState::Failed, + Self::Completed { .. } => RunState::Completed, + Self::Waiting { .. } => RunState::WaitingResume, + } + } + + pub(super) fn title(self) -> String { + match self { + Self::Stopped { request_kept: true } => "已停止本地自动操作 · 原请求保留".to_owned(), + Self::Stopped { request_kept: false } => "已停止本地自动操作".to_owned(), + Self::NeedsCheck => "原请求结果待核查".to_owned(), + Self::Failed { category } => category.title("这次操作没有完成").to_owned(), + Self::Completed { summary } => format!("已完成 · {summary}"), + Self::Waiting { reason } => reason.to_owned(), + } + } + + /// 失败时给人看的原因,挂在悬停提示上。 + pub(super) fn detail(self) -> Option<&'static str> { + match self { Self::Failed { category } => category.reason(), _ => None } + } +} + +/// 运行结果的反馈卡。`action` 是可选的一个下一步,点击由 `on_action` 处理。 +pub(super) fn run_outcome_card(ui: &mut Ui, outcome: RunOutcome<'_>, action: Option<&str>, on_action: impl FnOnce(&mut Ui)) -> Response { + let state = outcome.state(); + let title = outcome.title(); + let response = inline_notice(ui, state.glyph(), state.tone(), &title, |ui| { + if let Some(action) = action + && kit::action_button(ui, action, kit::ButtonRole::Secondary, true).clicked() + { + on_action(ui); + } + }); + match outcome.detail() { + Some(detail) => response.on_hover_text(detail), + None => response, + } +} + +/// 输入框上方的建议行:只填入草稿,点击后的行为由调用方持有。 +pub(super) fn suggestion_row(ui: &mut Ui, items: &[(&str, &str)], enabled: bool, reduced: bool) -> Vec { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(space::SM, 0.0); + items.iter().map(|(glyph, text)| agent_stream::suggestion_chip(ui, glyph, text, enabled, reduced)).collect() + }).inner +} + +// --------------------------------------------------------------------------- +// 目标驾驶舱 +// --------------------------------------------------------------------------- + +/// 目标的预算口径。时间进度是主条的默认口径;回执只给 Token 用量时按 Token 计量。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum GoalBudget { + /// 时段:已用时长;上限未知时只报已用。 + Time { elapsed: Duration, limit: Option }, + /// Token:已用与上限。 + Tokens { used: u64, limit: Option }, +} + +impl GoalBudget { + /// 预算已用的比例;没有上限时未知。 + pub(super) fn fraction(self) -> Option { + match self { + Self::Time { elapsed, limit } => limit.filter(|limit| !limit.is_zero()).map(|limit| (elapsed.as_secs_f32() / limit.as_secs_f32()).min(1.0)), + Self::Tokens { used, limit } => limit.filter(|limit| *limit > 0).map(|limit| (used as f32 / limit as f32).min(1.0)), + } + } + + /// 时间口径下是否已经超过上限。 + pub(super) fn over(self) -> bool { + match self { + Self::Time { elapsed, limit: Some(limit) } => elapsed > limit, + _ => false, + } + } + + pub(super) fn kind(self) -> &'static str { + match self { Self::Time { .. } => "时间", Self::Tokens { .. } => "Token" } + } + + pub(super) fn text(self) -> String { + match self { + // 有上限时两边都报分钟:预算行要短,给步骤名让位置。 + Self::Time { elapsed, limit: Some(limit) } => format!("{}m / {}m", elapsed.as_secs() / 60, limit.as_secs() / 60), + Self::Time { elapsed, limit: None } => format!("已用 {}", coarse(elapsed)), + Self::Tokens { used, limit: Some(limit) } => format!("{} / {} tokens", compact(used), compact(limit)), + Self::Tokens { used, limit: None } => format!("{} tokens", compact(used)), + } + } +} + +/// 人读的时长:一分钟以内给秒,一小时以内给分,再往上给时分。 +pub(super) fn coarse(duration: Duration) -> String { + let seconds = duration.as_secs(); + if seconds < 60 { + format!("{seconds}s") + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else { + format!("{}h {:02}m", seconds / 3600, seconds % 3600 / 60) + } +} + +/// 人读的数量:850、1.2k、8k、120k。整千不带小数。 +pub(super) fn compact(count: u64) -> String { + if count < 1000 { + count.to_string() + } else if count % 1000 == 0 { + format!("{}k", count / 1000) + } else if count < 10_000 { + format!("{:.1}k", count as f64 / 1000.0) + } else { + format!("{}k", count / 1000) + } +} + +/// 流水线里一个阶段的状态。 +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) enum StagePhase { Done, Current(f32), #[default] Queued } + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum SlotState { Done, Generating, Reviewing, Failed, #[default] Queued } + +impl SlotState { + pub(super) fn label(self) -> &'static str { + match self { + Self::Done => "已完成", + Self::Generating => "生图中", + Self::Reviewing => "验图中", + Self::Failed => "没成功", + Self::Queued => "排队中", + } + } + + fn glyph(self) -> &'static str { + match self { + Self::Done => "check", + Self::Generating => "circle-dashed", + Self::Reviewing => "clock", + Self::Failed => "triangle-alert", + Self::Queued => "circle", + } + } + + fn tone(self) -> Tone { + match self { + Self::Done => Tone::Success, + Self::Generating | Self::Reviewing => Tone::Active, + Self::Failed => Tone::Warning, + Self::Queued => Tone::Quiet, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct GoalSlot<'a> { pub label: &'a str, pub state: SlotState } + +/// 路线图里的一个阶段:进度,可选的时段明细与 Token 明细,以及图位列表。 +#[derive(Clone, Debug, PartialEq)] +pub(super) struct GoalStage<'a> { + pub name: &'a str, + pub done: usize, + pub total: usize, + pub unit: &'a str, + /// 时段明细接口:本阶段已用的时间。 + pub elapsed: Option, + /// Token 明细接口:本阶段已用的 Token。 + pub tokens: Option, + pub slots: Vec>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct WorkerState<'a> { pub number: u64, pub stage: WorkerStage, pub slot: &'a str, pub active: bool } + +/// 目标驾驶舱:钉在时间流上方的一块面板。主条报状态、进度环、流水线、预算与停止钮; +/// 展开后是路线图抽屉(各阶段的进度、时段或 Token 明细、图位)与子代理列表。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct GoalProgressPanel<'a> { + pub title: &'a str, + pub state: RunState, + pub budget: GoalBudget, + /// 流水线:详情页 → 主图 → SKU 图,各自的状态。 + pub pipeline: &'a [(&'a str, StagePhase)], + pub image_cells: &'a [Cell], + pub copy_cells: &'a [Cell], + pub workers: &'a [WorkerState<'a>], + /// `Some` 时路线图抽屉展开。 + pub roadmap: Option<&'a [GoalStage<'a>]>, +} + +#[derive(Debug)] +pub(super) struct GoalProgressResponse { + /// 展开或收起路线图的按钮。 + pub toggle: Response, + /// 只有任务还在本地推进时才有。 + pub stop: Option, + pub rect: Rect, + pub title: Rect, + /// 两条进度格的几何,沿用外部脚本读取的键名。 + pub image_cells: Value, + pub copy_cells: Value, + /// 展开列表里每个子代理的几何:`worker / slot / step / active / rect / badge`。 + pub workers: Vec, + /// 主条上每个子代理角标的几何,字段同上。 + pub worker_badges: Vec, +} + +/// 窄栏阈值:不超过它时主条把整行让给步骤名,流水线收起。 +const NARROW: f32 = 260.0; +/// 路线图抽屉里每个阶段最多列出这么多图位,其余归成一句"还有 N 个图位"。 +const ROADMAP_SLOTS: usize = 6; +/// 路线图里阶段名那一列的宽度。 +const STAGE_NAME_WIDTH: f32 = 60.0; +/// 展开列表里一行子代理的高度。 +const WORKER_ROW: f32 = 36.0; +/// 主条上步骤名至少分到的宽度;分不到就把流水线与预算让出去。 +const MIN_TITLE: f32 = 96.0; + +/// 主条上的步骤名分到多宽、后面的流水线与预算还摆不摆得下。 +fn split_head(available: f32, reserve: f32) -> (f32, bool) { + let title = available - reserve - space::SM; + if title >= MIN_TITLE { (title, true) } else { (available, false) } +} + +/// 整个目标的完成度:进度格、流水线各算一份;什么都没给时未知。 +fn progress_of(panel: &GoalProgressPanel<'_>) -> (f32, Option) { + let (mut done, mut total) = (0.0_f32, 0.0_f32); + for cell in panel.image_cells.iter().chain(panel.copy_cells) { + total += 1.0; + if *cell != Cell::Empty { + done += 1.0; + } + } + for (_, phase) in panel.pipeline { + total += 1.0; + match phase { + StagePhase::Done => done += 1.0, + StagePhase::Current(fraction) => done += fraction.clamp(0.0, 1.0), + StagePhase::Queued => {} + } + } + (done, (total > 0.0).then_some(total)) +} + +fn state_title(state: RunState) -> &'static str { + match state { + RunState::Idle => "正在准备", + RunState::Running => "正在自动制作", + RunState::WaitingResume => "等待恢复", + RunState::WaitingUser => "等待你的回复", + RunState::Stopped => "已停止", + RunState::NeedsCheck => "待核查", + RunState::Failed => "失败", + RunState::Completed => "已完成", + } +} + +/// 主条的标题:状态加上流水线里正在推进的阶段与它的百分比。 +fn heading_of(panel: &GoalProgressPanel<'_>) -> String { + let current = panel.pipeline.iter().rev().find(|(_, phase)| matches!(phase, StagePhase::Current(_))); + match current { + Some((name, StagePhase::Current(fraction))) if *fraction > 0.0 => format!("{} · {name} {:.0}%", state_title(panel.state), fraction * 100.0), + Some((name, _)) => format!("{} · {name}", state_title(panel.state)), + None => format!("{} · {}", state_title(panel.state), panel.title), + } +} + +/// 流水线与预算文字占的宽度。 +fn pipeline_width(ui: &Ui, pipeline: &[(&str, StagePhase)]) -> f32 { + let measure = |text: &str| ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), Color32::WHITE).size().x; + pipeline.iter().map(|(name, phase)| { + measure(&match phase { StagePhase::Current(fraction) if *fraction > 0.0 => format!("{name} {:.0}%", fraction * 100.0), _ => name.to_string() }) + }).sum::() + (icon::SM + 2.0 * space::SM) * pipeline.len() as f32 + + (measure("→") + space::SM) * pipeline.len().saturating_sub(1) as f32 +} + +fn paint_ring(ui: &mut Ui, fraction: Option, fill: Color32) { + let t = Tokens::get(ui.ctx()).agent(); + let (rect, _) = ui.allocate_exact_size(vec2(icon::LG, icon::LG), egui::Sense::hover()); + let center = rect.center(); + let radius = icon::LG * 0.5 - 1.5; + let painter = ui.painter(); + painter.circle_stroke(center, radius, Stroke::new(1.5, t.card_border)); + if let Some(fraction) = fraction.filter(|fraction| *fraction > 0.0) { + let segments = ((48.0 * fraction).ceil() as usize).max(1); + let points = (0..=segments).map(|index| { + let angle = -std::f32::consts::FRAC_PI_2 + std::f32::consts::TAU * fraction * index as f32 / segments as f32; + center + vec2(angle.cos(), angle.sin()) * radius + }).collect(); + painter.add(egui::Shape::line(points, Stroke::new(1.5, fill))); + } +} + +/// 主条上每个子代理一枚字母角标加阶段名。窄栏时并成一句文字。 +fn worker_summary(ui: &mut Ui, id: egui::Id, workers: &[WorkerState<'_>], compact: bool, reduced: bool) -> Vec { + let mut geometry = Vec::new(); + ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing = vec2(space::XS, 0.0); + ui.add_space(space::XS); + for worker in workers { + let Some(letter) = worker_letter(worker.number) else { continue }; + let badge = if compact { + // 窄栏并成一句文字:角标就是这句话,几何照常登记。 + caption(ui, format!("{letter} {}", worker.stage.label())) + .on_hover_text(format!("子代理 {letter} · {} · {}", worker.stage.label(), worker.slot)) + } else { + let kind = if worker.active && !worker.stage.waiting() { kit::BadgeKind::Running } else { kit::BadgeKind::Neutral }; + kit::badge(ui, id.with(("stage", worker.number)), kind, &letter.to_string(), reduced).on_hover_text(worker.slot) + }; + geometry.push(json!({"worker": worker.number, "slot": worker.slot, "step": worker.stage.label(), "active": worker.active, + "review": false, "badge": super::agent_panel::rect_value(badge.rect), "rect": super::agent_panel::rect_value(badge.rect)})); + if !compact { + caption(ui, worker.stage.label()); + ui.add_space(space::SM); + } + } + }); + geometry +} + +/// 展开的子代理列表:窄栏一列,宽栏两列;字母角标定宽,所以等待与运行中的行对得齐。 +fn worker_list(ui: &mut Ui, workers: &[WorkerState<'_>], reduced: bool) -> Vec { + let t = Tokens::get(ui.ctx()).agent(); + let mut geometry = Vec::new(); + adaptive_grid(ui, ui.scope_id().with("production-workers"), GridColumns { min_cell: 181.0, max_cell: 600.0, most: 2 }, space::SM, workers.len(), |ui, index| { + let Some(worker) = workers.get(index) else { return }; + let Some(letter) = worker_letter(worker.number) else { return }; + let running = worker.active && !worker.stage.waiting(); + let kind = if running { kit::BadgeKind::Running } else { kit::BadgeKind::Neutral }; + let cell = ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), WORKER_ROW), Layout::left_to_right(egui::Align::Center), |ui| { + let badge = kit::badge_sized(ui, ui.scope_id().with("badge"), kind, &letter.to_string(), reduced, WORKER_BADGE_WIDTH); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.add(egui::Label::new(RichText::new(worker.slot).font(Type::Meta.font_id()).color(t.text)).truncate()).on_hover_text(worker.slot); + caption(ui, worker.stage.label()); + }); + badge + }); + geometry.push(json!({"worker": worker.number, "slot": worker.slot, "step": worker.stage.label(), "active": worker.active, + "review": false, "rect": super::agent_panel::rect_value(cell.response.rect), "badge": super::agent_panel::rect_value(cell.inner.rect)})); + }); + geometry +} + +/// 路线图抽屉:各阶段的进度条、时段或 Token 明细与图位。 +fn roadmap(ui: &mut Ui, id: egui::Id, stages: &[GoalStage<'_>], panel: &GoalProgressPanel<'_>) { + let t = Tokens::get(ui.ctx()).agent(); + let copy_done = panel.copy_cells.iter().filter(|cell| **cell != Cell::Empty).count(); + let image_done = panel.image_cells.iter().filter(|cell| **cell != Cell::Empty).count(); + caption(ui, format!("文案 {}/{} · 图片 {}/{}", copy_done, panel.copy_cells.len(), image_done, panel.image_cells.len())); + ui.add_space(space::XS); + for (index, stage) in stages.iter().enumerate() { + let fraction = if stage.total > 0 { stage.done as f32 / stage.total as f32 } else { 0.0 }; + ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + ui.add_sized(vec2(STAGE_NAME_WIDTH, agent_stream::ROW), + egui::Label::new(RichText::new(stage.name).font(Type::Meta.font_id()).color(t.text)).truncate()); + let count = format!("{}/{} {}", stage.done, stage.total, stage.unit); + let width = ui.painter().layout_no_wrap(count.clone(), Type::Meta.font_id(), t.text_dim).size().x; + let track = ui.available_width().max(1.0) - width - space::SM; + ui.allocate_ui_with_layout(vec2(track.max(1.0), agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + // 完成的阶段转成成功色;仍在推进的是进度的琥珀色。条本身不动,动的是数字。 + kit::progress_bar_tinted(ui, id.with(("stage", index)), stage.name, Some(fraction), true, + if stage.total > 0 && stage.done >= stage.total { AGENT_SEMANTIC.success } else { AGENT_SEMANTIC.progress }); + }); + caption(ui, count); + if let Some(elapsed) = stage.elapsed { + caption(ui, format!("· {}", coarse(elapsed))); + } + if let Some(tokens) = stage.tokens { + caption(ui, format!("· {} tokens", compact(tokens))); + } + }); + if stage.slots.is_empty() { + continue; + } + ui.allocate_ui_with_layout(vec2(ui.available_width().max(1.0), agent_stream::ROW), Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| { + ui.spacing_mut().item_spacing = vec2(space::MD, 0.0); + ui.add_space(STAGE_NAME_WIDTH + space::SM); + for slot in stage.slots.iter().take(ROADMAP_SLOTS) { + let (rect, _) = ui.allocate_exact_size(vec2(icon::SM, icon::SM), egui::Sense::hover()); + crate::icons::paint(ui, rect, slot.state.glyph(), icon::SM, slot.state.tone().color(&t)); + let text = if slot.state == SlotState::Done { slot.label.to_owned() } else { format!("{} · {}", slot.label, slot.state.label()) }; + ui.add(egui::Label::new(RichText::new(text).font(Type::Meta.font_id()).color(t.text_dim)).truncate()); + } + if stage.slots.len() > ROADMAP_SLOTS { + caption(ui, format!("还有 {} 个图位", stage.slots.len() - ROADMAP_SLOTS)); + } + }); + } +} + +/// 目标驾驶舱。`describe` 给出每个图片格的悬停说明。布局、展开状态与停止钮都在这里, +/// 业务层只负责把真实进度归约成 `GoalProgressPanel` 并登记返回的几何。 +pub(super) fn goal_progress_panel(ui: &mut Ui, id: egui::Id, panel: GoalProgressPanel<'_>, reduced: bool, describe: D) -> GoalProgressResponse +where + D: Fn(usize) -> String, +{ + let t = Tokens::get(ui.ctx()).agent(); + let mut expanded = ui.data(|data| data.get_temp::(id.with("expanded"))).unwrap_or(false); + let running = panel.state.running(); + let waiting = panel.state.waiting(); + let compact = ui.available_width() <= NARROW; + let heading = heading_of(&panel); + let (done, total) = progress_of(&panel); + let fraction = total.filter(|total| *total > 0.0).map(|total| done / total).or_else(|| panel.budget.fraction()); + let ring = if panel.state == RunState::Completed { AGENT_SEMANTIC.success } else if panel.budget.over() { t.warning } else { AGENT_SEMANTIC.progress }; + let show_cells = !panel.image_cells.is_empty() || !panel.copy_cells.is_empty(); + let (mut toggle, mut toggle_clicked, mut stop, mut title) = (None, false, None, Rect::NOTHING); + let (mut image_cells, mut copy_cells, mut workers, mut worker_badges) = (Value::Null, Value::Null, Vec::new(), Vec::new()); + let card = kit::surface(ui, kit::SurfaceRole::Task, |ui| { + let background = super::agent_motion::reserve_background(ui); + let width = ui.available_width(); + ui.set_min_width(width); + // 主条:左边状态与进度,右边展开钮与停止钮。 + ui.allocate_ui_with_layout(vec2(width, agent_stream::ROW), Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::XS; + if running { + stop = Some(stop_button(ui, StopSize::Compact)); + } + let button = kit::icon_button(ui, if expanded { "chevron-up" } else { "chevron-down" }, control::COMPACT, expanded, + if expanded { "收起制作详情" } else { "展开制作详情" }); + toggle_clicked = button.clicked(); + toggle = Some(button); + let rest = ui.available_width(); + ui.allocate_ui_with_layout(vec2(rest, agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::SM; + paint_ring(ui, fraction, ring); + // 窄栏把整行让给步骤名;宽栏里步骤名至少分到 MIN_TITLE,分不到就先让出流水线与预算。 + let available = ui.available_width().max(1.0); + let budget = panel.budget.text(); + let budget_width = ui.painter().layout_no_wrap(budget.clone(), Type::Meta.font_id(), t.text_dim).size().x; + let (title_with_pipeline, fits_pipeline) = split_head(available, budget_width + pipeline_width(ui, panel.pipeline)); + let (title_width, show_budget) = if compact { (available, false) } + else if fits_pipeline { (title_with_pipeline, true) } + else { split_head(available, budget_width) }; + title = ui.add_sized(vec2(title_width, agent_stream::ROW), + egui::Label::new(RichText::new(heading.as_str()).font(Type::Title.semibold()).color(if waiting { t.warning } else { t.text })).truncate()) + .on_hover_text(heading.as_str()).rect; + if !compact && fits_pipeline { + for (index, (name, phase)) in panel.pipeline.iter().enumerate() { + if index > 0 { + caption(ui, "→"); + } + let (dot, ink) = match phase { + StagePhase::Done => (AGENT_SEMANTIC.success, t.text_dim), + StagePhase::Current(_) => (AGENT_SEMANTIC.active, t.text), + StagePhase::Queued => (t.text_faint, t.text_faint), + }; + let (rect, _) = ui.allocate_exact_size(vec2(icon::SM, icon::SM), egui::Sense::hover()); + ui.painter().circle_filled(rect.center(), 2.5, dot); + let text = match phase { + StagePhase::Current(fraction) if *fraction > 0.0 => format!("{name} {:.0}%", fraction * 100.0), + _ => name.to_string(), + }; + ui.add(egui::Label::new(RichText::new(text).font(Type::Meta.font_id()).color(ink)).truncate()); + } + } + if show_budget { ui.add(egui::Label::new(RichText::new(budget).font(Type::Meta.font_id()).color(t.text_dim)).extend()); } + }); + }); + if show_cells { + if !panel.image_cells.is_empty() { + image_cells = agent_stream::cell_rail(ui, id.with("productionImageCells"), "图片", panel.image_cells, compact, &describe); + } + if !panel.copy_cells.is_empty() { + copy_cells = agent_stream::cell_rail(ui, id.with("productionCopyCells"), "文案", panel.copy_cells, compact, &describe); + } + } else if let Some(fraction) = fraction { + // 还没有逐格进度时先给一条总进度:颜色与进度格同一套。 + kit::progress_bar_tinted(ui, id, &heading, Some(fraction), reduced || waiting, AGENT_SEMANTIC.progress); + } + if !panel.workers.is_empty() { + ui.add_space(space::XS); + worker_badges = worker_summary(ui, id, panel.workers, compact, reduced); + } + // 路线图抽屉:展开与收起带实测高度的过渡,收起后不再占位。 + let open = expanded && (panel.roadmap.is_some() || !panel.workers.is_empty()); + let _drawer = kit::morph_surface(ui, id.with("roadmap"), open, reduced, |ui| { + ui.add_space(space::XS); + if let Some(stages) = panel.roadmap { + roadmap(ui, id, stages, &panel); + } + if !panel.workers.is_empty() { + workers = worker_list(ui, panel.workers, reduced); + } + }); + background + }); + if toggle_clicked { + expanded = !expanded; + } + ui.data_mut(|data| data.insert_temp(id.with("expanded"), expanded)); + // 任务推进中、还没有逐格进度时,光涌沿着主条流动:沿用任务卡的同一套玻璃光场。 + if running && !waiting && fraction.is_some() && !show_cells { + super::glow_pill::background(ui, id, card.response.rect, 7.0, 0.34, card.inner); + } + GoalProgressResponse { + toggle: toggle.unwrap_or_else(|| ui.allocate_response(vec2(0.0, 0.0), egui::Sense::hover())), + stop, + rect: card.response.rect, + title, + image_cells, + copy_cells, + workers, + worker_badges, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Pos2, pos2}; + + /// 测试画布:高度要容得下十一块竖着排下来的整轮对话。 + const CANVAS: egui::Vec2 = vec2(820.0, 1100.0); + + /// 渲染一帧并处理掉字体纹理增量:本文件的测试都从这里走,不把未应用的增量丢给 epaint。 + fn render(ctx: &egui::Context, time: f64, ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), CANVAS)), time: Some(time), ..Default::default() }; + let mut output = ctx.run_ui(input, ui); + output.textures_delta.clear(); + output + } + + /// 在 `at` 处按下再松开,各渲染一帧;返回松开那一帧的输出。 + fn click(ctx: &egui::Context, at: Pos2, time: f64, mut paint: impl FnMut(&mut Ui)) -> egui::FullOutput { + let mut last = None; + for pressed in [true, false] { + let mut input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), CANVAS)), time: Some(time + f64::from(u8::from(!pressed)) / 60.0), ..Default::default() }; + input.events.push(egui::Event::PointerMoved(at)); + input.events.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + let mut output = ctx.run_ui(input, |ui| paint(ui)); + output.textures_delta.clear(); + last = Some(output); + } + last.unwrap_or_else(|| panic!("click renders")) + } + + fn texts(output: &egui::FullOutput) -> Vec { + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &output.shapes { + walk(&clipped.shape, &mut out); + } + out + } + + fn meshes(output: &egui::FullOutput) -> usize { + fn count(shape: &egui::Shape) -> usize { + match shape { + egui::Shape::Mesh(_) => 1, + egui::Shape::Vec(shapes) => shapes.iter().map(count).sum(), + _ => 0, + } + } + output.shapes.iter().map(|clipped| count(&clipped.shape)).sum() + } + + fn fonts(ctx: &egui::Context) { + crate::PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + } + + #[test] + fn the_eleven_timeline_blocks_render_from_typed_models() { + let ctx = egui::Context::default(); + fonts(&ctx); + let id = egui::Id::unique("blocks"); + let mut target = Rect::NOTHING; + let mut head_rect = Rect::NOTHING; + let mut grid = Vec::new(); + let mut approval = None; + let mut interaction = 0; + let mut suggestions = Vec::new(); + let output = render(&ctx, 0.0, |ui| { + ui.set_width(400.0); + kit::scope(ui, |ui| { + user_message(ui, "给这款边几做一整套详情页", None, true); + target = target_row(ui, id.with("target"), "边几 · 胡桃木", true).rect; + thinking_row(ui, id.with("thinking"), ThinkingStatus::Done, Some("1200 tokens"), true); + // 这一组含失败项,默认折叠;测试里先展开,好核对各行。 + ui.data_mut(|data| data.insert_temp(id.with("tools").with("open"), true)); + tool_group(ui, id.with("tools"), ToolGroupHead { total: 3, completed: 2, failed: 1, active: false }, &[ + ToolRow { tool: "canvas_read", name: "读取画布", status: ToolStatus::Completed, elapsed: Some("耗时 0.4 秒") }, + ToolRow { tool: "generate_slot_image", name: "生成候选图片", status: ToolStatus::Failed, elapsed: None }, + ToolRow { tool: "check_image_slots", name: "发起验图", status: ToolStatus::Started, elapsed: None }, + ], true); + notice_row(ui, id.with("notice"), Notice { kind: NoticeKind::Failed, text: "主图 4 · 细节特写没生成出来", hint: None }, true); + notice_row(ui, id.with("check"), Notice { kind: NoticeKind::NeedsCheck, text: "有一条对话未确认结果", hint: None }, true); + reply(ui, id.with("reply"), Reply { text: "整套已经推进到主图这一步。", streaming: false }, true); + let (heading, cells) = image_set(ui, id.with("images"), ImageSet::conversation("生成图片", Some("2"), 2), true, |ui, _index| { + ui.allocate_exact_size(vec2(ui.available_width(), 90.0), egui::Sense::hover()).1.rect + }); + head_rect = heading.rect; + grid = cells; + approval = Some(approval_card(ui, id.with("approval"), ApprovalCard { + title: "添加待审核建议", scope: Some("详情页 · 第 3 屏"), instruction: Some("把材质一栏改成北美黑胡桃木实木框架。"), + action: "执行创作操作", opt_out: "先不用", state: ApprovalState::Awaiting, + }, true, true)); + let card = interaction_card(ui, InteractionCard { title: "选一个卖点方向", note: Some("只影响这一屏的文案") }, |ui| { + kit::action_button(ui, "实木框架", kit::ButtonRole::Secondary, true); + kit::action_button(ui, "不晃", kit::ButtonRole::Secondary, true); + 2 + }); + interaction = card.inner; + suggestions = suggestion_row(ui, &[("sparkles", "继续做剩下的 SKU 图"), ("sparkles", "先看详情页草稿")], true, true); + }); + }); + assert!(target.height() > 0.0 && head_rect.width() > 0.0); + assert_eq!(grid.len(), 2); + assert!(grid[0].top() == grid[1].top() && grid[0].right() < grid[1].left(), "two images share a row in a wide column: {grid:?}"); + let approval = approval.expect("approval card renders"); + assert!(approval.action.rect.width() > 0.0 && approval.opt_out.is_some(), "awaiting approval offers both answers"); + assert_eq!(interaction, 2); + assert_eq!(suggestions.len(), 2); + let drawn = texts(&output); + for expected in ["给这款边几做一整套详情页", "边几 · 胡桃木", "已深度思考", "工具调用", "2/3 已完成 · 1 项失败", "读取画布", "失败", + "主图 4 · 细节特写没生成出来", "有一条对话未确认结果", "整套已经推进到主图这一步。", "生成图片", "添加待审核建议", "执行创作操作", "先不用", "选一个卖点方向", "继续做剩下的 SKU 图"] { + assert!(drawn.iter().any(|text| text == expected), "{expected} is drawn: {drawn:?}"); + } + assert_eq!(meshes(&output), 0, "a settled turn draws no reveal glow"); + } + + #[test] + fn a_blocked_or_decided_approval_offers_no_live_answers() { + let ctx = egui::Context::default(); + fonts(&ctx); + let card = |state| ApprovalCard { title: "添加待审核建议", scope: None, instruction: None, action: "执行创作操作", opt_out: "先不用", state }; + let mut blocked = None; + let mut decided = None; + let output = render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + blocked = Some(approval_card(ui, egui::Id::unique("blocked"), card(ApprovalState::Blocked("目标已在画布上改动")), true, true)); + decided = Some(approval_card(ui, egui::Id::unique("decided"), card(ApprovalState::Decided(0)), true, true)); + }); + }); + assert!(blocked.is_some_and(|response| response.opt_out.is_some())); + assert!(decided.is_some_and(|response| response.opt_out.is_none()), "a decided card keeps only the record line"); + let drawn = texts(&output); + assert!(drawn.iter().any(|text| text == "目标已在画布上改动"), "the reason is shown"); + } + + #[test] + fn run_outcomes_never_read_the_same_and_only_failures_carry_a_reason() { + let all = [ + RunOutcome::Stopped { request_kept: true }, RunOutcome::Stopped { request_kept: false }, RunOutcome::NeedsCheck, + RunOutcome::Failed { category: ErrorCategory::CanvasOperationFailed }, + RunOutcome::Completed { summary: "文案 20/20 · 主图 5/5" }, RunOutcome::Waiting { reason: "正在等子代理回执" }, + ]; + let titles: std::collections::HashSet<_> = all.iter().map(|outcome| outcome.title()).collect(); + assert_eq!(titles.len(), all.len(), "no two outcomes read the same"); + assert_eq!(all[0].state(), RunState::Stopped); + assert_eq!(all[0].state().tone(), Tone::Warning, "a stop is not a failure"); + assert_eq!(all[3].state(), RunState::Failed); + assert!(all[..4].iter().all(|outcome| !outcome.state().running())); + assert!(all[3].detail().is_some() && all[..5].iter().enumerate().all(|(index, outcome)| index == 3 || outcome.detail().is_none())); + let ctx = egui::Context::default(); + fonts(&ctx); + let mut acted = false; + let output = render(&ctx, 0.0, |ui| { + kit::scope(ui, |ui| { + run_outcome_card(ui, RunOutcome::Stopped { request_kept: true }, Some("核查结果"), |_| acted = true); + run_outcome_card(ui, RunOutcome::Failed { category: ErrorCategory::ImageUnreadable }, None, |_| acted = true); + }); + }); + assert!(!acted); + let drawn = texts(&output); + assert!(drawn.iter().any(|text| text == "已停止本地自动操作 · 原请求保留") && drawn.iter().any(|text| text == "核查结果")); + assert!(drawn.iter().any(|text| text == "图片暂时无法读取"), "a failure keeps its category's plain-language title: {drawn:?}"); + } + + #[test] + fn budgets_read_as_time_or_tokens_and_coarse_durations_stay_short() { + let time = GoalBudget::Time { elapsed: Duration::from_secs(240), limit: Some(Duration::from_secs(5400)) }; + assert_eq!(time.text(), "4m / 90m"); + assert!((time.fraction().unwrap_or(0.0) - 240.0 / 5400.0).abs() < 1e-6); + assert!(!time.over()); + assert_eq!(GoalBudget::Time { elapsed: Duration::from_secs(7500), limit: None }.text(), "已用 2h 05m"); + assert!(GoalBudget::Time { elapsed: Duration::from_secs(61), limit: Some(Duration::from_secs(60)) }.over()); + assert!(GoalBudget::Time { elapsed: Duration::from_secs(5), limit: None }.fraction().is_none()); + assert_eq!(GoalBudget::Tokens { used: 1200, limit: Some(8000) }.text(), "1.2k / 8k tokens"); + assert_eq!(GoalBudget::Tokens { used: 850, limit: None }.text(), "850 tokens"); + assert!((GoalBudget::Tokens { used: 4000, limit: Some(8000) }.fraction().unwrap_or(0.0) - 0.5).abs() < 1e-6); + assert_eq!((time.kind(), GoalBudget::Tokens { used: 0, limit: None }.kind()), ("时间", "Token")); + assert_eq!(coarse(Duration::from_secs(45)), "45s"); + assert_eq!(coarse(Duration::from_secs(0)), "0s"); + assert_eq!((compact(850).as_str(), compact(1200).as_str(), compact(120_000).as_str()), ("850", "1.2k", "120k")); + let (wide, tail) = split_head(400.0, 150.0); + assert!(tail && (wide - (400.0 - 150.0 - space::SM)).abs() < 1e-3); + let (narrow, tail) = split_head(200.0, 150.0); + assert!(!tail && narrow == 200.0, "the step name wins over the pipeline in a narrow dock"); + } + + struct Fixture { + pipeline: Vec<(&'static str, StagePhase)>, + image_cells: Vec, + copy_cells: Vec, + workers: Vec>, + stages: Vec>, + } + + fn fixture() -> Fixture { + let pipeline = vec![("详情页", StagePhase::Done), ("主图", StagePhase::Current(0.6)), ("SKU 图", StagePhase::Queued)]; + let image_cells = vec![Cell::Verified, Cell::Verified, Cell::Filled, Cell::Empty, Cell::Empty]; + let copy_cells = vec![Cell::Filled, Cell::Empty, Cell::Empty, Cell::Empty]; + let workers = vec![ + WorkerState { number: 1, stage: WorkerStage::Generating, slot: "主图 4 · 细节特写", active: true }, + WorkerState { number: 2, stage: WorkerStage::WaitingResult, slot: "主图 5 · 尺寸示意", active: true }, + WorkerState { number: 9, stage: WorkerStage::Preparing, slot: "没有代号的", active: false }, + ]; + let stages = vec![ + GoalStage { name: "详情页", done: 6, total: 6, unit: "屏", elapsed: Some(Duration::from_secs(240)), tokens: Some(1200), + slots: vec![GoalSlot { label: "第 1 屏 · 首屏卖点", state: SlotState::Done }] }, + GoalStage { name: "主图", done: 3, total: 5, unit: "张", elapsed: None, tokens: None, + slots: (0..7).map(|index| GoalSlot { label: "主图", state: if index < 3 { SlotState::Done } else if index == 3 { SlotState::Failed } else { SlotState::Queued } }).collect() }, + ]; + Fixture { pipeline, image_cells, copy_cells, workers, stages } + } + + #[test] + fn goal_progress_panel_fits_narrow_and_wide_docks_and_opens_its_roadmap_on_click() { + let Fixture { pipeline, image_cells, copy_cells, workers, stages } = fixture(); + let budget = GoalBudget::Time { elapsed: Duration::from_secs(240), limit: Some(Duration::from_secs(5400)) }; + let show = |ui: &mut Ui, state: RunState| { + kit::scope(ui, |ui| { + goal_progress_panel(ui, egui::Id::unique("goal"), GoalProgressPanel { + title: "整套", state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &workers, roadmap: Some(&stages), + }, false, |index| format!("图片 {}", index + 1)) + }).inner + }; + for (width, name) in [(250.0, "narrow"), (520.0, "wide")] { + let ctx = egui::Context::default(); + fonts(&ctx); + let mut first = None; + let output = render(&ctx, 0.0, |ui| { + ui.set_width(width); + first = Some(show(ui, RunState::Running)); + }); + let first = first.unwrap_or_else(|| panic!("{name} panel renders")); + let drawn = texts(&output); + assert!(first.rect.width() <= width + 0.1 && first.rect.left() >= 0.0 && first.rect.right() <= width + 0.1, "{name}: {:?} within {width}", first.rect); + assert!(first.rect.contains_rect(first.title) && first.title.width() > 0.0, "{name}: the step name keeps its room"); + assert!(first.stop.is_some() && first.toggle.rect.width() > 0.0, "running work can be stopped and the roadmap opened"); + assert_eq!((first.image_cells["filled"].as_u64(), first.image_cells["verified"].as_u64()), (Some(3), Some(2))); + assert_eq!((first.copy_cells["filled"].as_u64(), first.copy_cells["total"].as_u64()), (Some(1), Some(4))); + assert_eq!(first.worker_badges.len(), 2, "only sub-agents with a letter get a badge"); + assert!(first.workers.is_empty(), "the list stays closed until asked for"); + assert!(drawn.iter().any(|text| text.contains("主图 60%")), "{name}: the current stage reports its share"); + assert_eq!(drawn.iter().any(|text| text == "4m / 90m"), name == "wide", "the budget reads in the wide dock; the narrow dock gives the row to the step name"); + let _ = click(&ctx, first.toggle.rect.center(), 1.0, |ui| { + ui.set_width(width); + show(ui, RunState::Running); + }); + // 抽屉带着高度过渡展开:等过渡结束,列表里的字才都露出来。 + let mut opened = None; + let output = render(&ctx, 1.4, |ui| { + ui.set_width(width); + opened = Some(show(ui, RunState::Running)); + }); + let opened = opened.unwrap_or_else(|| panic!("{name} roadmap opens")); + assert!(opened.rect.height() > first.rect.height(), "{name}: the drawer takes real height"); + assert_eq!(opened.workers.len(), 2); + for worker in &opened.workers { + assert!(worker["rect"].is_array() && worker["badge"].is_array() && worker["step"].is_string(), "{worker}"); + } + let drawn = texts(&output); + for expected in ["详情页", "6/6 屏", "3/5 张", "4m", "1.2k tokens", "还有 1 个图位", "主图 4 · 细节特写", "等结果"] { + assert!(drawn.iter().any(|text| text == expected || text.ends_with(expected)), "{name}: {expected} is drawn: {drawn:?}"); + } + assert!(!drawn.iter().any(|text| text == "没有代号的"), "a sub-agent without a letter is not listed"); + // 再点一次:抽屉带着高度过渡收起,过渡结束后不再占位。 + let _ = click(&ctx, opened.toggle.rect.center(), 2.0, |ui| { + ui.set_width(width); + show(ui, RunState::Running); + }); + let mut closed = None; + render(&ctx, 3.0, |ui| { + ui.set_width(width); + closed = Some(show(ui, RunState::Running)); + }); + let closed = closed.unwrap_or_else(|| panic!("{name} roadmap closes")); + assert!(closed.workers.is_empty() && closed.rect.height() < opened.rect.height(), "{name}: {:?} back to {:?}", closed.rect, opened.rect); + } + } + + #[test] + fn a_settled_goal_has_no_stop_and_a_token_budget_reads_as_tokens() { + let ctx = egui::Context::default(); + fonts(&ctx); + let Fixture { pipeline, image_cells, copy_cells, .. } = fixture(); + let mut done = None; + let mut failed = None; + // 面板给足宽度:主条先保证步骤名的位置,放得下才轮到流水线与预算。 + let output = render(&ctx, 0.0, |ui| { + ui.set_width(780.0); + kit::scope(ui, |ui| { + done = Some(goal_progress_panel(ui, egui::Id::unique("done"), GoalProgressPanel { + title: "整套", state: RunState::Completed, budget: GoalBudget::Tokens { used: 1200, limit: Some(8000) }, + pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &[], roadmap: None, + }, true, |_| String::new())); + failed = Some(goal_progress_panel(ui, egui::Id::unique("failed"), GoalProgressPanel { + title: "整套", state: RunState::Failed, budget: GoalBudget::Tokens { used: 1200, limit: None }, + pipeline: &[], image_cells: &[], copy_cells: &[], + workers: &[WorkerState { number: 1, stage: WorkerStage::Reviewing, slot: "主图", active: false }], roadmap: None, + }, true, |_| String::new())); + }); + }); + assert!(done.is_some_and(|panel| panel.stop.is_none() && panel.workers.is_empty() && panel.image_cells["filled"] == 3)); + let failed = failed.unwrap_or_else(|| panic!("failed panel renders")); + assert!(failed.stop.is_none() && failed.image_cells.is_null() && failed.worker_badges.len() == 1); + let drawn = texts(&output); + assert!(drawn.iter().any(|text| text == "1.2k / 8k tokens") && drawn.iter().any(|text| text == "1.2k tokens"), "the bar reads tokens in both panels when that is the budget: {drawn:?}"); + } + + #[test] + fn user_messages_reveal_with_a_glow_and_settle_without_changing_the_bubble() { + let ctx = egui::Context::default(); + crate::cjk_fonts::install_system_provider_for_tests(&ctx); + fonts(&ctx); + let text = "保留产品结构,让光线更加柔和。"; + let mut bounds = Vec::new(); + let mut glows = Vec::new(); + for time in [0.0, 0.1, 0.4, 4.0] { + let output = render(&ctx, time, |ui| { + ui.set_width(240.0); + kit::scope(ui, |ui| { + bounds.push(user_message(ui, text, Some(0.0), false)); + }); + }); + glows.push(meshes(&output)); + } + assert!(bounds.windows(2).all(|pair| pair[0] == pair[1]), "the bubble is sized to the whole message and never resizes: {bounds:?}"); + assert!(glows[1] > 0, "the reveal carries a soft glow while it runs"); + assert_eq!(glows[3], 0, "and draws nothing once the message has settled"); + let mut reduced = Vec::new(); + let output = render(&ctx, 10.0, |ui| { + ui.set_width(240.0); + kit::scope(ui, |ui| { + reduced.push(user_message(ui, text, Some(10.0), true)); + }); + }); + assert_eq!(reduced[0], bounds[0], "reduced motion shows the same bubble at once"); + assert_eq!(meshes(&output), 0, "reduced motion never starts the reveal glow"); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 0306908a..ead25dbc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -1,6 +1,20 @@ //! Scoped Stitch vocabulary for the collaboration surfaces. Native editor styles are untouched. -use crate::theme::Tokens; -use egui::{Color32, Context, CornerRadius, FontId, Frame, InnerResponse, Margin, Response, RichText, Stroke, TextStyle, Ui, Vec2, vec2}; +//! +//! 库内的规矩:字号、间距、圆角、控件高度与动效时长一律取 `theme::agent_scale` 的具名阶梯; +//! 颜色一律取 `Tokens::agent()` 与它的语义色;状态一律读 `stitch_state` 的枚举,不嗅探文案。 +//! 仍然收 `&str` 状态的旧签名只是给现有调用方的垫片,内部转调新实现,第 2 批迁走调用方后删除。 +use super::agent_motion::{Pace, schedule}; +use super::stitch_cache::{changed_environment, content_key, Settled}; +use super::stitch_state::{Tone, ToolStatus}; +use super::typing_text::{self as reveal, TrailToken}; +use crate::theme::agent_scale::motion as timing; +use crate::theme::agent_scale::{control, icon, radius, space, Type}; +use crate::theme::{Tokens, AGENT_SEMANTIC}; +use egui::{Color32, Context, CornerRadius, FontId, Frame, InnerResponse, Margin, Response, RichText, Stroke, TextStyle, Ui, Vec2, pos2, vec2}; +// 补齐的原语、状态模型与时间流外壳分在三个兄弟模块里,各自带单测: +// `stitch_kit`(排版、提示条、停止钮、等待卡、网格、列表行、徽标、叠图说明)、 +// `stitch_state`(Tone、ToolStatus、WorkerStage、NoticeKind、RunState、ErrorCategory、FieldState)、 +// `stitch_timeline`(时间流 11 块外壳与目标驾驶舱)。它们只依赖本文件,本文件不反向依赖。 /// A critically damped surface spring. Reversals preserve both position and /// velocity; layout and identity use the same sampled value for a whole frame. @@ -15,7 +29,7 @@ impl SurfaceSpring { if reduced || !now.is_finite() { self.value = target; self.velocity = 0.0; } else { - let omega = 20.0; + let omega = timing::SPRING_OMEGA; let tangent = self.velocity + omega * displacement; let decay = (-omega * dt).exp(); self.value = self.target + (displacement + tangent * dt) * decay; @@ -79,7 +93,7 @@ fn select_popup_with_behavior(ui: &mut Ui, response: &Response, width: f32, r let opacity=ui.opacity(); ui.set_opacity(opacity * visual.opacity); let t = Tokens::get(ui.ctx()).agent(); - material_over(ui, id, rect, 8.0, 0.0, light, menu_base(), menu_rim(t)); + material_over(ui, id, rect, radius::MENU, 0.0, light, menu_base(), menu_rim(t)); ui.set_opacity(opacity); result }) @@ -92,10 +106,10 @@ pub(super) fn halo_select(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::D pub(super) fn halo_select_with_behavior(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, width: f32, selected: &str, reduced: bool, close_behavior: egui::PopupCloseBehavior, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse> { let t = Tokens::get(ui.ctx()).agent(); let background = super::agent_motion::reserve_background(ui); - let response = ui.push_id(id, |ui| ui.add(egui::Button::new(RichText::new(selected).size(13.0)) + let response = ui.push_id(id, |ui| ui.add(egui::Button::new(RichText::new(selected).size(Type::Title.size())) .right_text(crate::icons::image("chevron-down", 12.0, t.text_dim)).gap(2.0) .fill(Color32::TRANSPARENT).stroke(Stroke::NONE) - .min_size(vec2(width, 34.0)).corner_radius(12).truncate())).inner; + .min_size(vec2(width, control::DEFAULT)).corner_radius(radius::CHIP).truncate())).inner; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), selected)); control_material(ui, &response, 12.0, reduced, egui::Popup::is_id_open(ui.ctx(), response.id.with("popup")), background); let limit = (ui.ctx().content_rect().width() - 32.0).max(140.0); @@ -157,12 +171,17 @@ fn reply_job(text: &str, width: f32, color: Color32, code_background: Color32) - reply_layout(text, width, color, code_background).0 } +/// 回复正文行高:14pt × 1.65。 +const REPLY_LINE_HEIGHT: f32 = 23.1; +/// 代码块标题行(语言标记所在的那一行)的行高。 +const REPLY_CODE_HEADER_HEIGHT: f32 = 30.0; + fn reply_layout(text: &str, width: f32, color: Color32, code_background: Color32) -> (egui::text::LayoutJob, Vec) { - let plain = egui::TextFormat { font_id: FontId::proportional(14.0), color, line_height: Some(23.1), ..Default::default() }; - let strong = egui::TextFormat { font_id: crate::theme::semibold(14.0), ..plain.clone() }; - let code = egui::TextFormat { font_id: crate::theme::mono(13.0), background: code_background, ..plain.clone() }; + let plain = egui::TextFormat { font_id: Type::Body.font_id(), color, line_height: Some(REPLY_LINE_HEIGHT), ..Default::default() }; + let strong = egui::TextFormat { font_id: Type::Body.semibold(), ..plain.clone() }; + let code = egui::TextFormat { font_id: crate::theme::mono(Type::Title.size()), background: code_background, ..plain.clone() }; let block_code = egui::TextFormat { background: Color32::TRANSPARENT, ..code.clone() }; - let header = egui::TextFormat { line_height: Some(30.0), ..plain.clone() }; + let header = egui::TextFormat { line_height: Some(REPLY_CODE_HEADER_HEIGHT), ..plain.clone() }; let mut job = egui::text::LayoutJob::default(); let mut blocks: Vec = Vec::new(); let mut fence_length = 0usize; @@ -195,7 +214,7 @@ fn reply_layout(text: &str, width: f32, color: Color32, code_background: Color32 job.append("\n", 0.0, header.clone()); blocks.push(ReplyCodeBlock { start, end: job.text.chars().count(), language: language.trim().to_owned(), contents: String::new() }); fence_length = opening_ticks; - } else if let Some((size, heading)) = content.strip_prefix("###### ").or_else(|| content.strip_prefix("##### ")).or_else(|| content.strip_prefix("#### ")).map(|s| (14.0, s)).or_else(|| content.strip_prefix("### ").map(|s| (15.0, s))).or_else(|| content.strip_prefix("## ").map(|s| (16.0, s))).or_else(|| content.strip_prefix("# ").map(|s| (18.0, s))) { + } else if let Some((size, heading)) = content.strip_prefix("###### ").or_else(|| content.strip_prefix("##### ")).or_else(|| content.strip_prefix("#### ")).map(|s| (Type::Body.size(), s)).or_else(|| content.strip_prefix("### ").map(|s| (Type::Subheading.size(), s))).or_else(|| content.strip_prefix("## ").map(|s| (Type::Heading.size(), s))).or_else(|| content.strip_prefix("# ").map(|s| (Type::TitleLg.size(), s))) { let format = egui::TextFormat { font_id: crate::theme::semibold(size), ..plain.clone() }; append_reply_inline(&mut job, heading, &format, &format, &code); job.append(ending, 0.0, format); @@ -266,7 +285,7 @@ fn loader_ease(x: f32) -> f32 { fn loader_dot_opacity(now: f64, index: usize, running: bool, reduced: bool) -> f32 { if reduced || !running { return 0.5; } - let phase = ((now - index as f64 * 0.2).rem_euclid(1.2) / 0.6) as f32; + let phase = ((now - index as f64 * 0.2).rem_euclid(timing::LOADER_PERIOD) / (timing::LOADER_PERIOD * 0.5)) as f32; let ramp = if phase <= 1.0 { loader_ease(phase) } else { 1.0 - loader_ease(phase - 1.0) }; 0.25 + 0.75 * ramp } @@ -282,31 +301,24 @@ pub(super) fn ai_loader(ui: &mut Ui, id: egui::Id, running: bool, reduced: bool) ui.painter().circle_filled(rect.left_center() + vec2(4.0 + i as f32 * 8.0, 0.0), 3.0, t.text.gamma_multiply(opacity)); } let _ = id; - if running && !reduced && ui.is_rect_visible(rect) { ui.ctx().request_repaint_after(std::time::Duration::from_millis(16)); } + if running && !reduced { schedule(ui, rect, Pace::Full); } } /// Only public, allowlisted activity is passed in by the business layer. /// Each group keeps its own disclosure choice as tool states change. The /// heading is the same quiet row as every other timeline event; only an open /// group spends a card on its rows. -pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { +/// 工具调用组的外壳:标题行与可折叠的卡片。计数与成败由调用方结构化给出,不从标题文案里拆。 +pub(super) fn tool_group_head(ui: &mut Ui, id: egui::Id, heading: &str, count: Option<&str>, tone: Tone, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { use super::agent_stream::{EventRow, EventTone, RowAction}; - let mut open = ui.data(|data| data.get_temp::(id.with("open"))).unwrap_or(active); - let (heading, count) = title.split_once(" · ").map_or((title, None), |(heading, count)| (heading, Some(count))); - let tone = if title.contains("失败") { - EventTone::Failure - } else if active { - EventTone::Active - } else { - EventTone::Quiet - }; + let mut open = ui.data(|data| data.get_temp::(id.with("open"))).unwrap_or(tone == Tone::Active); let header = super::agent_stream::event_row(ui, id.with("header"), EventRow { - glyph: "settings", text: heading, meta: count, tone, hint: None, action: RowAction::Expand(open), + glyph: "settings", text: heading, meta: count, tone: EventTone::from(tone), hint: None, action: RowAction::Expand(open), }, reduced); if header.clicked() { open = !open; } if open { ui.horizontal(|ui| { - ui.add_space(12.0); + ui.add_space(space::MD); surface(ui, SurfaceRole::Task, |ui| { ui.vertical(|ui| { ui.set_width(ui.available_width().max(1.0)); @@ -318,6 +330,14 @@ pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool ui.data_mut(|data| data.insert_temp(id.with("open"), open)); } +/// 旧签名垫片:标题形如"工具调用 · 3/5 已完成 · 1 项失败",成败仍从文案里读。 +/// 这是本文件里唯一一处读中文文案定色调的地方;第 2 批把调用方迁到 `typed_tool_group` 后删除。 +pub(super) fn tool_group(ui: &mut Ui, id: egui::Id, title: &str, active: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) { + let (heading, count) = title.split_once(" · ").map_or((title, None), |(heading, count)| (heading, Some(count))); + let tone = if title.contains("失败") { Tone::Failure } else if active { Tone::Active } else { Tone::Quiet }; + tool_group_head(ui, id, heading, count, tone, reduced, body) +} + /// A static capacity ring; missing measurements show only the neutral track. pub(super) fn context_capacity(ui: &mut Ui, fraction: Option, label: &str) -> Response { let t = Tokens::get(ui.ctx()).agent(); @@ -337,62 +357,65 @@ pub(super) fn context_capacity(ui: &mut Ui, fraction: Option, label: &str) response.on_hover_text(label) } +/// 旧签名垫片:线上状态字符串只在这里解析一次,转给 `task_status_row`。 pub(super) fn task_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, status: &str, elapsed: Option<&str>, reduced: bool) { + task_status_row(ui, _id, glyph, name, ToolStatus::parse(status), elapsed, reduced); +} + +/// 一行工具调用:图标、状态徽标与可选的真实耗时。文案、色调与图标都取自 `ToolStatus`。 +pub(super) fn task_status_row(ui: &mut Ui, _id: egui::Id, glyph: &str, name: &str, status: ToolStatus, elapsed: Option<&str>, reduced: bool) { let t = Tokens::get(ui.ctx()).agent(); - let (state, tone) = match status { - "pending" => ("等待", StatusTone::Neutral), "started" => ("进行中", StatusTone::Neutral), - "completed" => ("已完成", StatusTone::Neutral), "failed" => ("失败", StatusTone::Error), - "stopped" => ("已停止", StatusTone::Warning), _ => ("状态未知", StatusTone::Warning), - }; - let text_color = match tone { StatusTone::Neutral => t.text_dim, StatusTone::Warning => t.warning, StatusTone::Error => t.danger }; - let status_galley = ui.painter().layout_no_wrap(state.to_owned(), FontId::proportional(12.0), text_color); - let name_galley = ui.painter().layout_no_wrap(name.to_owned(), FontId::proportional(12.0), t.text); - let timer_height = elapsed.map_or(0.0, |text| ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(12.0), t.text_dim).size().y.max(12.0)); - let badge_height = status_galley.size().y.max(12.0) + 8.0; - let row_height = badge_height.max(name_galley.size().y).max(timer_height).max(14.0); + let state = status.label(); + let running = status == ToolStatus::Started; + let text_color = status.tone().color(&t); + let status_galley = ui.painter().layout_no_wrap(state.to_owned(), Type::Meta.font_id(), text_color); + let name_galley = ui.painter().layout_no_wrap(name.to_owned(), Type::Meta.font_id(), t.text); + let timer_height = elapsed.map_or(0.0, |text| ui.painter().layout_no_wrap(text.to_owned(), Type::Meta.font_id(), t.text_dim).size().y.max(12.0)); + let badge_height = status_galley.size().y.max(12.0) + space::SM; + let row_height = badge_height.max(name_galley.size().y).max(timer_height).max(icon::MD); let row = ui.allocate_ui_with_layout(vec2(ui.available_width(), row_height), egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| { - ui.add(crate::icons::image(glyph, 14.0, t.text_dim)); - ui.label(RichText::new(name).size(12.0).color(t.text)); - let size = vec2(8.0 + 12.0 + 4.0 + status_galley.size().x + 8.0, badge_height); + ui.add(crate::icons::image(glyph, icon::MD, t.text_dim)); + ui.label(RichText::new(name).size(Type::Meta.size()).color(t.text)); + let size = vec2(space::SM + icon::SM + space::XS + status_galley.size().x + space::SM, badge_height); let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, state)); - ui.painter().rect_filled(rect, 9.0, t.field); - let (glyph, color) = match status { - "completed" => ("check", Color32::from_rgb(91, 192, 146)), - "failed" | "stopped" => ("triangle-alert", if status == "failed" { t.danger } else { t.warning }), - "started" => ("circle-dashed", t.text_dim), - _ => ("circle", t.text_dim), + ui.painter().rect_filled(rect, radius::CONTROL, t.field); + let color = match status { + ToolStatus::Completed => t.agent_semantic().success, + ToolStatus::Failed => t.danger, + ToolStatus::Stopped => t.warning, + _ => t.text_dim, }; - let alpha = if status == "started" && !reduced { 0.55 + 0.45 * ((ui.input(|i| i.time) as f32 * std::f32::consts::TAU).sin() * 0.5 + 0.5) } else { 1.0 }; - let image = crate::icons::image(glyph, 12.0, color.gamma_multiply(alpha)); - let image = if status == "started" && !reduced { - image.rotate((ui.input(|i| i.time).rem_euclid(1.2) / 1.2 * std::f64::consts::TAU) as f32, vec2(0.5, 0.5)) + let alpha = if running && !reduced { 0.55 + 0.45 * ((ui.input(|i| i.time) as f32 * std::f32::consts::TAU).sin() * 0.5 + 0.5) } else { 1.0 }; + let image = crate::icons::image(status.glyph(), icon::SM, color.gamma_multiply(alpha)); + let image = if running && !reduced { + image.rotate((ui.input(|i| i.time).rem_euclid(timing::LOADER_PERIOD) / timing::LOADER_PERIOD * std::f64::consts::TAU) as f32, vec2(0.5, 0.5)) } else { image }; - image.paint_at(ui, egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), vec2(12.0, 12.0))); + image.paint_at(ui, egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), vec2(icon::SM, icon::SM))); let text_pos = egui::pos2(rect.left() + 24.0, rect.center().y - status_galley.size().y * 0.5); ui.painter().galley(text_pos, status_galley.clone(), text_color); if let Some(elapsed) = elapsed { timer(ui, elapsed); } }); - if status == "started" && !reduced && ui.is_rect_visible(row.response.rect) { ui.ctx().request_repaint_after(std::time::Duration::from_millis(16)); } + if running && !reduced { schedule(ui, row.response.rect, Pace::Full); } } /// A compact, non-interactive timer sourced entirely from the caller's actual /// upstream duration. Reserving the measured group keeps it on one line. pub(super) fn timer(ui: &mut Ui, elapsed: &str) { let t = Tokens::get(ui.ctx()).agent(); - let galley = ui.painter().layout_no_wrap(elapsed.to_owned(), FontId::proportional(12.0), t.text_dim); + let galley = ui.painter().layout_no_wrap(elapsed.to_owned(), Type::Meta.font_id(), t.text_dim); let width = galley.size().x + 16.0; ui.allocate_ui_with_layout(vec2(width, galley.size().y.max(12.0)), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 4.0; ui.add(crate::icons::image("clock", 12.0, t.text_dim)); - ui.add(egui::Label::new(RichText::new(elapsed).size(12.0).color(t.text_dim)).extend()); + ui.add(egui::Label::new(RichText::new(elapsed).size(Type::Meta.size()).color(t.text_dim)).extend()); }); } pub(super) fn disclosure(ui: &mut Ui, id: egui::Id, title: &str, default_open: bool, reduced: bool, body: impl FnOnce(&mut Ui) -> R) -> Response { let t = Tokens::get(ui.ctx()).agent(); let mut open = ui.data(|data| data.get_temp::(id.with("open"))).unwrap_or(default_open); - let header = ui.add(egui::Button::image_and_text(crate::icons::image(if open { "chevron-down" } else { "chevron-right" }, 13.0, t.text_dim), RichText::new(title).size(13.0).color(t.text)).frame(false)); + let header = ui.add(egui::Button::image_and_text(crate::icons::image(if open { "chevron-down" } else { "chevron-right" }, 13.0, t.text_dim), RichText::new(title).size(Type::Title.size()).color(t.text)).frame(false)); if header.clicked() { open = !open; } morph_surface(ui, id.with("body"), open, reduced, body); ui.data_mut(|data| data.insert_temp(id.with("open"), open)); @@ -400,7 +423,7 @@ pub(super) fn disclosure(ui: &mut Ui, id: egui::Id, title: &str, default_open } #[derive(Clone, Default)] -struct ResponseArrival { rendered: String, arrivals: Vec, was_streaming: bool, caret_exit: Option<(f64, f32)> } +struct ResponseArrival { rendered: String, arrivals: Vec, was_streaming: bool, caret_exit: Option<(f64, f32)>, rest_at: f64 } // Cubic-bezier(.23, 1, .32, 1): invert x before evaluating y. pub(super) fn response_ease(x: f32) -> f32 { @@ -418,11 +441,24 @@ pub(super) fn response_ease(x: f32) -> f32 { 1.0 - (1.0 - u).powi(3) } +impl ResponseArrival { + /// 一批新到的字按每字 15ms 铺开(字素簇内同时到达),并记下整段文字完全定稿的时刻。 + fn settle(&mut self, added: std::ops::Range, text: &str, now: f64) { + reveal::spread_text(&mut self.arrivals, added, text, now); + self.rest_at = reveal::rest_at(&self.arrivals); + } +} + +/// 流式回复每个字符的到达时间。历史消息第一次出现就是定稿;纯追加的新字按每字 15ms 铺开, +/// 积压过多时整体压回跨度上限,吐字不会越拖越远。 fn response_arrivals(state: &mut ResponseArrival, rendered: &str, now: f64, is_streaming: bool) { if state.rendered == rendered { return; } + let live = is_streaming || !state.rendered.is_empty(); if !state.rendered.is_empty() && let Some(suffix) = rendered.strip_prefix(&state.rendered) { - state.arrivals.extend(suffix.chars().map(|_| now)); + let added = state.arrivals.len()..state.arrivals.len() + suffix.chars().count(); + state.arrivals.extend(std::iter::repeat_n(now, suffix.chars().count())); state.rendered = rendered.to_owned(); + state.settle(added, suffix, now); return; } // Keep only an anchored, ordered prefix. Markdown closing can remove its @@ -430,8 +466,9 @@ fn response_arrivals(state: &mut ResponseArrival, rendered: &str, now: f64, is_s let old: Vec = state.rendered.chars().collect(); let mut cursor = 0; let mut matching = true; + let mut rewritten = rendered.chars().count(); let mut next = Vec::new(); - let initial_arrival = if old.is_empty() && !is_streaming { now - 1.0 } else { now }; + let initial_arrival = if live { now } else { now - reveal::SETTLED_AGE }; for c in rendered.chars() { if matching && old.get(cursor) != Some(&c) { while old.get(cursor).is_some_and(|previous| matches!(*previous, '*' | '`')) { cursor += 1; } @@ -440,11 +477,21 @@ fn response_arrivals(state: &mut ResponseArrival, rendered: &str, now: f64, is_s let arrival = state.arrivals.get(cursor).copied().unwrap_or(initial_arrival); cursor += 1; arrival - } else { matching = false; initial_arrival }; + } else { + if matching { rewritten = next.len(); } + matching = false; + initial_arrival + }; next.push(arrival); } + let tail = rendered.chars().skip(rewritten).collect::(); state.rendered = rendered.to_owned(); state.arrivals = next; + if live { + state.settle(rewritten..state.arrivals.len(), &tail, now); + } else { + state.rest_at = reveal::rest_at(&state.arrivals); + } } /// Preserve the already rendered suffix when a final receipt is a suffix of @@ -480,27 +527,127 @@ fn response_static_character(c: char) -> bool { Category::OtherPunctuation) } -/// Shared glyph entrance; the native galley geometry and text remain unchanged. -pub(super) fn animate_galley(galley:&mut std::sync::Arc,arrivals:&[f64],now:f64,reduced:bool)->bool { - if reduced||!galley.text().chars().zip(arrivals).any(|(c,at)|if response_static_character(c) {*at>now} else {now-*at<0.220}) {return false;} - let mut index=0;let mut animating=false; - for placed in &mut std::sync::Arc::make_mut(galley).rows { - let row=std::sync::Arc::make_mut(&mut placed.row); - for glyph in &row.glyphs { - let arrival=arrivals.get(index).copied().unwrap_or(now-1.0);index+=1; - if glyph.uv_rect.is_nothing(){continue;} - let fixed=response_static_character(glyph.chr); - let progress=if fixed {if now>=arrival {1.0} else {0.0}} else {response_ease(((now-arrival)/0.220).clamp(0.0,1.0) as f32)}; - if progress>=1.0 {continue;} - animating=true; - let first=glyph.first_vertex as usize;let end=first.saturating_add(4).min(row.visuals.glyph_vertex_range.end); - if let Some(vertices)=row.visuals.mesh.vertices.get_mut(first..end) { - for vertex in vertices {if !fixed {vertex.pos.y+=2.0*(1.0-progress);}vertex.color=vertex.color.gamma_multiply(progress);} +/// 逐字扩散在一帧里的结果。调用方据此决定重绘档位,并把 `glow` 画在字形所在的位置上。 +#[derive(Default)] +pub(super) struct RevealPaint { + /// 还有字在入场或尚未轮到:按满帧重绘。 + pub entering: bool, + /// 尾韵正亮:按满帧重绘。 + pub glowing: bool, + /// 只剩尾韵在慢慢收:按待机档重绘即可。 + pub fading: bool, + /// 流头柔光与尾韵光带,galley 自身坐标;定稿后为空。 + pub glow: Vec, +} + +/// 逐字扩散:输入框、用户气泡与 Agent 正文共用的字形入场与柔光,节奏见 `typing_text`。 +/// 只改已经排好版的 galley 里的字形顶点,原生几何与文本不变;标点与空白不入场, +/// 保持它们已排好的位置。 +pub(super) fn animate_galley( + galley: &mut std::sync::Arc, + arrivals: &[f64], + now: f64, + reduced: bool, + show_glow: bool, + ink: reveal::RevealInk, +) -> RevealPaint { + let mut paint = RevealPaint::default(); + if reduced || galley.rows.is_empty() || !now.is_finite() { + return paint; + } + // 流头附近由新到旧的可见字:先算好柔光,入场时要用到它。 + let mut tokens = Vec::new(); + let total: usize = galley.rows.iter().map(|placed| placed.glyphs.len() + usize::from(placed.ends_with_newline)).sum(); + if show_glow && total == arrivals.len() { + let mut index = total; + 'collect: for (row_index, placed) in galley.rows.iter().enumerate().rev() { + index -= usize::from(placed.ends_with_newline); + for (glyph_index, glyph) in placed.glyphs.iter().enumerate().rev() { + index -= 1; + if glyph.chr.is_whitespace() || glyph.uv_rect.is_nothing() { + continue; + } + let Some(arrival) = arrivals.get(index) else { break 'collect }; + let top = placed.pos.y + glyph.pos.y - glyph.font_ascent; + tokens.push(TrailToken { + row: row_index, + glyph: glyph_index, + center: pos2(placed.pos.x + glyph.pos.x + glyph.advance_width * 0.5, top + glyph.font_height * 0.5), + advance: glyph.advance_width, + font: glyph.font_height.max(8.0), + top, + bottom: top + glyph.font_height, + arrival: *arrival, + glow: 0.0, + }); + if tokens.len() >= reveal::TAIL + 3 { + break 'collect; + } } } - if placed.ends_with_newline {index+=1;} + reveal::light_trail(&mut tokens, now); } - animating + // 入场:单字 300ms cubic-out,自下方 4pt 升起并从 1.035 倍收拢;尚未轮到的字以极淡的光雾占位; + // 尾韵里的字被柔光微微托起并染上光的颜色。 + let lit = ink.glow().lerp_to_gamma(Color32::WHITE, 0.5); + let first_trail_row = tokens.last().map_or(usize::MAX, |token| token.row); + let mut index = 0usize; + // Galley 与排版缓存共享:只在逐字扩散时才克隆一份(行数组很轻,字形网格按行再按需克隆)。 + for (row_index, placed) in std::sync::Arc::make_mut(galley).rows.iter_mut().enumerate() { + let row_chars = placed.glyphs.len() + usize::from(placed.ends_with_newline); + let range = index..index + row_chars; + index += row_chars; + if range.end > arrivals.len() || !arrivals[range.clone()].iter().any(|at| *at > now || now - *at < reveal::ENTER) { + continue; + } + let row = std::sync::Arc::make_mut(&mut placed.row); + let near_head = row_index >= first_trail_row; + for (glyph_index, glyph) in row.glyphs.iter_mut().enumerate() { + if glyph.uv_rect.is_nothing() { + continue; + } + let arrival = arrivals.get(range.start + glyph_index).copied().unwrap_or(now - reveal::SETTLED_AGE); + let glow = if near_head { + tokens.iter().find(|token| token.row == row_index && token.glyph == glyph_index).map_or(0.0, |token| token.glow) + } else { + 0.0 + }; + let age = now - arrival; + let mist = age < 0.0; + let progress = if mist { + 0.0 + } else if response_static_character(glyph.chr) { + 1.0 + } else { + reveal::ease_out((age / reveal::ENTER) as f32) + }; + if progress >= 1.0 && glow < reveal::GLOW_LIMIT { + continue; + } + paint.entering |= progress < 1.0; + let first = glyph.first_vertex as usize; + let end = first.saturating_add(4).min(row.visuals.glyph_vertex_range.end); + let Some(vertices) = row.visuals.mesh.vertices.get_mut(first..end) else { continue }; + let rise = if mist { 0.0 } else { reveal::RISE_POINTS * (1.0 - progress) - reveal::LIFT_POINTS * glow }; + let scale = if mist { 1.0 } else { reveal::SCALE_FROM + (1.0 - reveal::SCALE_FROM) * progress }; + let center = vertices.iter().fold(pos2(0.0, 0.0), |sum, vertex| sum + vertex.pos.to_vec2()) / vertices.len() as f32; + for vertex in vertices { + vertex.pos = center + (vertex.pos - center) * scale + vec2(0.0, rise); + if glow >= reveal::GLOW_LIMIT { + vertex.color = vertex.color.lerp_to_gamma(lit, 0.38 * glow); + } + let opacity = if mist && show_glow { reveal::MIST } else { progress }; + vertex.color = vertex.color.gamma_multiply(opacity); + } + } + } + let strength = tokens.iter().fold(0.0_f32, |most, token| most.max(token.glow)); + if strength >= reveal::GLOW_LIMIT { + paint.glowing = strength >= reveal::STRONG_GLOW; + paint.fading = !paint.glowing; + paint.glow = reveal::glow_shapes(&tokens, ink.glow()); + } + paint } fn response_caret_rect(galley: &egui::Galley, pos: egui::Pos2) -> egui::Rect { @@ -519,39 +666,27 @@ fn response_caret_rect(galley: &egui::Galley, pos: egui::Pos2) -> egui::Rect { egui::Rect::from_min_size(egui::pos2(cursor.min.x + 1.0, top), vec2(width, height)) } +/// 一段回复的排版结果:去掉 Markdown 标记后的正文、代码块位置与整段 Galley。 #[derive(Clone)] -struct ReplyLayoutCache { - owner: egui::Id, - text: String, - width: f32, - color: Color32, - code_background: Color32, - pixels_per_point: f32, - fonts: egui::FontDefinitions, - options: egui::epaint::text::TextOptions, +pub(super) struct ReplyLayout { rendered: String, blocks: Vec, galley: std::sync::Arc, } -fn same_font_definitions(a: &egui::FontDefinitions, b: &egui::FontDefinitions) -> bool { - a.families == b.families && a.font_data.len() == b.font_data.len() - && a.font_data.iter().all(|(name, font)| b.font_data.get(name).is_some_and(|other| std::sync::Arc::ptr_eq(font, other))) +/// 正在流式变化的那一条回复(至多一条),加上已定稿回复的排版缓存。 +#[derive(Clone, Default)] +struct ReplyLayouts { + streaming: Settled, + settled: Settled, + layouts: u64, } -fn cached_reply_layout(ui: &Ui, id: egui::Id, text: &str, width: f32, color: Color32, code_background: Color32, streaming: bool) -> std::sync::Arc { - // Exactly one active reply can retain a shaped galley, bounded in size. A - // finished reply clears its entry, so history does not hold text meshes. - let cache_id = egui::Id::unique("agent-active-reply-layout"); - let (fonts, options) = ui.fonts(|fonts| (fonts.definitions().clone(), *fonts.options())); - let pixels_per_point = ui.ctx().pixels_per_point(); - let previous = ui.data(|data| data.get_temp::>(cache_id)); - if streaming && let Some(cache) = &previous - && cache.owner == id && cache.text == text && cache.width == width && cache.color == color - && cache.code_background == code_background && cache.pixels_per_point == pixels_per_point - && same_font_definitions(&cache.fonts, &fonts) && cache.options == options { - return cache.clone(); - } +fn reply_layout_cache() -> egui::Id { + egui::Id::unique("agent-active-reply-layout") +} + +fn build_reply_layout(ui: &Ui, text: &str, width: f32, color: Color32, code_background: Color32) -> std::sync::Arc { let (job, blocks) = reply_layout(text, width, color, code_background); let rendered = job.text.clone(); let mut galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); @@ -563,12 +698,53 @@ fn cached_reply_layout(ui: &Ui, id: egui::Id, text: &str, width: f32, color: Col for row in std::sync::Arc::make_mut(&mut galley).rows.iter_mut().skip(first).take(last - first + 1) { row.pos.x += 10.0; } } } - let cache = std::sync::Arc::new(ReplyLayoutCache { owner: id, text: text.to_owned(), width, color, code_background, pixels_per_point, fonts, options, rendered, blocks, galley }); - ui.data_mut(|data| { - if streaming && text.len() <= 262_144 { data.insert_temp(cache_id, cache.clone()); } - else if previous.as_ref().is_some_and(|prior| prior.owner == id) { data.remove::>(cache_id); } + std::sync::Arc::new(ReplyLayout { rendered, blocks, galley }) +} + +/// 回复的排版缓存。流式中的那一条文本没变就复用;已经定稿的回复按内容键留住: +/// 历史消息重绘时不再重新解析 Markdown、重建 LayoutJob 并整段哈希,带代码块的回复也不再每帧深拷贝那些行。 +/// 缓存有条数与字符总量上限;字体定义、缩放或字体图集一变整体作废(见 `stitch_cache`)。 +fn cached_reply_layout(ui: &Ui, id: egui::Id, text: &str, width: f32, color: Color32, code_background: Color32, streaming: bool) -> std::sync::Arc { + let key = content_key((text, width.to_bits(), color, code_background)); + let chars = text.chars().count(); + // 核对字体环境要读字体,而 ui.fonts 与 ui.data 取的是同一把锁:先在锁外核对,再进锁查缓存。 + let held = ui.data(|data| { + data.get_temp::(reply_layout_cache()) + .and_then(|cache| if streaming { cache.streaming.held() } else { cache.settled.held() }) }); - cache + let fresh = changed_environment(held.as_deref(), ui); + if let Some(layout) = ui.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(reply_layout_cache()); + if streaming { cache.streaming.get(id, key, fresh.as_ref()) } else { cache.settled.get(id, key, fresh.as_ref()) } + }) { + return layout; + } + let layout = build_reply_layout(ui, text, width, color, code_background); + ui.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(reply_layout_cache()); + cache.layouts += 1; + if streaming { + // Exactly one bounded active reply retains its galley while its text is unchanged. + cache.streaming.replace(id, key, chars, std::sync::Arc::clone(&layout)); + } else { + // A finished reply leaves the streaming slot and settles into the bounded history cache. + cache.streaming.retire(id); + cache.settled.insert(id, key, chars, std::sync::Arc::clone(&layout)); + } + }); + layout +} + +/// 测试与诊断用:到目前为止真正执行过的回复排版次数。 +#[cfg(test)] +pub(super) fn reply_layouts_performed(ui: &Ui) -> u64 { + ui.data(|data| data.get_temp::(reply_layout_cache()).map_or(0, |cache| cache.layouts)) +} + +/// 测试与诊断用:此刻留住的"正在流式变化"的回复条数(至多一条)。 +#[cfg(test)] +pub(super) fn streaming_reply_held(ui: &Ui) -> usize { + ui.data(|data| data.get_temp::(reply_layout_cache()).map_or(0, |cache| cache.streaming.len())) } /// Selectable Markdown layout with independent arrival batches and a streaming caret. @@ -593,9 +769,12 @@ pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streamin state.clone() }); let mut galley = layout.galley.clone(); - // Modify the already-shaped galley once. Each visible glyph owns its vertex - // range, so punctuation, selection geometry and code backgrounds stay put. - let animating=animate_galley(&mut galley,&state.arrivals,now,reduced); + // 还在逐字扩散时才改写已排好版的 galley:每个可见字形有自己的顶点区间, + // 标点、选区几何与代码块背景都留在原位。定稿的回复一个顶点都不碰。 + let mut frame = RevealPaint::default(); + if now < state.rest_at { + frame = animate_galley(&mut galley, &state.arrivals, now, reduced, is_streaming, reveal::RevealInk::agent(t)); + } let response = ui.add(egui::Label::new(galley.clone()).selectable(true)); let pos = response.rect.min; let mut backgrounds = Vec::new(); @@ -604,29 +783,37 @@ pub(super) fn streaming_reply(ui: &mut Ui, id: egui::Id, text: &str, is_streamin let end_index = if block.contents.ends_with('\n') { block.end.saturating_sub(1) } else { block.end }; let end = galley.pos_from_cursor(egui::text::CCursor::new(end_index)).translate(pos.to_vec2()); let rect = egui::Rect::from_min_max(egui::pos2(pos.x, start.top()), egui::pos2(pos.x + width, end.bottom().max(start.bottom()))); - backgrounds.push(egui::Shape::rect_filled(rect, 12.0, t.canvas)); - backgrounds.push(egui::Shape::rect_stroke(rect.shrink(0.5), 12.0, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside)); + backgrounds.push(egui::Shape::rect_filled(rect, radius::CHIP, t.canvas)); + backgrounds.push(egui::Shape::rect_stroke(rect.shrink(0.5), radius::CHIP, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside)); if !block.language.is_empty() { - let label_clip = egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - 32.0).max(rect.left()), (rect.top() + 30.0).min(rect.bottom()))); - ui.painter().with_clip_rect(ui.clip_rect().intersect(label_clip)).text(rect.min + vec2(10.0, 7.0), egui::Align2::LEFT_TOP, &block.language, FontId::proportional(11.0), t.text.gamma_multiply(0.7)); + let label_clip = egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - 32.0).max(rect.left()), (rect.top() + REPLY_CODE_HEADER_HEIGHT).min(rect.bottom()))); + ui.painter().with_clip_rect(ui.clip_rect().intersect(label_clip)).text(rect.min + vec2(10.0, 7.0), egui::Align2::LEFT_TOP, &block.language, Type::Caption.font_id(), t.text.gamma_multiply(0.7)); } - let button_rect = egui::Rect::from_min_size(egui::pos2(rect.right() - 30.0, rect.top() + 1.0), vec2(28.0, 28.0)); + let button_rect = egui::Rect::from_min_size(egui::pos2(rect.right() - 30.0, rect.top() + 1.0), vec2(control::STANDARD, control::STANDARD)); let mut child = ui.new_child(egui::UiBuilder::new().id_salt((id, "copy-code", index)).max_rect(button_rect)); child.set_clip_rect(ui.clip_rect().intersect(rect)); - if crate::icons::agent_icon_button(&mut child, "copy", 28.0, false, "复制代码").clicked() { + if crate::icons::agent_icon_button(&mut child, "copy", control::STANDARD, false, "复制代码").clicked() { ui.ctx().copy_text(block.contents.clone()); } } + // 流头柔光与尾韵光带垫在字形下面、代码块背景上面。 + for mut shape in frame.glow.drain(..) { + shape.translate(pos.to_vec2()); + backgrounds.push(shape); + } ui.painter().set(background, egui::Shape::Vec(backgrounds)); let caret_alpha = if is_streaming { response_caret_opacity(now, reduced) } else if reduced { 0.0 } else { - state.caret_exit.map_or(0.0, |(start, initial)| initial * (1.0 - response_ease(((now - start) / 0.160).clamp(0.0, 1.0) as f32))) + state.caret_exit.map_or(0.0, |(start, initial)| initial * (1.0 - response_ease(((now - start) / timing::CARET_EXIT).clamp(0.0, 1.0) as f32))) }; if caret_alpha > 0.001 { let caret = response_caret_rect(&galley, pos); ui.painter().rect_filled(caret, caret.width() * 0.5, t.text.gamma_multiply(caret_alpha)); } - if ui.is_rect_visible(response.rect) && (animating || (!reduced && (is_streaming || caret_alpha > 0.001))) { - ui.ctx().request_repaint(); + // 逐字入场、流式输出与光标按满帧;只剩尾韵在收时交给待机档;定稿且不可见时一帧都不申请。 + if !reduced && (frame.entering || frame.glowing || is_streaming || caret_alpha > 0.001) { + schedule(ui, response.rect, Pace::Full); + } else if frame.fading { + schedule(ui, response.rect, Pace::Idle); } response } @@ -641,7 +828,7 @@ pub(super) fn approval_options(ui: &mut Ui, id: egui::Id, labels: &[&str], resol let t = Tokens::get(ui.ctx()).agent(); let deciding = resolved.is_none(); let progress = morph_value(ui.ctx(), id.with("answers"), deciding, reduced); - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), 34.0), egui::Sense::hover()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), control::DEFAULT), egui::Sense::hover()); let opacity = ui.opacity(); let mut answers = Vec::new(); if progress > 0.001 { @@ -658,7 +845,7 @@ pub(super) fn approval_options(ui: &mut Ui, id: egui::Id, labels: &[&str], resol record.set_clip_rect(rect.intersect(ui.clip_rect())); record.set_opacity(opacity * (1.0 - progress)); let text = if chosen == 0 { *action } else { *opt_out }; - record.add(egui::Label::new(RichText::new(format!("已选择 · {text}")).size(13.0).color(t.text_dim))); + record.add(egui::Label::new(RichText::new(format!("已选择 · {text}")).size(Type::Title.size()).color(t.text_dim))); } answers } @@ -669,12 +856,26 @@ impl From for SendSurface { fn from(rect:egui::Rect)->Self {Self {re pub(super) fn sent_glow_active(ui:&Ui,id:egui::Id,reduced:bool)->bool { if reduced {return false;} let now=ui.input(|input|input.time); - ui.data(|data|data.get_temp::(id)).is_some_and(|start|(0.0..0.640).contains(&(now-start))) + ui.data(|data|data.get_temp::(id)).is_some_and(|start|(0.0..timing::GLOW_SEND).contains(&(now-start))) } pub(super) fn composer_glow_mode(ui:&Ui,reduced:bool)->&'static str { if reduced {"static"} else if sent_glow_active(ui,egui::Id::unique("composer-sent-glow"),false) {"glow-pill-surge"} else {"glow-pill"} } + +/// 此刻是什么让输入浮层的光涌保持满帧:任务在运行,或输入框持有焦点、正在输入。 +/// 这些之外就是纯待机,帧率平滑降下来。指针悬停由库自己判断。 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct GlowPace { pub running: bool, pub engaged: bool } + +/// 旧签名:只给既有测试用;生产代码走 `sent_glow_paced`,由调用方说明运行与聚焦状态。 +#[cfg(test)] pub(super) fn sent_glow(ui:&Ui,id:egui::Id,surface:impl Into,new_message:bool,reduced:bool) { + sent_glow_paced(ui, id, surface, new_message, reduced, GlowPace::default()); +} + +/// 输入浮层的光涌。玻璃材质、流光与发送脉冲原样不动(见 `glow_pill`);这里只决定向节拍器申请哪个档位: +/// 发送脉冲的 640ms、任务运行、输入框聚焦或指针悬停时满帧,纯待机平滑降到半帧,最小化或不可见时零重绘。 +pub(super) fn sent_glow_paced(ui:&Ui,id:egui::Id,surface:impl Into,new_message:bool,reduced:bool,pace:GlowPace) { let now=ui.input(|input|input.time); let start=ui.data_mut(|data|{ if reduced {data.remove::(id);return None;} @@ -682,10 +883,13 @@ pub(super) fn sent_glow(ui:&Ui,id:egui::Id,surface:impl Into,new_me data.get_temp::(id) }); let elapsed=start.map(|start|now-start); - let pulse=elapsed.filter(|elapsed|(0.0..0.640).contains(elapsed)).map(super::glow_pill::send).unwrap_or_default(); + let pulsing=elapsed.is_some_and(|elapsed| (0.0..timing::GLOW_SEND).contains(&elapsed)); + let pulse=elapsed.filter(|elapsed| (0.0..timing::GLOW_SEND).contains(elapsed)).map(super::glow_pill::send).unwrap_or_default(); let surface=surface.into(); super::glow_pill::paint(ui,super::glow_pill::Surface {id,rect:surface.rect,radius:surface.radius,time:if reduced {2.4} else {now},pulse,opacity:1.0,background:surface.background,text_range:surface.text_range,flanks:surface.flanks}); - if !reduced&&ui.is_rect_visible(surface.rect) {ui.ctx().request_repaint_after(std::time::Duration::from_millis(16));} + if reduced {return;} + let hovering = ui.rect_contains_pointer(surface.rect); + schedule(ui, surface.rect, if pulsing || pace.running || pace.engaged || hovering { Pace::Full } else { Pace::Idle }); } pub(super) fn scope(ui: &mut Ui, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse { @@ -699,23 +903,23 @@ pub(super) fn scope_with_motion(ui: &mut Ui, reduced: bool, contents: impl Fn ui.scope(|ui| { let t = Tokens::get(ui.ctx()).agent(); let style = ui.style_mut(); - style.animation_time = if reduced { 0.0 } else { 0.22 }; - style.text_styles.insert(TextStyle::Body, FontId::proportional(14.0)); - style.text_styles.insert(TextStyle::Button, FontId::proportional(13.0)); - style.text_styles.insert(TextStyle::Small, FontId::proportional(12.0)); - style.text_styles.insert(TextStyle::Heading, FontId::proportional(20.0)); - style.spacing.item_spacing = vec2(10.0, 10.0); - style.spacing.button_padding = vec2(12.0, 7.0); - style.spacing.interact_size.y = 32.0; - style.spacing.menu_margin = Margin::same(8); + style.animation_time = if reduced { 0.0 } else { timing::NATIVE }; + style.text_styles.insert(TextStyle::Body, Type::Body.font_id()); + style.text_styles.insert(TextStyle::Button, Type::Title.font_id()); + style.text_styles.insert(TextStyle::Small, Type::Meta.font_id()); + style.text_styles.insert(TextStyle::Heading, Type::Display.font_id()); + style.spacing.item_spacing = space::ITEM; + style.spacing.button_padding = space::BUTTON_PADDING; + style.spacing.interact_size.y = control::MENU_ROW; + style.spacing.menu_margin = Margin::same(space::SM as i8); style.visuals.dark_mode = true; style.visuals.override_text_color = Some(t.text); style.visuals.weak_text_color = Some(t.text_dim); style.visuals.panel_fill = t.dock; style.visuals.window_fill = t.tab_strip; style.visuals.window_stroke = Stroke::new(1.0, t.card_border); - style.visuals.window_corner_radius = CornerRadius::same(20); - style.visuals.menu_corner_radius = CornerRadius::same(8); + style.visuals.window_corner_radius = CornerRadius::same(radius::DIALOG as u8); + style.visuals.menu_corner_radius = CornerRadius::same(radius::MENU as u8); style.visuals.extreme_bg_color = t.field; style.visuals.faint_bg_color = t.field; style.visuals.selection.bg_fill = t.hover; @@ -728,7 +932,7 @@ pub(super) fn scope_with_motion(ui: &mut Ui, reduced: bool, contents: impl Fn &mut style.visuals.widgets.open, &mut style.visuals.widgets.noninteractive, ] { - visual.corner_radius = CornerRadius::same(9); + visual.corner_radius = CornerRadius::same(radius::CONTROL as u8); visual.bg_stroke = Stroke::new(1.0, t.field_border); visual.fg_stroke = Stroke::new(1.0, t.text); visual.expansion = 0.0; @@ -764,6 +968,10 @@ pub(super) fn host_ground(ui: &mut Ui, contents: impl FnOnce(&mut Ui) -> R) - scope.inner } +/// 表面内距里不在通用阶梯上的两个档位:对话框 25、输入浮层 14。 +const DIALOG_MARGIN: i8 = 25; +const COMPOSER_MARGIN: i8 = 14; + /// Agent-only surfaces. These frames are opaque materials, not backdrop blur. /// The caller owns placement, visibility and any real blur or motion layer. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -779,12 +987,12 @@ pub(super) fn surface_frame(ctx: &Context, role: SurfaceRole) -> Frame { let t = Tokens::get(ctx).agent(); match role { SurfaceRole::Dialog => Frame::window(&ctx.style_of(egui::Theme::Dark)) - .fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(20).inner_margin(25), + .fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(radius::DIALOG as u8).inner_margin(DIALOG_MARGIN), SurfaceRole::Menu => Frame::popup(&ctx.style_of(egui::Theme::Dark)) - .fill(menu_base()).stroke(Stroke::new(1.0, menu_rim(t))).corner_radius(8).inner_margin(8), - SurfaceRole::Composer => Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(24).inner_margin(14), - SurfaceRole::Task => Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(12).inner_margin(12), - SurfaceRole::Input => Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(9).inner_margin(8), + .fill(menu_base()).stroke(Stroke::new(1.0, menu_rim(t))).corner_radius(radius::MENU as u8).inner_margin(space::SM as i8), + SurfaceRole::Composer => Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(radius::COMPOSER as u8).inner_margin(COMPOSER_MARGIN), + SurfaceRole::Task => Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(radius::CHIP as u8).inner_margin(space::MD as i8), + SurfaceRole::Input => Frame::NONE.fill(t.field).stroke(Stroke::new(1.0, t.field_border)).corner_radius(radius::CONTROL as u8).inner_margin(space::SM as i8), } } @@ -794,7 +1002,7 @@ pub(super) fn surface_frame(ctx: &Context, role: SurfaceRole) -> Frame { /// It has to stay opaque: text or controls behind a menu would otherwise /// read through between its rows. (`gamma_multiply` on a premultiplied colour /// lowers alpha, it does not darken.) -pub(super) fn menu_base() -> Color32 { Color32::from_rgb(11, 12, 13) } +pub(super) fn menu_base() -> Color32 { AGENT_SEMANTIC.menu_base } pub(super) fn menu_rim(t: Tokens) -> Color32 { t.card_border.lerp_to_gamma(t.text_dim, 0.38) } @@ -813,12 +1021,12 @@ pub(super) fn material_over(ui:&Ui, id:egui::Id, rect:egui::Rect, radius:f32, ga } fn material_fallback(gain:f32)->Color32 { - Color32::from_rgb(17,18,20).lerp_to_gamma(Color32::from_rgb(43,45,50),gain.clamp(0.0,1.0)*0.6) + AGENT_SEMANTIC.glass_rest.lerp_to_gamma(AGENT_SEMANTIC.glass_lit,gain.clamp(0.0,1.0)*0.6) } fn candidate_glass(ui: &Ui, rect: egui::Rect, radius: f32, slot: egui::layers::ShapeIdx) { let t = Tokens::get(ui.ctx()).agent(); - let rim = t.card_border.lerp_to_gamma(t.text_dim, 0.38); + let rim = menu_rim(t); ui.painter().set(slot, egui::Shape::Rect(egui::epaint::RectShape::new( rect, radius, t.field, Stroke::new(1.0, rim), egui::StrokeKind::Inside, ))); @@ -826,7 +1034,7 @@ fn candidate_glass(ui: &Ui, rect: egui::Rect, radius: f32, slot: egui::layers::S fn control_material(ui:&Ui, response:&Response, radius:f32, reduced:bool, selected:bool, slot:egui::layers::ShapeIdx) { let active=response.enabled() && (response.hovered() || response.has_focus()); - let strength=ui.ctx().animate_bool_with_time(response.id.with("material-focus"),active,if reduced {0.0} else {0.18}); + let strength=ui.ctx().animate_bool_with_time(response.id.with("material-focus"),active,if reduced {0.0} else {timing::MATERIAL as f32}); let gain=0.52*strength; material(ui,response.id,response.rect,radius,gain,slot); if selected && strength<=0.001 { @@ -869,7 +1077,7 @@ pub(super) fn surface(ui:&mut Ui, role:SurfaceRole, contents:impl FnOnce(&mut pub(super) fn surface_card(ui: &mut Ui, id: egui::Id, enabled: bool, reduced: bool, contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse { let enabled = enabled && ui.is_enabled(); let t = Tokens::get(ui.ctx()).agent(); - let frame = Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(12).inner_margin(12); + let frame = Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.card_border)).corner_radius(radius::CHIP as u8).inner_margin(space::MD as i8); let width = ui.available_width(); let mut prepared = frame.begin(ui); if width.is_finite() { prepared.content_ui.set_min_width((width - 26.0).max(0.0)); } @@ -882,7 +1090,7 @@ pub(super) fn surface_card(ui: &mut Ui, id: egui::Id, enabled: bool, reduced: // rect test so the card stays lit beneath it but not beneath a popup. let hovered = enabled && ui.rect_contains_pointer(rect) && ui.is_rect_visible(rect); let progress = if ui.is_rect_visible(rect) { - ui.ctx().animate_bool_with_time(id.with("surface-hover"), hovered, if reduced { 0.0 } else { 0.16 }) + ui.ctx().animate_bool_with_time(id.with("surface-hover"), hovered, if reduced { 0.0 } else { timing::HOVER as f32 }) } else { 0.0 }; material(ui,id,rect,12.0,progress*0.52,background); InnerResponse { inner: result, response } @@ -892,9 +1100,9 @@ pub(super) fn surface_card(ui: &mut Ui, id: egui::Id, enabled: bool, reduced: pub(super) fn dialog_heading(ui: &mut Ui, title: &str) -> bool { let t = Tokens::get(ui.ctx()).agent(); let close = ui.horizontal(|ui| { - ui.label(RichText::new(title).size(18.0).strong().color(t.text)); + ui.label(RichText::new(title).size(Type::TitleLg.size()).strong().color(t.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let response = icon_button(ui, "x", 28.0, false, "关闭"); + let response = icon_button(ui, "x", control::STANDARD, false, "关闭"); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "关闭")); response.clicked() }).inner @@ -962,7 +1170,7 @@ impl OverlayTransition { if reduced || !now.is_finite() { *self = Self { from: target, target, started: now, duration: 0.0 }; } else if self.target != target || now < self.started { - *self = Self { from: self.value(now), target, started: now, duration: if open { 0.22 } else { 0.16 } }; + *self = Self { from: self.value(now), target, started: now, duration: if open { timing::OVERLAY_IN } else { timing::OVERLAY_OUT } }; } let opacity = self.value(now).clamp(0.0, 1.0); OverlayVisual { render: open || opacity > 0.0, interactive: open, opacity } @@ -1048,7 +1256,7 @@ pub(super) fn modal(ctx: &Context, id: egui::Id, visual: OverlayVisual, reduced: if !visual.render { return None; } let opacity = if visual.opacity.is_finite() { visual.opacity.clamp(0.0, 1.0) } else { 1.0 }; Some(egui::Modal::new(id) - .backdrop_color(Color32::from_black_alpha(100).gamma_multiply(opacity)) + .backdrop_color(AGENT_SEMANTIC.backdrop.gamma_multiply(opacity)) .frame(Frame::NONE) .show(ctx, |ui| { material_frame(ui,overlay_frame(ctx,SurfaceRole::Dialog,opacity),|ui| { @@ -1085,7 +1293,7 @@ impl QuietRule { let state = ui.next_auto_id().with("quiet-state"); let active = enabled && ui.data(|data| data.get_temp::(state)).unwrap_or(false); let rise = if ui.style().animation_time == 0.0 { f32::from(active) } - else { ui.ctx().animate_bool_with_time(state, active, 0.12) }; + else { ui.ctx().animate_bool_with_time(state, active, timing::QUIET as f32) }; Some(Self { state, danger, rise }) } @@ -1110,6 +1318,50 @@ impl QuietRule { } } +/// 统一焦点环。线宽恒为 1pt、画在内侧;内缩与颜色只有下面六种规格,库内所有控件都走这里。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum FocusRing { + /// 常规控件:内缩 0.5pt,正文色。 + Control, + /// 叠在浅色实心主按钮上:内缩 0.5pt,按钮文字色。 + OnPrimary, + /// 叠在圆形发送钮上:内缩 1pt,按钮文字色。 + OnSend, + /// 叠在深色玻璃轨或无框行上:不内缩,次级文字色。 + OnGlass, + /// 普通分段轨上的选项:内缩 1pt,正文色。 + OnRail, + /// 玻璃分段轨上的选项:内缩 1pt,次级文字色。 + OnGlassRail, +} + +impl FocusRing { + fn place(self, t: &Tokens) -> (f32, Color32) { + match self { + Self::Control => (0.5, t.text), + Self::OnPrimary => (0.5, t.primary_text), + Self::OnSend => (1.0, t.primary_text), + Self::OnGlass => (0.0, t.text_dim), + Self::OnRail => (1.0, t.text), + Self::OnGlassRail => (1.0, t.text_dim), + } + } +} + +/// 键盘焦点落在 `response` 上时画一圈焦点环。布局与命中区域不变;不可见或窗口最小化时不画。 +pub(super) fn focus_ring(ui: &Ui, response: &Response, radius: f32, ring: FocusRing) { + focus_ring_at(ui, response.rect, radius, ring, response.has_focus()); +} + +/// `focus_ring` 的位置版:焦点状态由调用方给出(例如整块区域都是同一个焦点目标)。 +pub(super) fn focus_ring_at(ui: &Ui, rect: egui::Rect, radius: f32, ring: FocusRing, focused: bool) { + if !focused || super::agent_motion::hidden(ui, rect) { + return; + } + let (inset, color) = ring.place(&Tokens::get(ui.ctx()).agent()); + ui.painter().rect_stroke(rect.shrink(inset), radius, Stroke::new(1.0, color), egui::StrokeKind::Inside); +} + fn primary_button_fills(t: Tokens) -> (Color32, Color32, Color32) { // Interpolate opaque colours rather than multiplying alpha: the same // interaction must remain readable on the dock, menus and glass surfaces. @@ -1128,13 +1380,13 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: ButtonRole::Quiet | ButtonRole::QuietDanger => (t.text, Color32::TRANSPARENT, t.hover, t.pressed, Color32::TRANSPARENT), ButtonRole::Destructive => (t.danger, t.field, t.hover, t.pressed, t.field_border), }; - let galley = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(13.0), text); + let galley = ui.painter().layout_no_wrap(label.to_owned(), Type::Title.font_id(), text); let label_width = galley.size().x; let width = (label_width + ui.spacing().button_padding.x * 2.0).min(ui.max_rect().width().max(1.0)); let rule = QuietRule::new(ui, role, enabled); // Reserve the whole control in the parent layout before creating a style // scope: a zero-sized scope cannot wrap an already-painted child row. - let response = ui.allocate_ui_with_layout(Vec2::new(width, 34.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + let response = ui.allocate_ui_with_layout(Vec2::new(width, control::DEFAULT), egui::Layout::left_to_right(egui::Align::Center), |ui| { let widgets = &mut ui.style_mut().visuals.widgets; for (visual, background) in [ (&mut widgets.inactive, fill), @@ -1147,11 +1399,11 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: visual.bg_stroke = Stroke::new(1.0, border); visual.expansion = 0.0; } - let button=egui::Button::new(RichText::new(label).color(rule.as_ref().map_or(text, |rule| rule.text(t))).size(13.0)) - .corner_radius(9) + let button=egui::Button::new(RichText::new(label).color(rule.as_ref().map_or(text, |rule| rule.text(t))).size(Type::Title.size())) + .corner_radius(radius::CONTROL) .stroke(if role==ButtonRole::Secondary || role==ButtonRole::Destructive {Stroke::NONE} else {Stroke::new(1.0, border)}) .wrap_mode(egui::TextWrapMode::Truncate) - .min_size(Vec2::new(width, 34.0)); + .min_size(Vec2::new(width, control::DEFAULT)); let button=if role==ButtonRole::Secondary || role==ButtonRole::Destructive {button.fill(Color32::TRANSPARENT)} else {button}; ui.add_enabled(enabled,button) }).inner; @@ -1164,9 +1416,8 @@ pub(super) fn action_button(ui: &mut Ui, label: &str, role: ButtonRole, enabled: // The explicit constant-width frame prevents hover-driven layout shifts; // paint keyboard focus separately so a transparent Quiet border still has // a visible, equally sized focus indicator. - if enabled && response.has_focus() && ui.is_rect_visible(response.rect) { - let focus_color = if role == ButtonRole::Primary { t.primary_text } else { t.text }; - ui.painter().rect_stroke(response.rect.shrink(0.5), 9.0, Stroke::new(1.0, focus_color), egui::StrokeKind::Inside); + if enabled && response.has_focus() { + focus_ring(ui, &response, radius::CONTROL, if role == ButtonRole::Primary { FocusRing::OnPrimary } else { FocusRing::Control }); } response } @@ -1178,7 +1429,7 @@ pub(super) fn button(ui: &mut Ui, label: &str, primary: bool) -> Response { /// Inline object reference with independent locate and detach hit targets. /// Detaching is draft state only; the caller owns the actual canvas identity. pub(super) fn reference_chip_width(ui: &Ui, label: &str, max_width: f32) -> f32 { - let text_width = ui.painter().layout_no_wrap(label.to_owned(), egui::FontId::proportional(11.0), egui::Color32::WHITE).size().x; + let text_width = ui.painter().layout_no_wrap(label.to_owned(), Type::Caption.font_id(), egui::Color32::WHITE).size().x; let max_width = max_width.clamp(0.0, 144.0); (text_width + 48.0).clamp(48.0_f32.min(max_width), max_width) } @@ -1211,10 +1462,10 @@ fn reference_chip_core(ui: &mut Ui, icon: &str, label: &str, locate_name: Option let focused = locate.has_focus() || remove.has_focus(); let slot = super::agent_motion::reserve_background(ui); let gain = ui.ctx().animate_bool_with_time(locate.id.with("reference-light"), ui.is_enabled() && (hovered || focused), - if ui.style().animation_time == 0.0 { 0.0 } else { 0.18 }); - material(ui, locate.id, rect, 12.0, (gain * 0.40).max(pulse * 0.20), slot); + if ui.style().animation_time == 0.0 { 0.0 } else { timing::MATERIAL as f32 }); + material(ui, locate.id, rect, radius::CHIP, (gain * 0.40).max(pulse * 0.20), slot); if focused { - ui.painter().rect_stroke(rect, 12.0, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside); + focus_ring_at(ui, rect, radius::CHIP, FocusRing::OnGlass, true); } let swatch = egui::Rect::from_center_size(egui::pos2(rect.left() + 12.0, rect.center().y), vec2(16.0, 14.0)); if let Some(preview) = preview { @@ -1228,7 +1479,7 @@ fn reference_chip_core(ui: &mut Ui, icon: &str, label: &str, locate_name: Option crate::icons::paint(ui, swatch, icon, 10.0, t.icon); } let text_clip = egui::Rect::from_min_max(egui::pos2(rect.left() + 22.0, rect.top()), egui::pos2(remove_rect.left().max(rect.left() + 22.0), rect.bottom())); - ui.painter_at(text_clip).text(egui::pos2(rect.left() + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(11.0), t.text); + ui.painter_at(text_clip).text(egui::pos2(rect.left() + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, label, Type::Caption.font_id(), t.text); crate::icons::paint(ui, remove_rect.shrink(5.0), "x", 12.0, if remove.hovered() { t.text } else { t.icon }); if let Some(accessible_name) = locate_name { locate.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("定位引用:{accessible_name}"))); } remove.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, remove_name)); @@ -1263,7 +1514,8 @@ fn reference_chip_hover_over_editor_outputs_hand_cursor() { let mut targets = [egui::Rect::NOTHING; 2]; for frame in 0..5 { let events = if frame >= 1 { vec![egui::Event::PointerMoved(targets[if frame < 3 { 0 } else { 1 }].center())] } else { vec![] }; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 100.0))), events, ..Default::default() }, |ui| { + use crate::jiansun::test_support::SettleUi; + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 100.0))), events, ..Default::default() }, |ui| { let editor = ui.add(egui::TextEdit::singleline(&mut text).desired_width(200.0)); let mut chip = ui.new_child(egui::UiBuilder::new().id_salt("chip-test").max_rect(egui::Rect::from_min_size(editor.rect.min, vec2(88.0, 24.0)))); let (locate, remove) = reference_chip(&mut chip, "layers", "对象", "对象", 0.0, 72.0); @@ -1291,7 +1543,7 @@ fn menu_row(ui: &mut Ui, label: &str, selected: bool, enabled: bool, min_size: V visual.expansion = 0.0; } ui.add_enabled(enabled, egui::Button::new(()) - .left_text(RichText::new(label).size(13.0)) + .left_text(RichText::new(label).size(Type::Title.size())) .min_size(vec2(width, min_size.y)) .corner_radius(MENU_ITEM_RADIUS) .stroke(Stroke::NONE) @@ -1305,12 +1557,12 @@ fn menu_row(ui: &mut Ui, label: &str, selected: bool, enabled: bool, min_size: V } pub(super) fn menu_item(ui: &mut Ui, label: &str, enabled: bool) -> Response { - menu_row(ui, label, false, enabled, vec2(ui.available_width().max(0.0), 32.0), egui::Role::Button) + menu_row(ui, label, false, enabled, vec2(ui.available_width().max(0.0), control::MENU_ROW), egui::Role::Button) } /// Floating command menu surface shared by compact composer actions. pub(super) fn command_menu_frame(ctx: &Context) -> Frame { - surface_frame(ctx, SurfaceRole::Menu).corner_radius(12) + surface_frame(ctx, SurfaceRole::Menu).corner_radius(radius::CHIP) } /// A full-width native keyboard-accessible menu command with a real SVG icon. @@ -1329,12 +1581,12 @@ pub(super) fn command_menu_item(ui: &mut Ui, icon: &str, label: &str, enabled: b visual.expansion = 0.0; } let image = crate::icons::image(icon, 16.0, tint); - ui.add_enabled(enabled, egui::Button::image_and_text(image, RichText::new(label).size(13.0).color(if enabled { t.text } else { t.text_faint })) - .min_size(vec2(width, 36.0)).corner_radius(MENU_ITEM_RADIUS).stroke(Stroke::NONE).frame_when_inactive(false).truncate()) + ui.add_enabled(enabled, egui::Button::image_and_text(image, RichText::new(label).size(Type::Title.size()).color(if enabled { t.text } else { t.text_faint })) + .min_size(vec2(width, control::COMMAND_ROW)).corner_radius(MENU_ITEM_RADIUS).stroke(Stroke::NONE).frame_when_inactive(false).truncate()) }).inner; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); if enabled && response.has_focus() { - ui.painter().rect_stroke(response.rect.shrink(0.5), MENU_ITEM_RADIUS, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside); + focus_ring(ui, &response, f32::from(MENU_ITEM_RADIUS), FocusRing::OnGlass); } response } @@ -1349,16 +1601,16 @@ pub(super) fn icon_action_button(ui: &mut Ui, icon: &str, label: &str, compact: let t = Tokens::get(ui.ctx()).agent(); let image = crate::icons::image(icon, 16.0, if enabled { t.text } else { t.text_faint }); let button = if compact { egui::Button::image(image) } - else { egui::Button::image_and_text(image, RichText::new(label).size(13.0).color(t.text)) }; - let width = if compact { min_width.max(1.0) } else { min_width.max(28.0) }; + else { egui::Button::image_and_text(image, RichText::new(label).size(Type::Title.size()).color(t.text)) }; + let width = if compact { min_width.max(1.0) } else { min_width.max(control::STANDARD) }; let response = ui.scope(|ui| { if compact { ui.spacing_mut().button_padding = vec2(0.0, 0.0); } - ui.add_enabled(enabled, button.frame(false).min_size(vec2(width, 28.0)).truncate()) + ui.add_enabled(enabled, button.frame(false).min_size(vec2(width, control::STANDARD)).truncate()) }).inner; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); // Frameless, so focus needs the shared ring rather than a button frame. - if enabled && response.has_focus() && ui.is_rect_visible(response.rect) { - ui.painter().rect_stroke(response.rect.shrink(0.5), 8.0, Stroke::new(1.0, t.text), egui::StrokeKind::Inside); + if enabled && response.has_focus() { + focus_ring(ui, &response, 8.0, FocusRing::Control); } response } @@ -1378,9 +1630,9 @@ pub(super) fn send_action_button(ui: &mut Ui, id: egui::Id, _reduced: bool) -> R visual.bg_stroke = Stroke::NONE; visual.expansion = 0.0; } - let response = ui.add(egui::Button::image(crate::icons::image("navigation", 15.0, t.primary_text)).min_size(Vec2::splat(30.0)).corner_radius(15)); + let response = ui.add(egui::Button::image(crate::icons::image("navigation", icon::SEND, t.primary_text)).min_size(Vec2::splat(control::SEND)).corner_radius(control::SEND as u8 / 2)); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), "发送")); - if response.has_focus() { ui.painter().rect_stroke(response.rect.shrink(1.0), 14.0, Stroke::new(1.0, t.primary_text), egui::StrokeKind::Inside); } + focus_ring(ui, &response, control::SEND * 0.5 - 1.0, FocusRing::OnSend); response }).inner).inner } @@ -1393,16 +1645,57 @@ pub(super) fn selectable_galley_at(ui: &mut Ui, rect: egui::Rect, galley: std::s ui.put(rect, egui::Label::new(galley).selectable(true)) } +/// 用户消息气泡:按实际排版结果定尺寸,靠右,段落左对齐。`started` 给出时从那一刻逐字扩散入场, +/// 柔光是用户的琥珀色;`reduced` 为真时直接显示全文。气泡尺寸取全文的排版结果,入场过程中不变形。 +pub(super) fn user_bubble_with_reveal(ui: &mut Ui, text: &str, started: Option, reduced: bool) -> egui::Rect { + let t = Tokens::get(ui.ctx()).agent(); + let now = ui.input(|input| input.time); + let max_text = (ui.available_width() - 22.0 - 28.0).max(1.0); + let count = text.chars().count(); + let key = content_key((text, max_text.to_bits(), t.text)); + let mut galley = super::stitch_cache::settled_galley(ui, egui::Id::unique("stitch-user-bubble"), key, count, |fonts| { + fonts.layout(text.to_owned(), Type::Body.font_id(), t.text, max_text) + }); + let mut frame = RevealPaint::default(); + if let Some(started) = started.filter(|started| now - *started < reveal::duration(count)) { + let arrivals = reveal::staggered(text, started); + frame = animate_galley(&mut galley, &arrivals, now, reduced, true, reveal::RevealInk::user(t)); + } + let size = galley.size() + vec2(28.0, 24.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| { + let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover()); + let background = super::agent_motion::reserve_background(ui); + let glow = super::agent_motion::reserve_background(ui); + material(ui, response.id, rect, t.radius, 0.0, background); + let inset = rect.shrink2(vec2(14.0, 12.0)); + selectable_galley_at(ui, inset, galley.clone()); + // 尾韵光带与流头柔光垫在字形下面。 + if !frame.glow.is_empty() { + let mut shapes = std::mem::take(&mut frame.glow); + for shape in &mut shapes { + shape.translate(inset.min.to_vec2()); + } + ui.painter().set(glow, egui::Shape::Vec(shapes)); + } + if frame.entering || frame.glowing { + schedule(ui, rect, Pace::Full); + } else if frame.fading { + schedule(ui, rect, Pace::Idle); + } + rect + }).inner +} + pub(super) fn select_trigger(ui: &mut Ui, label: &str, width: f32, enabled: bool) -> Response { let t = Tokens::get(ui.ctx()).agent(); ui.add_enabled(enabled, egui::Button::new(()) - .left_text(RichText::new(label).size(13.0)) + .left_text(RichText::new(label).size(Type::Title.size())) .right_text(crate::icons::image("chevron-down", 12.0, t.text_dim)) - .min_size(vec2(width, 34.0)).corner_radius(12).truncate()) + .min_size(vec2(width, control::DEFAULT)).corner_radius(radius::CHIP).truncate()) } pub(super) fn select_option(ui: &mut Ui, label: &str, selected: bool, enabled: bool) -> Response { - select_option_sized(ui, label, selected, enabled, vec2(ui.available_width().max(0.0), 32.0)) + select_option_sized(ui, label, selected, enabled, vec2(ui.available_width().max(0.0), control::MENU_ROW)) } pub(super) fn select_option_sized(ui: &mut Ui, label: &str, selected: bool, enabled: bool, min_size: Vec2) -> Response { @@ -1441,7 +1734,7 @@ pub(super) fn halo_field(ui: &mut Ui, id: egui::Id, error: Option<&str>, reduced let t = Tokens::get(ui.ctx()).agent(); let frame = Frame::NONE.fill(t.field) .stroke(Stroke::new(1.0, if error.is_some() { t.danger } else { t.field_border })) - .corner_radius(9).inner_margin(Margin::symmetric(10, 8)); + .corner_radius(radius::CONTROL).inner_margin(Margin::symmetric(10, 8)); let mut prepared = frame.begin(ui); let light = super::agent_motion::reserve_background(&prepared.content_ui); prepared.content_ui.spacing_mut().interact_size.y = 16.0; @@ -1449,7 +1742,7 @@ pub(super) fn halo_field(ui: &mut Ui, id: egui::Id, error: Option<&str>, reduced let rect = frame.widget_rect(prepared.content_ui.min_rect()); let frame_response = prepared.end(ui); let focused=response.has_focus() || response.hovered() || frame_response.hovered(); - let strength=ui.ctx().animate_bool_with_time(id.with("field-material"),focused,if reduced {0.0} else {0.18}); + let strength=ui.ctx().animate_bool_with_time(id.with("field-material"),focused,if reduced {0.0} else {timing::MATERIAL as f32}); material(ui,id,rect.shrink(0.5),8.5,0.42*strength,light); if let Some(message) = error.filter(|message| !message.is_empty()) { status_chip(ui, message, StatusTone::Error); @@ -1461,8 +1754,9 @@ fn drop_halo_outline(ui: &Ui, id: egui::Id, rect: egui::Rect, radius: f32, activ let t = Tokens::get(ui.ctx()).agent(); let visible = rect.intersect(ui.clip_rect()); let time = ui.input(|input| input.time); - let pulse = if reduced { 0.5 } else { (0.5 + 0.5 * (time * std::f64::consts::TAU / 1.8).sin()) as f32 }; - let color = if active { Color32::from_rgb(162, 150, 247).lerp_to_gamma(Color32::from_rgb(85, 215, 226), pulse) } else { t.card_border }; + let pulse = if reduced { 0.5 } else { (0.5 + 0.5 * (time * std::f64::consts::TAU / timing::HALO_PERIOD).sin()) as f32 }; + let light = t.agent_light(); + let color = if active { light[0].lerp_to_gamma(light[1], pulse) } else { t.card_border }; if !rect.is_finite() || !visible.is_positive() || rect.width() <= 1.0 || rect.height() <= 1.0 { return color; } let radius = radius.max(0.5).min(rect.width().min(rect.height()) * 0.5); if active { @@ -1478,7 +1772,7 @@ fn drop_halo_outline(ui: &Ui, id: egui::Id, rect: egui::Rect, radius: f32, activ } if let Some(first) = path.first().copied() { path.push(first); } ui.painter().with_clip_rect(visible).extend(egui::Shape::dashed_line(&path, Stroke::new(1.0,color), 6.0,4.0)); - if active && !reduced { ui.ctx().request_repaint_after(std::time::Duration::from_millis(32)); } + if active && !reduced { schedule(ui, rect, Pace::Full); } color } @@ -1499,16 +1793,16 @@ pub(super) fn file_drop_zone(ui: &mut Ui, id: egui::Id, width: f32, drop_pointer if !visible.is_positive() { return response; } let active = enabled && drop_pointer.is_some_and(|point| visible.contains(point)); let time = ui.input(|input| input.time); - let pulse = if reduced { 0.5 } else { (0.5 + 0.5 * (time * std::f64::consts::TAU / 1.8).sin()) as f32 }; + let pulse = if reduced { 0.5 } else { (0.5 + 0.5 * (time * std::f64::consts::TAU / timing::HALO_PERIOD).sin()) as f32 }; let painter = ui.painter().with_clip_rect(visible); let background=painter.add(egui::Shape::Noop); let interacting=enabled && (active || response.hovered() || response.has_focus()); - let strength=ui.ctx().animate_bool_with_time(id.with("drop-material"),interacting,if reduced {0.0} else {0.18}); + let strength=ui.ctx().animate_bool_with_time(id.with("drop-material"),interacting,if reduced {0.0} else {timing::MATERIAL as f32}); material(ui,id,rect,12.0,0.52*strength,background); let color = drop_halo_outline(ui, id.with("rim"), rect, 12.0, active, reduced); let title = if active { "释放以上传图片" } else if rect.width() < 230.0 { "添加参考图" } else { "拖放图片,或点击添加参考图" }; let foreground = if enabled { t.text } else { t.text_faint }; - let galley = painter.layout_no_wrap(title.to_owned(), FontId::proportional(12.0), foreground); + let galley = painter.layout_no_wrap(title.to_owned(), Type::Meta.font_id(), foreground); let icon_size = if active && !reduced { 15.0 * (0.92 + 0.08 * pulse) } else { 15.0 }; let left = rect.center().x - (galley.size().x + 23.0) * 0.5; crate::icons::paint(ui, egui::Rect::from_center_size(egui::pos2(left + 7.5, rect.center().y), vec2(icon_size, icon_size)), "image", icon_size, if active { color } else if enabled { t.text_dim } else { t.text_faint }); @@ -1523,6 +1817,18 @@ pub(super) enum StatusTone { Error, } +/// 旧的三档状态色调,现有调用方仍在用。统一色调 `Tone` 可以直接转进来: +/// 成功、进行中归中性,待核查归警告,只有失败才是错误。 +impl From for StatusTone { + fn from(tone: Tone) -> Self { + match tone { + Tone::Failure => Self::Error, + Tone::Warning | Tone::Unknown => Self::Warning, + Tone::Quiet | Tone::Active | Tone::Success | Tone::Verified | Tone::Progress => Self::Neutral, + } + } +} + /// Displays the caller's real status; it does not infer progress or change task state. pub(super) fn status_label(ui: &mut Ui, text: &str, tone: StatusTone) -> Response { let t = Tokens::get(ui.ctx()).agent(); @@ -1531,12 +1837,12 @@ pub(super) fn status_label(ui: &mut Ui, text: &str, tone: StatusTone) -> Respons StatusTone::Warning => t.warning, StatusTone::Error => t.danger, }; - ui.add(egui::Label::new(RichText::new(text).color(color).size(13.0)).wrap()) + ui.add(egui::Label::new(RichText::new(text).color(color).size(Type::Title.size())).wrap()) } /// A compact, non-interactive label. Callers supply the actual state and copy. pub(super) fn status_chip(ui: &mut Ui, text: &str, tone: StatusTone) -> Response { - material_frame(ui,Frame::NONE.corner_radius(12).inner_margin(Margin::symmetric(8, 4)),|ui|status_label(ui,text,tone)).inner + material_frame(ui,Frame::NONE.corner_radius(radius::CHIP).inner_margin(Margin::symmetric(space::SM as i8, space::XS as i8)),|ui|status_label(ui,text,tone)).inner } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1546,7 +1852,25 @@ pub(super) enum StatusChipStyle { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum BadgeKind { Count, Unread, Adopted, Draft, Version, Ai, Warning, Running, Neutral } +pub(super) enum BadgeKind { + Count, + Unread, + Adopted, + Draft, + Version, + /// 目前只有测试在用;留给带 AI 标记的角标。 + #[cfg_attr(not(test), expect(dead_code, reason = "Halo 角标种类:留给带 AI 标记的角标,暂无生产调用方;接入后编译器会要求移除这一行"))] + Ai, + Warning, + Running, + Neutral, +} + +/// 徽标里文字的字号随徽标高度走:24pt 高的徽标是 11.76pt,最矮 10pt、最高 13pt。 +/// 测宽与绘制必须用同一个数,否则徽标会被量窄。 +fn badge_text_size(height: f32) -> f32 { + (height * 0.49).clamp(10.0, Type::Title.size()) +} impl BadgeKind { fn icon(self)->Option<&'static str> { @@ -1564,14 +1888,16 @@ impl BadgeKind { /// stable identity; the badge never creates, retries or cancels a task. pub(super) fn paint_badge(ui:&Ui,id:egui::Id,rect:egui::Rect,kind:BadgeKind,text:&str,reduced:bool) { if !rect.is_positive() || !ui.is_rect_visible(rect) {return;} + let t = Tokens::get(ui.ctx()).agent(); let radius=rect.height().min(rect.width())*0.5; let painter=ui.painter_at(rect.intersect(ui.clip_rect())); if kind==BadgeKind::Unread { let center=rect.center(); - painter.circle_filled(center,radius,Color32::from_rgba_unmultiplied(196,203,227,28)); - painter.circle_filled(center,radius*0.78,Color32::from_rgba_unmultiplied(213,218,235,45)); - painter.circle_filled(center,radius*0.57,Color32::from_rgb(222,222,237)); - painter.circle_filled(center-vec2(radius*0.16,radius*0.18),radius*0.24,Color32::WHITE); + let [halo, ring, dot, spark]=t.agent_semantic().unread_dot; + painter.circle_filled(center,radius,halo); + painter.circle_filled(center,radius*0.78,ring); + painter.circle_filled(center,radius*0.57,dot); + painter.circle_filled(center-vec2(radius*0.16,radius*0.18),radius*0.24,spark); return; } let slot=painter.add(egui::Shape::Noop); @@ -1579,8 +1905,7 @@ pub(super) fn paint_badge(ui:&Ui,id:egui::Id,rect:egui::Rect,kind:BadgeKind,text let moving=kind==BadgeKind::Running && !reduced; let phase=if moving {now as f32*2.4} else {0.0}; material(ui,id,rect,radius,0.0,slot); - let t=Tokens::get(ui.ctx()).agent(); - let size=(rect.height()*0.49).clamp(10.0,13.0); + let size=badge_text_size(rect.height()); let leading=kind.leading_width(); let mut job=egui::text::LayoutJob::simple_singleline(text.to_owned(),FontId::proportional(size),t.text); job.wrap.max_width=(rect.width()-leading-14.0).max(1.0); @@ -1598,35 +1923,54 @@ pub(super) fn paint_badge(ui:&Ui,id:egui::Id,rect:egui::Rect,kind:BadgeKind,text } } painter.galley(egui::pos2(left+leading,rect.center().y-galley.size().y*0.5),galley,t.text); - if moving {ui.ctx().request_repaint_after(std::time::Duration::from_millis(32));} + if moving {schedule(ui,rect,Pace::Full);} } pub(super) fn badge(ui:&mut Ui,id:egui::Id,kind:BadgeKind,text:&str,reduced:bool)->Response { - let width=ui.painter().layout_no_wrap(text.to_owned(),FontId::proportional(11.75),Color32::WHITE).size().x+kind.leading_width()+18.0; - badge_sized(ui,id,kind,text,reduced,width.max(24.0)) + let size = badge_text_size(control::ROW); + let width=ui.painter().layout_no_wrap(text.to_owned(),FontId::proportional(size),Color32::WHITE).size().x+kind.leading_width()+18.0; + badge_sized(ui,id,kind,text,reduced,width.max(control::ROW)) } /// `badge` with a caller-owned width. A waiting badge owns no dots and is /// narrower than a running one; where the two share a column the caller sets /// one width, and the letter stays centred in either. pub(super) fn badge_sized(ui:&mut Ui,id:egui::Id,kind:BadgeKind,text:&str,reduced:bool,width:f32)->Response { - let (rect,response)=ui.allocate_exact_size(vec2(width.min(ui.available_width().max(1.0)),24.0),egui::Sense::hover()); + let (rect,response)=ui.allocate_exact_size(vec2(width.min(ui.available_width().max(1.0)),control::ROW),egui::Sense::hover()); paint_badge(ui,id,rect,kind,text,reduced); response.widget_info(||egui::WidgetInfo::labeled(egui::Role::Label,true,text)); response } -/// Fixed-layout counterpart of `status_chip` for image/card overlays. The -/// caller owns the real status and bounds; this component owns the neutral -/// material and typography, and never adds a control or a running animation. -pub(super) fn paint_status_chip(ui: &Ui, t: &Tokens, rect: egui::Rect, text: &str, style: StatusChipStyle) { +impl BadgeKind { + /// 桥接兜底:旧调用方手里只有状态文案时,在这里认一次。 + /// 第 3 批把 `project_browser` 改成直接传 `BadgeKind` 之后删除。 + fn from_status_text(text: &str) -> Self { + match text {"已采纳"=>Self::Adopted,"草稿"=>Self::Draft,"状态未知"=>Self::Warning,_=>Self::Neutral} + } +} + +/// 旧签名垫片:按状态文案认角标类型,外观保持今天的中性灰底(`style` 沿用以往的忽略)。 +/// 新调用方请用 `paint_status_badge` 直接传类型与样式。 +pub(super) fn paint_status_chip(ui: &Ui, _t: &Tokens, rect: egui::Rect, text: &str, _style: StatusChipStyle) { + paint_status_badge(ui, rect, BadgeKind::from_status_text(text), text, StatusChipStyle::Muted, ui.style().animation_time == 0.0); +} + +/// 叠在图片或卡片上的状态角标(固定位置)。调用方给出真实状态与位置;这里只负责材质与排版, +/// 不添加控件,也不添加运行中的动画。`Contrast` 是浅色实心角标,给"有了结果"的状态用。 +pub(super) fn paint_status_badge(ui: &Ui, rect: egui::Rect, kind: BadgeKind, text: &str, style: StatusChipStyle, reduced: bool) { let painter=ui.painter(); if !rect.is_positive() || !rect.min.is_finite() || !rect.max.is_finite() || !rect.intersects(painter.clip_rect()) { return; } - let _=(t,style); - let kind=match text {"已采纳"=>BadgeKind::Adopted,"草稿"=>BadgeKind::Draft,"状态未知"=>BadgeKind::Warning,_=>BadgeKind::Neutral}; - paint_badge(ui,ui.scope_id().with(("status-material",text)),rect,kind,text,ui.style().animation_time==0.0); + if style == StatusChipStyle::Contrast { + let t = Tokens::get(ui.ctx()).agent(); + let galley = painter.layout_no_wrap(text.to_owned(), FontId::proportional(badge_text_size(rect.height())), t.primary_text); + painter.rect_filled(rect, rect.height().min(rect.width()) * 0.5, t.primary_bg); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, rect.center().y - galley.size().y * 0.5), galley, t.primary_text); + return; + } + paint_badge(ui,ui.scope_id().with(("status-material",text)),rect,kind,text,reduced); } /// A native search field with a keyboard-accessible clear control. The stable @@ -1655,13 +1999,14 @@ pub(super) fn search_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: let rect = frame.widget_rect(prepared.content_ui.min_rect()); let frame_response = prepared.end(ui); let focused=response.has_focus() || response.hovered() || frame_response.hovered(); - let strength=ui.ctx().animate_bool_with_time(id.with("search-material"),focused,if reduced {0.0} else {0.18}); + let strength=ui.ctx().animate_bool_with_time(id.with("search-material"),focused,if reduced {0.0} else {timing::MATERIAL as f32}); material(ui,id,rect,18.0,0.52*strength,light); response } /// The caller owns and persists the value. The switch has one native keyboard /// target and reports its real checkbox state to assistive technology. +#[cfg_attr(not(test), expect(dead_code, reason = "Halo 开关原语:库内先行并通过单测,暂无生产调用方;接入后编译器会要求移除这一行"))] pub(super) fn switch(ui: &mut Ui, id: egui::Id, value: &mut bool, label: &str, enabled: bool, reduced: bool) -> Response { ui.push_id(id, |ui| { let enabled = enabled && ui.is_enabled(); @@ -1669,7 +2014,7 @@ pub(super) fn switch(ui: &mut Ui, id: egui::Id, value: &mut bool, label: &str, e let t = Tokens::get(ui.ctx()).agent(); let width = ui.available_width().max(42.0); let label_color = if enabled { t.text } else { t.text_faint }; - let galley = ui.painter().layout(label.to_owned(), FontId::proportional(13.0), label_color, (width - 52.0).max(1.0)); + let galley = ui.painter().layout(label.to_owned(), Type::Title.font_id(), label_color, (width - 52.0).max(1.0)); let height = galley.size().y.max(32.0); let (rect, mut response) = ui.allocate_exact_size(vec2(width, height), egui::Sense::click()); if response.clicked() { @@ -1679,7 +2024,7 @@ pub(super) fn switch(ui: &mut Ui, id: egui::Id, value: &mut bool, label: &str, e response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, enabled, *value, label)); if ui.is_rect_visible(rect) { let amount = if reduced { if *value { 1.0 } else { 0.0 } } - else { ui.ctx().animate_bool_with_time(response.id.with("switch"), *value, 0.18) }; + else { ui.ctx().animate_bool_with_time(response.id.with("switch"), *value, timing::MATERIAL as f32) }; let track = egui::Rect::from_center_size(egui::pos2(rect.left() + 19.0, rect.center().y), vec2(34.0, 19.0)); let painter = ui.painter().with_clip_rect(rect); let slot=painter.add(egui::Shape::Noop); @@ -1715,13 +2060,13 @@ fn choice_option(ui: &mut Ui, label: &str, selected: bool, enabled: bool, widget visual.bg_stroke = Stroke::new(1.0, if selected { t.text_dim } else { t.field_border }); visual.expansion = 0.0; } - ui.add_enabled(enabled, egui::Button::selectable(selected, RichText::new(label).size(13.0).color(t.text)).fill(Color32::TRANSPARENT).stroke(Stroke::NONE).corner_radius(8).min_size(min_size)) + ui.add_enabled(enabled, egui::Button::selectable(selected, RichText::new(label).size(Type::Title.size()).color(t.text)).fill(Color32::TRANSPARENT).stroke(Stroke::NONE).corner_radius(8).min_size(min_size)) }).inner; control_material(ui,&response,8.0,ui.style().animation_time==0.0,selected,material_slot); // The glass light under a focused option changes too little to be seen; // a keyboard user picking between options needs a clear ring. - if enabled && response.has_focus() && ui.is_rect_visible(response.rect) { - ui.painter().rect_stroke(response.rect.shrink(0.5), 8.0, Stroke::new(1.0, t.text), egui::StrokeKind::Inside); + if enabled && response.has_focus() { + focus_ring(ui, &response, 8.0, FocusRing::Control); } response.widget_info(|| egui::WidgetInfo::selected(widget, enabled, selected, label)); response @@ -1748,7 +2093,7 @@ pub(super) const SEGMENT_GAP: f32 = 2.0; pub(super) const SEGMENT_MORE_WIDTH: f32 = 34.0; pub(super) fn segment_width(ui: &Ui, label: &str) -> f32 { - ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(13.0), Color32::WHITE).size().x + 24.0 + ui.painter().layout_no_wrap(label.to_owned(), Type::Title.font_id(), Color32::WHITE).size().x + 24.0 } fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], selected: usize, reduced: bool, glass: bool, overflow: Option) -> HaloSegmented { @@ -1757,7 +2102,7 @@ fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], let frame = if glass { Frame::NONE.corner_radius(20).inner_margin(3).stroke(Stroke::new(1.0, Color32::TRANSPARENT)) } else { - Frame::NONE.fill(t.field).corner_radius(12).inner_margin(3) + Frame::NONE.fill(t.field).corner_radius(radius::CHIP).inner_margin(3) }; let mut prepared = frame.begin(ui); let background = super::agent_motion::reserve_background(&prepared.content_ui); @@ -1772,8 +2117,8 @@ fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], for (index, (label, enabled)) in options.iter().copied().enumerate() { let enabled = enabled && ui.is_enabled(); let width = segment_width(ui, label).min(option_width).max(1.0); - let button = egui::Button::new(RichText::new(label).size(13.0).color(if enabled { t.text } else { t.text_faint })) - .frame(false).min_size(vec2(width, 32.0)).truncate(); + let button = egui::Button::new(RichText::new(label).size(Type::Title.size()).color(if enabled { t.text } else { t.text_faint })) + .frame(false).min_size(vec2(width, control::MENU_ROW)).truncate(); let response = ui.add_enabled(enabled, button); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, enabled, selected == index, label)); if response.clicked() { chosen = Some(index); } @@ -1781,7 +2126,7 @@ fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], } if let Some(enabled) = overflow { let button = egui::Button::image(crate::icons::image("ellipsis", 16.0, t.text)) - .frame(false).min_size(vec2(SEGMENT_MORE_WIDTH, 32.0)); + .frame(false).min_size(vec2(SEGMENT_MORE_WIDTH, control::MENU_ROW)); let response = ui.add_enabled(enabled, button).on_hover_text("更多图位"); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, "更多图位")); more = Some(response); @@ -1814,7 +2159,7 @@ fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], } if let Some(target) = responses.get(chosen.unwrap_or(selected)).map(|response| response.rect) { let target = target.translate(-rect.min.to_vec2()); - let sample = |axis: &str, value: f32| ui.ctx().animate_value_with_time(id.with(axis), value, if reduced { 0.0 } else { 0.22 }); + let sample = |axis: &str, value: f32| ui.ctx().animate_value_with_time(id.with(axis), value, if reduced { 0.0 } else { timing::NATIVE }); let min = egui::pos2(sample("x", target.min.x), sample("y", target.min.y)) + rect.min.to_vec2(); let size = vec2(sample("width", target.width()), sample("height", target.height())); let selection = egui::Rect::from_min_size(min, size); @@ -1831,9 +2176,9 @@ fn segmented_control_inner(ui: &mut Ui, id: egui::Id, options: &[(&str, bool)], // Keyboard focus draws the same kind of ring on either rail. Arrow keys // move between segments, so the ring is how a keyboard user sees which // segment is next; a frameless button shows nothing by itself. - let (radius, focus) = if glass { (15.0, t.text_dim) } else { (9.0, t.text) }; + let (radius, ring) = if glass { (15.0, FocusRing::OnGlassRail) } else { (9.0, FocusRing::OnRail) }; for response in responses.iter().chain(more.iter()).filter(|response| response.has_focus()) { - ui.painter().rect_stroke(response.rect.shrink(1.0), radius, Stroke::new(1.0, focus), egui::StrokeKind::Inside); + focus_ring(ui, response, radius, ring); } HaloSegmented { responses, selected: chosen, more } } @@ -1848,10 +2193,9 @@ pub(super) fn paint_generation_placeholder(ui: &mut Ui, response: &Response, rec candidate_glass(ui, rect, radius, background); let light = super::agent_motion::reserve_background(ui); super::glow_pill::background(ui, response.id, rect, radius, 0.16 * gain, light); - if response.has_focus() { - ui.painter().rect_stroke(rect, radius, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside); - } - let text = ui.painter().layout_no_wrap("生成图片".into(), FontId::proportional(14.0), t.text); + focus_ring_at(ui, rect, radius, FocusRing::OnGlass, response.has_focus()); + + let text = ui.painter().layout_no_wrap("生成图片".into(), Type::Body.font_id(), t.text); let icon_size = 16.0; let gap = 7.0; let visible = ui.clip_rect().intersect(rect); @@ -1879,7 +2223,7 @@ pub(super) fn segmented_option_sized(ui: &mut Ui, label: &str, selected: bool, e } pub(super) fn toggle_option(ui: &mut Ui, label: &str, selected: bool, enabled: bool) -> Response { - toggle_option_sized(ui, label, selected, enabled, vec2(0.0, 32.0)) + toggle_option_sized(ui, label, selected, enabled, vec2(0.0, control::MENU_ROW)) } pub(super) fn toggle_option_sized(ui: &mut Ui, label: &str, selected: bool, enabled: bool, min_size: Vec2) -> Response { @@ -1892,16 +2236,16 @@ pub(super) fn filter_chip(ui: &mut Ui, label: &str, selected: bool, enabled: boo let enabled = enabled && ui.is_enabled(); let t = Tokens::get(ui.ctx()).agent(); let background = super::agent_motion::reserve_background(ui); - let width = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(13.0), t.text).size().x + 20.0; - let response = ui.allocate_ui_with_layout(vec2(width, 34.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + let width = ui.painter().layout_no_wrap(label.to_owned(), Type::Title.font_id(), t.text).size().x + 20.0; + let response = ui.allocate_ui_with_layout(vec2(width, control::DEFAULT), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.spacing_mut().button_padding = vec2(10.0, 4.0); - ui.spacing_mut().interact_size.y = 28.0; - ui.add_enabled(enabled, egui::Button::new(RichText::new(label).size(13.0).color(if enabled { t.text } else { t.text_faint })) - .frame(false).wrap_mode(egui::TextWrapMode::Extend).min_size(vec2(width, 34.0))) + ui.spacing_mut().interact_size.y = control::STANDARD; + ui.add_enabled(enabled, egui::Button::new(RichText::new(label).size(Type::Title.size()).color(if enabled { t.text } else { t.text_faint })) + .frame(false).wrap_mode(egui::TextWrapMode::Extend).min_size(vec2(width, control::DEFAULT))) }).inner; response.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, enabled, selected, label)); let hover = if ui.is_rect_visible(response.rect) { - ui.ctx().animate_bool_with_time(response.id.with("filter-hover"), enabled && response.hovered(), if reduced { 0.0 } else { 0.16 }) + ui.ctx().animate_bool_with_time(response.id.with("filter-hover"), enabled && response.hovered(), if reduced { 0.0 } else { timing::HOVER as f32 }) } else { 0.0 }; let base = if selected { t.pressed } else { t.field }; let fill = base.lerp_to_gamma(t.hover, hover * 0.5); @@ -1923,7 +2267,7 @@ pub(super) fn progress(ui: &mut Ui, id: egui::Id, label: &str, fraction: Option< let known = valid_progress(fraction); let title = known.map_or_else(|| label.to_owned(), |value| format!("{label} · {:.0}%", value * 100.0)); let t = Tokens::get(ui.ctx()).agent(); - ui.label(RichText::new(title).size(12.0).color(t.text_dim)); + ui.label(RichText::new(title).size(Type::Meta.size()).color(t.text_dim)); progress_bar(ui, id.with("bar"), label, known, reduced) }).inner } @@ -1957,7 +2301,7 @@ pub(super) fn progress_bar_tinted(ui: &mut Ui, id: egui::Id, label: &str, fracti let segment = rect.width() * 0.3; let x = egui::lerp(rect.left()..=(rect.right() - segment), phase); painter.rect_filled(egui::Rect::from_min_size(egui::pos2(x, rect.top()), vec2(segment, rect.height())), 3.0, fill); - if !reduced { ui.ctx().request_repaint_after(std::time::Duration::from_millis(33)); } + if !reduced { schedule(ui, rect, Pace::Full); } } } response @@ -2030,6 +2374,9 @@ pub(super) fn ui_fonts_ready(ui: &Ui) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::jiansun::test_support::SettleUi; + use super::super::stitch_state::tool_glyph; + use super::super::stitch_timeline::ToolGroupHead; /// Exercise the real lazy system-font loader until both the actual CJK /// glyph coverage and the font definitions/measurements are stable. @@ -2037,7 +2384,7 @@ mod tests { let mut previous = None; for frame in 0..16 { let mut sample = None; - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), ..Default::default() }, |ui| { ui.label("编辑"); let font = FontId::proportional(13.0); let galley = ui.painter().layout_no_wrap("编辑".into(), font.clone(), Color32::WHITE); @@ -2088,7 +2435,7 @@ mod tests { #[test] fn reduced_motion_is_scoped_and_preserves_native_style() { let ctx = Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let native = ui.style().animation_time; scope_with_motion(ui, true, |ui| assert_eq!(ui.style().animation_time, 0.0)); assert_eq!(ui.style().animation_time, native); @@ -2101,7 +2448,7 @@ mod tests { fn switch_only_changes_real_value_on_enabled_click() { fn render(ctx: &Context, value: &mut bool, enabled: bool, time: f64, events: Vec) -> Response { let mut response = None; - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 100.0))), time: Some(time), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 100.0))), time: Some(time), events, ..Default::default() }, |ui| { response = Some(scope_with_motion(ui, true, |ui| switch(ui, egui::Id::unique("reduce"), value, "减少动态效果", enabled, true)).inner); }); response.unwrap() @@ -2129,7 +2476,7 @@ mod tests { #[test] fn choice_sizes_preserve_caller_owned_hit_targets() { let ctx = Context::default(); - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 200.0))), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 200.0))), ..Default::default() }, |ui| { scope(ui, |ui| { let source = segmented_option_sized(ui, "产品库", true, true, vec2(92.0, 28.0)); assert!(source.rect.width() >= 92.0 && source.rect.height() >= 28.0); @@ -2170,7 +2517,7 @@ mod tests { fn search_clear_reports_a_change_and_restores_focus_to_the_same_input() { fn render(ctx: &Context, query: &mut String, time: f64, events: Vec) -> Response { let mut result = None; - let _ = ctx.run_ui(egui::RawInput { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), time: Some(time), events, @@ -2206,27 +2553,35 @@ mod tests { #[test] fn response_arrivals_keep_independent_batches_across_markdown_closure() { + // 同一批到达的字按每字 15ms 铺开;此前已经显示的字保留自己的到达时间。 + let step = reveal::STEP; let mut state = ResponseArrival::default(); response_arrivals(&mut state, "**中文", 0.0, true); + assert_eq!(state.arrivals, vec![0.0, step, 2.0 * step, 3.0 * step]); response_arrivals(&mut state, "中文新", 0.1, true); + assert_eq!(state.arrivals, vec![2.0 * step, 3.0 * step, 0.1], "kept characters keep their arrival; the new one gets its own"); response_arrivals(&mut state, "中文新词", 0.2, true); - assert_eq!(state.arrivals, vec![0.0, 0.0, 0.1, 0.2]); + assert_eq!(state.arrivals, vec![2.0 * step, 3.0 * step, 0.1, 0.2]); response_arrivals(&mut state, "中文新词e\u{301}", 0.3, true); - assert_eq!(state.arrivals[4], state.arrivals[5]); + assert_eq!(state.arrivals[4], state.arrivals[5], "a combining mark arrives together with its base letter"); + assert!((state.rest_at - (0.3 + reveal::REST_AFTER)).abs() < 1e-9, "the reply settles a fixed while after its last arrival"); let mut emoji = ResponseArrival::default(); response_arrivals(&mut emoji, "👩", 1.0, true); response_arrivals(&mut emoji, "👩\u{200d}", 1.1, true); response_arrivals(&mut emoji, "👩\u{200d}💻🇨", 1.2, true); response_arrivals(&mut emoji, "👩\u{200d}💻🇨🇳", 1.3, true); - assert_eq!(emoji.arrivals, vec![1.0, 1.1, 1.2, 1.2, 1.3]); + assert_eq!(emoji.arrivals, vec![1.0, 1.1, 1.2, 1.2 + step, 1.3]); let mut long = ResponseArrival::default(); response_arrivals(&mut long, &"甲".repeat(65_000), 0.0, true); response_arrivals(&mut long, &"乙".repeat(65_000), 1.0, true); assert_eq!(long.arrivals.len(), 65_000); - assert!(long.arrivals.iter().all(|time| *time == 1.0)); + assert!(long.arrivals.iter().all(|time| *time >= 1.0)); + assert!(long.arrivals.windows(2).all(|pair| pair[0] < pair[1]), "a rewritten tail still spreads out in order"); + assert!(long.arrivals[64_999] - 1.0 <= reveal::MAX_SPAN + 1e-9, "and never lags more than the span cap"); let mut history = ResponseArrival::default(); response_arrivals(&mut history, "历史回复", 5.0, false); - assert!(history.arrivals.iter().all(|time| *time <= 4.78)); + assert!(history.arrivals.iter().all(|time| *time <= 5.0 - reveal::SETTLED_AGE + 1e-9)); + assert!(history.rest_at < 5.0, "history is settled the moment it first appears"); assert!((response_ease(0.0)).abs() < 0.001); assert!((response_ease(1.0) - 1.0).abs() < 0.001); assert!((response_caret_opacity(0.0, false) - 1.0).abs() < 0.001); @@ -2239,29 +2594,31 @@ mod tests { response_arrivals(&mut words, "hel", 1.0, true); response_arrivals(&mut words, "hello 中", 1.1, true); response_arrivals(&mut words, "hello 中文 world", 1.4, true); - assert_eq!(&words.arrivals[..5], &[1.0, 1.0, 1.0, 1.1, 1.1], "new suffix keeps its own arrival without altering the prefix"); - assert_eq!(words.arrivals[6], 1.1); - assert_eq!(words.arrivals[7], 1.4, "Chinese graphemes remain independent"); - assert!(words.arrivals[9..].iter().all(|time| *time == 1.4)); + assert_eq!(&words.arrivals[..7], &[1.0, 1.0 + step, 1.0 + 2.0 * step, 1.1, 1.1 + step, 1.1 + 2.0 * step, 1.1 + 3.0 * step], + "a new suffix staggers from its own arrival without altering the prefix"); + assert_eq!(&words.arrivals[7..], &[1.4, 1.4 + step, 1.4 + 2.0 * step, 1.4 + 3.0 * step, 1.4 + 4.0 * step, 1.4 + 5.0 * step, 1.4 + 6.0 * step], + "Chinese graphemes remain independent"); let mut accented = ResponseArrival::default(); response_arrivals(&mut accented, "caf", 2.0, true); - response_arrivals(&mut accented, "café 中", 2.1, true); - response_arrivals(&mut accented, "café 中文", 2.2, true); - assert_eq!(&accented.arrivals[..4], &[2.0, 2.0, 2.0, 2.1]); - assert_eq!(accented.arrivals[5], 2.1); - assert_eq!(accented.arrivals[6], 2.2); + // 重音写成"基字加组合符号"两个码点:它要和基字同时到达,所以不写字面上已被合并成单码点的 é。 + response_arrivals(&mut accented, "cafe\u{301} 中", 2.1, true); + response_arrivals(&mut accented, "cafe\u{301} 中文", 2.2, true); + assert_eq!(&accented.arrivals[..4], &[2.0, 2.0 + step, 2.0 + 2.0 * step, 2.1]); + assert_eq!(accented.arrivals[4], 2.1, "the combining acute arrives with its base letter"); + assert_eq!(&accented.arrivals[5..], &[2.1 + step, 2.1 + 2.0 * step, 2.2]); let mut combining = ResponseArrival::default(); response_arrivals(&mut combining, "nai", 3.0, true); response_arrivals(&mut combining, "nai\u{308}ve", 3.1, true); - assert_eq!(combining.arrivals, vec![3.0, 3.0, 3.0, 3.1, 3.1, 3.1]); + assert_eq!(combining.arrivals, vec![3.0, 3.0 + step, 3.0 + 2.0 * step, 3.1, 3.1 + step, 3.1 + 2.0 * step]); let mut replacement = ResponseArrival::default(); response_arrivals(&mut replacement, "abczzz", 4.0, true); response_arrivals(&mut replacement, "aazz", 4.1, true); - assert_eq!(replacement.arrivals, vec![4.0, 4.1, 4.1, 4.1], "a later matching letter cannot borrow an unrelated old arrival"); + assert_eq!(replacement.arrivals, vec![4.0, 4.1, 4.1 + step, 4.1 + 2.0 * step], "a later matching letter cannot borrow an unrelated old arrival"); let mut appended = ResponseArrival::default(); response_arrivals(&mut appended, "中Hel", 6.0, true); response_arrivals(&mut appended, "中Hello文", 6.5, true); - assert_eq!(appended.arrivals, vec![6.0, 6.0, 6.0, 6.0, 6.5, 6.5, 6.5], "expired prefix stays settled and every new code point gets its actual arrival"); + assert_eq!(appended.arrivals, vec![6.0, 6.0 + step, 6.0 + 2.0 * step, 6.0 + 3.0 * step, 6.5, 6.5 + step, 6.5 + 2.0 * step], + "an expired prefix stays settled and every new code point gets its actual arrival"); } #[test] @@ -2271,11 +2628,11 @@ mod tests { ctx.data_mut(|data| data.insert_temp(id, ResponseArrival { rendered: "前文abc".into(), arrivals: vec![0.0, 0.0, 0.1, 0.2, 0.3], ..Default::default() })); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| prepare_final_handoff(ui, id, "abc")); + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| prepare_final_handoff(ui, id, "abc")); let state = ctx.data(|data| data.get_temp::(id)).unwrap(); assert_eq!(state.rendered, "abc"); assert_eq!(state.arrivals, vec![0.1, 0.2, 0.3]); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| prepare_final_handoff(ui, id, "ab")); + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| prepare_final_handoff(ui, id, "ab")); let state = ctx.data(|data| data.get_temp::(id)).unwrap(); assert_eq!(state.rendered, "abc", "non-suffix updates are handled by the normal prefix path"); } @@ -2290,7 +2647,7 @@ mod tests { assert_eq!(loader_dot_opacity(0.5, 2, false, false), 0.5); let ctx = Context::default(); let positions = |time| { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| ai_loader(ui, egui::Id::unique("loader"), true, false)); + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| ai_loader(ui, egui::Id::unique("loader"), true, false)); output.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Circle(circle) => Some((circle.center, circle.radius)), _ => None }).collect::>() }; assert_eq!(positions(0.1), positions(0.5)); @@ -2301,7 +2658,7 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); for (status, elapsed, expected) in [("started", None, "进行中"), ("completed", Some("耗时 1.3 秒"), "已完成"), ("failed", None, "失败"), ("unknown", None, "状态未知")] { - let output = ctx.run_ui(egui::RawInput::default(), |ui| task_row(ui, egui::Id::unique("task"), "settings", "读取项目规则", status, elapsed, true)); + let output = ctx.settle_ui(egui::RawInput::default(), |ui| task_row(ui, egui::Id::unique("task"), "settings", "读取项目规则", status, elapsed, true)); let texts: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Text(text) => Some(text.galley.text()), _ => None }).collect(); assert!(texts.contains(&"读取项目规则") && texts.contains(&expected)); assert_eq!(texts.iter().any(|text| text.contains("耗时")), elapsed.is_some()); @@ -2313,7 +2670,7 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let t = Tokens::get(&ctx).agent(); - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() }, |ui| { scope_with_motion(ui, false, |ui| { let interaction_height = ui.spacing().interact_size.y; task_row(ui, egui::Id::unique("compact-badge"), "check", "读取画布", "completed", Some("耗时 1.3 秒"), false); @@ -2335,7 +2692,7 @@ mod tests { let ctx = Context::default(); ctx.set_pixels_per_point(ppp); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 200.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 200.0))), ..Default::default() }, |ui| { task_row(ui, egui::Id::unique("baseline-check"), "search", "读取画布", "completed", Some("耗时 27 毫秒"), true); }); let find = |wanted| output.shapes.iter().find_map(|shape| match &shape.shape { @@ -2362,7 +2719,7 @@ mod tests { fn narrow_task_duration_is_one_visible_line() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 200.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 200.0))), ..Default::default() }, |ui| { ui.set_width(250.0); task_row(ui, egui::Id::unique("narrow-duration"), "search", "读取项目规则", "completed", Some("耗时 27 毫秒"), true); }); @@ -2381,7 +2738,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); crate::cjk_fonts::install_system_provider_for_tests(&ctx); let mut first_id = None; - ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))), ..Default::default() }, |ui| { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))), ..Default::default() }, |ui| { ui.set_width(100.0); let group = segmented_control(ui, egui::Id::unique("test-segments"), &[("详情", true), ("主图", false), ("SKU", true)], 0, true); assert_eq!(group.responses.len(), 3); @@ -2390,7 +2747,7 @@ mod tests { }).textures_delta.clear(); ctx.memory_mut(|memory| memory.request_focus(first_id.unwrap())); let mut choice = None; - ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))), events: vec![egui::Event::Key { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 300.0))), events: vec![egui::Event::Key { key: egui::Key::ArrowRight, physical_key: Some(egui::Key::ArrowRight), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE, }], ..Default::default() }, |ui| { ui.set_width(100.0); @@ -2404,7 +2761,7 @@ mod tests { let ctx = Context::default(); let sample = |time: f64, selected, reduced| { let mut targets = Vec::new(); - let mut output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let mut output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { ui.set_width(270.0); let rail = candidate_segments(ui, egui::Id::unique("glass-test"), &[("Wood", true), ("Finish", true)], selected, reduced, Some(true)); let more = rail.more.expect("overflow button"); @@ -2434,13 +2791,13 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let mut id = None; - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { id = Some(filter_chip(ui, "mm", false, true, true).id); assert!(!filter_chip(ui, "cm", false, false, true).enabled()); }); ctx.memory_mut(|memory| memory.request_focus(id.unwrap())); let mut clicked = false; - let output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::Key { + let output = ctx.settle_ui(egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Space, physical_key: Some(egui::Key::Space), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE, }], ..Default::default() }, |ui| { let response = filter_chip(ui, "mm", false, true, true); @@ -2461,7 +2818,7 @@ mod tests { let card_rect = std::cell::Cell::new(egui::Rect::NOTHING); let clicked = std::cell::Cell::new(false); let render = |events: Vec| { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { let card = surface_card(ui, egui::Id::unique("card"), true, true, |ui| { let t = Tokens::get(ui.ctx()).agent(); let galley = ui.painter().layout_no_wrap("编辑".to_owned(), FontId::proportional(13.0), t.text); @@ -2501,7 +2858,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); settle_test_cjk_font(&ctx); let observed = std::cell::Cell::new((egui::Rect::NOTHING, false, false)); - let render = |events: Vec| ctx.run_ui(egui::RawInput { + let render = |events: Vec| ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { let response = action_button(ui, "编辑", role, true); @@ -2531,7 +2888,7 @@ mod tests { settle_test_cjk_font(&ctx); let measured = std::cell::Cell::new((egui::Rect::NOTHING, 0.0_f32, 0.0_f32)); let render = |events: Vec| { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { let t = Tokens::get(ui.ctx()).agent(); let galley = ui.painter().layout_no_wrap("编辑".to_owned(), FontId::proportional(13.0), t.text); let label_width = galley.size().x; @@ -2632,7 +2989,7 @@ mod tests { let hover_fill = material_fallback(0.52); let render = |pointer: Option, overlay: bool| { let events = pointer.map_or_else(Vec::new, |position| vec![egui::Event::PointerMoved(position)]); - ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events, ..Default::default() }, |ui| { let card = surface_card(ui, egui::Id::unique("hover-card"), true, true, |ui| action_button(ui, "编辑", ButtonRole::Quiet, true)); child_rect.set(card.inner.rect); if overlay { @@ -2661,7 +3018,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let t = Tokens::get(&ctx).agent(); let mut selected_rect = egui::Rect::NOTHING; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 200.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(240.0, 200.0))), ..Default::default() }, |ui| { ui.set_width(120.0); let selected = select_option_sized(ui, "一个很长的产品花色名称需要截断", true, true, vec2(120.0, 28.0)); selected_rect = selected.rect; @@ -2685,7 +3042,7 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let target = egui::pos2(30.0, 30.0); for pressed in [true, false] { - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events: vec![ + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), events: vec![ egui::Event::PointerMoved(target), egui::Event::PointerButton { pos: target, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, ], ..Default::default() }, |ui| { let response = file_drop_zone(ui, egui::Id::unique("disabled-drop"), 200.0, Some(target), false, false); @@ -2701,12 +3058,12 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let mut remove_rect = egui::Rect::NOTHING; - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { remove_rect = attachment_reference_chip(ui, "参考图片.png").rect; }); let body = egui::pos2(remove_rect.left() - 12.0, remove_rect.center().y); for pressed in [true, false] { - let _ = ctx.run_ui(egui::RawInput { events: vec![egui::Event::PointerMoved(body), egui::Event::PointerButton { + let _ = ctx.settle_ui(egui::RawInput { events: vec![egui::Event::PointerMoved(body), egui::Event::PointerButton { pos: body, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE, }], ..Default::default() }, |ui| { assert!(!attachment_reference_chip(ui, "参考图片.png").clicked()); @@ -2719,7 +3076,7 @@ mod tests { let ctx=Context::default(); crate::PhotocraftApp::setup_context(&ctx,crate::theme::ThemeKind::ProMedium); for width in [180.0,220.0] { - let output=ctx.run_ui(egui::RawInput::default(),|ui| { + let output=ctx.settle_ui(egui::RawInput::default(),|ui| { scope(ui,|ui| { ui.set_width(width); let left=ui.cursor().min.x; @@ -2743,7 +3100,7 @@ mod tests { #[test] fn response_draws_single_galley_and_caret_converges() { fn render(ctx: &Context, time: f64, text: &str, streaming: bool, reduced: bool) -> egui::FullOutput { - ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), time: Some(time), ..Default::default() }, |ui| { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), time: Some(time), ..Default::default() }, |ui| { streaming_reply(ui, egui::Id::unique("response-test"), text, streaming, reduced); }) } @@ -2751,28 +3108,32 @@ mod tests { crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); render(&ctx, 0.0, "A, B", true, false); let animated = render(&ctx, 0.05, "A, B", true, false); - assert_eq!(animated.shapes.iter().filter(|shape| matches!(&shape.shape, egui::Shape::Mesh(_))).count(), 0, "no shadow samples"); - let drawn = animated.shapes.iter().filter_map(|shape| match &shape.shape { egui::Shape::Text(text) => Some(text), _ => None }).next_back().unwrap(); - let row = &drawn.galley.rows[0]; + // 回复永远只有一个字形 galley;柔光是另外的、有界的渐变网格(一行文字至多一团流头加一条光带)。 + let drawn = reply_text_shapes(&animated, "A, B"); + assert_eq!(drawn.len(), 1); + assert!((1..=2).contains(&glow_mesh_count(&animated)), "a single line carries at most one halo and one band: {}", glow_mesh_count(&animated)); + let row = &drawn[0].galley.rows[0]; let alpha = |i: usize| row.visuals.mesh.vertices[row.glyphs[i].first_vertex as usize].color.a(); assert!(alpha(0) < alpha(1), "incoming letters fade while punctuation stays static"); + assert!(alpha(3) < alpha(0), "a later character of the same batch starts later: 15ms a character"); let finished = render(&ctx, 0.06, "A, B", false, false); - assert_eq!(finished.shapes.iter().filter(|shape| matches!(&shape.shape, egui::Shape::Mesh(_))).count(), 0); - let caret_count = |output: &egui::FullOutput| output.shapes.iter().filter(|shape| match &shape.shape { - egui::Shape::Rect(rect) => rect.rect.width() <= 2.0 && rect.rect.height() > 2.0 && rect.corner_radius.nw > 0, - _ => false, - }).count(); + assert_eq!(reply_text_shapes(&finished, "A, B").len(), 1); + let caret_count = |output: &egui::FullOutput| { + output.shapes.iter().filter(|shape| matches!(&shape.shape, egui::Shape::Rect(rect) if rect.rect.width() <= 2.0 && rect.rect.height() > 2.0 && rect.corner_radius.nw > 0)).count() + }; assert_eq!(caret_count(&animated), 1); assert_eq!(caret_count(&finished), 1, "the caret fades out after handoff"); assert_eq!(caret_count(&render(&ctx, 0.23, "A, B", false, false)), 0, "caret exit completes within 160ms"); - let settled = render(&ctx, 1.0, "A, B", false, false); - assert_eq!(caret_count(&settled), 0); + let resting = render(&ctx, 4.0, "A, B", false, false); + assert_eq!(caret_count(&resting), 0); + assert_eq!(glow_mesh_count(&resting), 0, "a settled reply draws no glow"); + assert_eq!(super::super::agent_motion::requested_delay(&resting), None, "and asks for no repaint at all"); let fresh = Context::default(); crate::PhotocraftApp::setup_context(&fresh, crate::theme::ThemeKind::ProMedium); let history = render(&fresh, 2.0, "历史回复", false, false); - assert_eq!(history.shapes.iter().filter(|shape| matches!(&shape.shape, egui::Shape::Mesh(_))).count(), 0, "first render of history is settled"); + assert_eq!(glow_mesh_count(&history), 0, "first render of history is settled"); assert_eq!(caret_count(&history), 0); - for c in ", :«»؛؟;।「」—…".chars() { + for c in ", :«»؛؟؛।「」—…".chars() { assert!(response_static_character(c), "punctuation {c} stays at its shaped position"); } assert!(!response_static_character('中') && !response_static_character('🪵')); @@ -2781,7 +3142,7 @@ mod tests { #[test] fn glow_send_envelope_retriggers_only_on_another_accepted_send() { let ctx=Context::default();let id=egui::Id::unique("glow-test"); - let frame=|time,trigger,reduced|{let _=ctx.run_ui(egui::RawInput {time:Some(time),screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(320.0,200.0))),..Default::default()},|ui|{sent_glow(ui,id,egui::Rect::from_min_size(egui::pos2(20.0,20.0),vec2(200.0,60.0)),trigger,reduced);});}; + let frame=|time,trigger,reduced|{let _=ctx.settle_ui(egui::RawInput {time:Some(time),screen_rect:Some(egui::Rect::from_min_size(egui::Pos2::ZERO,vec2(320.0,200.0))),..Default::default()},|ui|{sent_glow(ui,id,egui::Rect::from_min_size(egui::pos2(20.0,20.0),vec2(200.0,60.0)),trigger,reduced);});}; frame(0.0,true,false);assert_eq!(ctx.data(|d|d.get_temp::(id)),Some(0.0)); frame(0.2,false,false);assert_eq!(ctx.data(|d|d.get_temp::(id)),Some(0.0)); frame(1.1,true,false);assert_eq!(ctx.data(|d|d.get_temp::(id)),Some(1.1)); @@ -3129,7 +3490,7 @@ mod tests { fn caret_tracks_real_end_row_for_wrap_spaces_newlines_and_code() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { for text in ["word word word", "word ", "word\n", "word\n\n", "正文 `code`"] { let job = reply_job(text, 38.0, Color32::WHITE, Color32::BLACK); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); @@ -3156,7 +3517,7 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); let mut right = 0.0; - let output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 240.0))), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 240.0))), ..Default::default() }, |ui| { ui.set_width(width); right = ui.cursor().min.x + ui.available_width(); streaming_reply(ui, egui::Id::unique("caret-boundary"), text, true, false); @@ -3170,25 +3531,13 @@ mod tests { } } - #[test] - fn font_cache_compares_shared_identity_and_detects_replaced_data() { - let ctx = Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { - let fonts = ui.fonts(|view| view.definitions().clone()); - let same = fonts.clone(); - assert!(same_font_definitions(&fonts, &same)); - let mut replaced = fonts.clone(); - let data = replaced.font_data.values_mut().next().expect("installed font"); - *data = std::sync::Arc::new((**data).clone()); - assert!(!same_font_definitions(&fonts, &replaced)); - }); - } - #[test] fn streaming_layout_reuses_one_bounded_galley_and_invalidates_changes() { let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); let id = egui::Id::unique("stream-cache"); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { let long = "较长的中文和 English streaming reply ".repeat(200); for text in ["短回复", long.as_str()] { let first = cached_reply_layout(ui, id, text, 250.0, Color32::WHITE, Color32::BLACK, true); @@ -3197,11 +3546,45 @@ mod tests { let changed = cached_reply_layout(ui, id, text, 180.0, Color32::WHITE, Color32::BLACK, true); assert!(!std::sync::Arc::ptr_eq(&first.galley, &changed.galley)); } + assert_eq!(streaming_reply_held(ui), 1, "exactly one streaming reply holds its galley"); let _ = cached_reply_layout(ui, id, "结束", 250.0, Color32::WHITE, Color32::BLACK, false); - assert!(ui.data(|data| data.get_temp::>(egui::Id::unique("agent-active-reply-layout"))).is_none()); + assert_eq!(streaming_reply_held(ui), 0, "a finished reply leaves the streaming slot"); }); } + /// 历史里已定稿的回复按内容留住排版结果:同一条回复连画几帧只排版一次,换宽度才重排; + /// 代码块缩进过的那份 galley 原样复用,不再每帧重新解析 Markdown、深拷贝行。 + #[test] + fn settled_replies_are_laid_out_once_and_reused_while_unchanged() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let id = egui::Id::unique("settled-cache"); + let text = "已经定稿的回复。\n\n```rust\nfn main() {}\n```\n\n最后一段。"; + // 预热一帧:把这段文字用到的字形都放进字体图集,之后的帧里图集尺寸不再变化。 + let _ = ctx.settle_ui(egui::RawInput { time: Some(-1.0), ..Default::default() }, |ui| { + ui.set_width(300.0); + scope(ui, |ui| cached_reply_layout(ui, id, text, 297.0, Color32::WHITE, Color32::BLACK, false)); + }); + let mut held = Vec::new(); + let mut layouts = Vec::new(); + for frame in 0..5 { + let width = if frame < 3 { 300.0 } else { 260.0 }; + let _ = ctx.settle_ui(egui::RawInput { time: Some(frame as f64 / 60.0), ..Default::default() }, |ui| { + ui.set_width(width); + scope(ui, |ui| { + layouts.push(reply_layouts_performed(ui)); + held.push(cached_reply_layout(ui, id, text, width - 3.0, Color32::WHITE, Color32::BLACK, false)); + }); + }); + } + let first = layouts[0]; + assert_eq!(&layouts[..], &[first, first, first, first, first + 1], "the first frame reuses, the next two reuse, a new width lays out once more"); + assert!(std::sync::Arc::ptr_eq(&held[0], &held[2]), "an unchanged settled reply reuses the very same galley"); + assert!(std::sync::Arc::ptr_eq(&held[3], &held[4]) && !std::sync::Arc::ptr_eq(&held[2], &held[3])); + assert!(held[4].galley.rows.iter().any(|row| row.pos.x > 0.0), "the indented code block is kept as it was laid out"); + } + #[test] fn streaming_progress_tracks_real_60_and_120_hz_clocks() { for hz in [60.0, 120.0] { @@ -3216,10 +3599,10 @@ mod tests { fn command_menu_native_focus_enter_and_disabled_state() { let ctx = Context::default(); let mut id = egui::Id::NULL; - let _ = ctx.run_ui(Default::default(), |ui| { id = command_menu_item(ui, "layers", "引用选中画布对象", true).id; }); + let _ = ctx.settle_ui(Default::default(), |ui| { id = command_menu_item(ui, "layers", "引用选中画布对象", true).id; }); ctx.memory_mut(|memory| memory.request_focus(id)); let mut clicked = false; - let output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { events: vec![egui::Event::Key { key: egui::Key::Enter, physical_key: Some(egui::Key::Enter), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], ..Default::default() }, |ui| { clicked = command_menu_item(ui, "layers", "引用选中画布对象", true).clicked(); assert!(!command_menu_item(ui, "image", "添加本地参考图", false).clicked()); }); @@ -3231,7 +3614,7 @@ mod tests { fn context_capacity_draws_unfilled_track_and_actual_arc() { let ctx = Context::default(); for (fraction, has_arc) in [(None, false), (Some(f32::NAN), false), (Some(0.0), false), (Some(0.25), true), (Some(1.0), true)] { - let output = ctx.run_ui(Default::default(), |ui| { context_capacity(ui, fraction, "上下文容量"); }); + let output = ctx.settle_ui(Default::default(), |ui| { context_capacity(ui, fraction, "上下文容量"); }); let paths: Vec<_> = output.shapes.iter().filter_map(|item| match &item.shape { egui::Shape::Path(path) => Some(path), _ => None }).collect(); assert_eq!(!paths.is_empty(), has_arc); assert!(paths.iter().all(|path| path.fill == Color32::TRANSPARENT)); @@ -3273,7 +3656,7 @@ mod tests { #[test] fn first_fence_preserves_existing_prose_row_positions() { let ctx = Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let prefix = "长中文说明和 a moderately long English sentence 在窄栏换行。\n"; let expanded = format!("{prefix}```json\n{{}}\n"); let (before, _) = reply_layout(prefix, 250.0, Color32::WHITE, Color32::BLACK); @@ -3292,7 +3675,7 @@ mod tests { fn markdown_copy_button_emits_real_clipboard_command_at_narrow_width() { let ctx = Context::default(); let mut target = egui::Pos2::ZERO; - let render = |events, target: &mut egui::Pos2| ctx.run_ui(egui::RawInput { + let render = |events, target: &mut egui::Pos2| ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 400.0))), events, ..Default::default() }, |ui| { let right = ui.max_rect().right(); @@ -3318,7 +3701,7 @@ mod tests { #[test] fn markdown_empty_and_long_blocks_use_real_wrapped_galley() { let ctx = Context::default(); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let _ = ctx.settle_ui(egui::RawInput::default(), |ui| { for source in ["```\n```", "```txt\n中文abcdefghijklmno 12345678901234567890\n```\n后文"] { let (job, blocks) = reply_layout(source, 247.0, Color32::WHITE, Color32::BLACK); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); @@ -3335,7 +3718,7 @@ mod tests { fn markdown_card_and_button_stay_inside_narrow_clip() { let ctx = Context::default(); let mut clip = egui::Rect::NOTHING; - let output = ctx.run_ui(egui::RawInput { + let output = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(250.0, 400.0))), ..Default::default() }, |ui| { clip = ui.clip_rect(); @@ -3419,7 +3802,7 @@ mod tests { #[test] fn collaboration_style_does_not_restyle_native_parent() { let ctx = Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let before = ui.style().clone(); scope(ui, |ui| { assert!(ui.visuals().dark_mode); @@ -3440,7 +3823,7 @@ mod tests { assert_eq!(idle, t.primary_bg); assert_eq!([idle.a(), hover.a(), pressed.a()], [255, 255, 255]); assert!(idle.r() > hover.r() && hover.r() > pressed.r(), "interaction shades the neutral background without transparency"); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let original = ui.visuals().clone(); scope(ui, |ui| { let scoped = ui.visuals().clone(); @@ -3459,7 +3842,7 @@ mod tests { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, native_theme); let mut draft = String::from("柚木色:保持原有结构 🪵"); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let native_visuals = ui.visuals().clone(); scope(ui, |ui| { for role in [SurfaceRole::Dialog, SurfaceRole::Menu, SurfaceRole::Composer, SurfaceRole::Task, SurfaceRole::Input] { @@ -3494,7 +3877,7 @@ mod tests { let t = Tokens::get(&ctx).agent(); let rect = egui::Rect::from_min_size(egui::pos2(20.0, 20.0), size); for time in [1.0, 20.0] { - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { paint_status_chip(ui, &t, rect, text, style); }); let labels: Vec<_> = output.shapes.iter().filter_map(|shape| match &shape.shape { @@ -3507,7 +3890,7 @@ mod tests { let foreground = t.text; assert!(labels[0].1.galley.job.sections.iter().all(|section| section.format.color == foreground)); assert_eq!(output.shapes.iter().filter(|shape| matches!(&shape.shape, - egui::Shape::Rect(surface) if surface.rect == rect && surface.fill == material_fallback(0.48))).count(), 1); + egui::Shape::Rect(surface) if surface.rect == rect && surface.fill == material_fallback(0.0))).count(), 1); } } } @@ -3575,7 +3958,7 @@ mod tests { #[test] fn material_frame_at_zero_opacity_does_not_restore_visible_background() { let ctx=egui::Context::default(); - let output=ctx.run_ui(egui::RawInput::default(),|ui| { + let output=ctx.settle_ui(egui::RawInput::default(),|ui| { let frame=overlay_frame(ui.ctx(),SurfaceRole::Task,0.0); material_frame(ui,frame,|ui| {ui.allocate_space(vec2(200.0,100.0));}); }); @@ -3616,7 +3999,7 @@ mod tests { (2.0, true, true), (2.1, false, true), ] { - let _ = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { let visual = overlay_transition(ui.ctx(), id, open, reduced); let rendered = overlay_contents(ui, visual, |ui| { assert_eq!(ui.is_enabled(), open, "a departing surface must not accept input"); @@ -3643,7 +4026,7 @@ mod tests { let exit_button_clicked = std::cell::Cell::new(false); let was_disabled = std::cell::Cell::new(false); let render = |events: Vec, interactive: bool| { - let _ = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 300.0))), events, ..Default::default() }, |ui| { + let _ = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 300.0))), events, ..Default::default() }, |ui| { let response = ui.button("背景操作"); underlying_rect.set(response.rect); underlying_clicked.set(underlying_clicked.get() || response.clicked()); @@ -3666,7 +4049,7 @@ mod tests { } assert!(!underlying_clicked.get(), "retained modal must continue blocking the background"); assert!(was_disabled.get() && !exit_button_clicked.get(), "departing controls cannot activate"); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { assert!(modal(ui.ctx(), id, OverlayVisual { render: false, interactive: false, opacity: 0.0 }, true, |_| {}).is_none()); }); } @@ -3674,7 +4057,7 @@ mod tests { #[test] fn retained_overlay_respects_parent_opacity_and_disabled_state() { let ctx = Context::default(); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { ui.scope(|ui| { ui.set_opacity(0.5); ui.disable(); @@ -3692,7 +4075,7 @@ mod tests { fn an_open_picker_keeps_the_stitch_material_inside_a_light_native_editor() { let ctx = Context::default(); crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProLight); - let _ = ctx.run_ui(Default::default(), |ui| { + let _ = ctx.settle_ui(Default::default(), |ui| { let original = ui.visuals().widgets.open; scope(ui, |ui| { let t = Tokens::get(ui.ctx()).agent(); @@ -3717,7 +4100,7 @@ mod tests { fn render(ctx: &Context, time: f64) -> (egui::FullOutput, egui::Id, usize) { let mut button_id = egui::Id::NULL; let mut popup_visits = 0; - let output = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let output = ctx.settle_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { scope(ui, |ui| { ui.style_mut().animation_time = 0.0; let response = halo_select(ui, "scoped-popup-proof", 160.0, "Model", true, |ui| { @@ -3749,7 +4132,281 @@ mod tests { let t = Tokens::get(&ctx).agent(); assert_ne!(t.tab_strip, native_fill); assert!(popup_visits > 0, "the test opens the actual Stitch selector popup"); - assert!(output.shapes.iter().any(|shape| has_popup_frame(&shape.shape, t.tab_strip, Stroke::new(1.0, t.card_border))), "the popup paint output contains the scoped fill, border and radius"); + assert!(output.shapes.iter().any(|shape| has_popup_frame(&shape.shape, menu_base(), Stroke::new(1.0, menu_rim(t)))), "the popup paint output contains the scoped fill, border and radius"); assert_eq!(ctx.style_of(egui::Theme::Dark).visuals.window_fill, native_fill, "the native editor style remains unchanged"); } + + fn glow_mesh_count(output: &egui::FullOutput) -> usize { + fn count(shape: &egui::Shape) -> usize { + match shape { + egui::Shape::Mesh(_) => 1, + egui::Shape::Vec(shapes) => shapes.iter().map(count).sum(), + _ => 0, + } + } + output.shapes.iter().map(|clipped| count(&clipped.shape)).sum() + } + + fn reply_text_shapes<'a>(output: &'a egui::FullOutput, text: &str) -> Vec<&'a egui::epaint::TextShape> { + fn walk<'a>(shape: &'a egui::Shape, text: &str, out: &mut Vec<&'a egui::epaint::TextShape>) { + match shape { + egui::Shape::Text(shape) if shape.galley.text() == text => out.push(shape), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, text, out)), + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &output.shapes { + walk(&clipped.shape, text, &mut out); + } + out + } + + fn requested_delay(output: &egui::FullOutput) -> Option { + super::super::agent_motion::requested_delay(output) + } + + /// 品牌动效的定稿参数都落在 Token 上:改这里就是改观感,别处不许再写字面量。 + #[test] + fn typing_reveal_and_motion_tokens_hold_the_locked_brand_parameters() { + assert!((reveal::ENTER - 0.300).abs() < 1e-9, "单字入场 300ms cubic-out"); + assert!((reveal::STEP - 0.015).abs() < 1e-9, "每字步进 15ms"); + assert!((10..=12).contains(&reveal::TAIL), "尾韵约 10–12 字"); + assert!( + (reveal::ENTER + reveal::STEP * reveal::TAIL as f64) < 0.5, + "原型 460ms 的单字节奏已明显加快:一个字入场、整段尾韵铺完都不到半秒" + ); + assert!((timing::STOP_SETTLE - 0.190).abs() < 1e-9, "停止减速定格收敛在 180–200ms"); + assert_eq!(timing::FRAME_FULL, std::time::Duration::from_millis(16), "发送脉冲、运行、交互满帧"); + assert_eq!(timing::FRAME_IDLE, std::time::Duration::from_millis(32), "纯待机降到半帧"); + assert_eq!(timing::FRAME_DEEP, std::time::Duration::from_millis(50)); + assert_eq!(timing::GLOW_SEND, 0.640, "发送光涌的 640ms 包络原样保留"); + assert_eq!(timing::GLOW_SEND_PEAK, 0.280); + assert_eq!(timing::SPRING_OMEGA, 20.0, "对话框与输入框展开收缩用的是同一个临界阻尼弹簧"); + assert_eq!((timing::OVERLAY_IN, timing::OVERLAY_OUT, timing::CARET_EXIT), (0.22, 0.16, 0.16), "弹窗 220ms 入、160ms 出不变"); + assert_eq!(timing::NATIVE, 0.22); + assert_eq!((timing::RIM_PERIOD, timing::FIELD_PERIOD), (9.0, 6.0)); + assert_eq!((timing::ORB_LOOP, timing::ORB_BREATH), (20.0, 5.5)); + assert_eq!(timing::GLOW_WAIT_SCALE, 0.55); + assert_eq!(timing::IDLE_AFTER, 1.5); + assert_eq!(timing::DEEP_AFTER, 15.0); + } + + /// 回复正文逐字入场时带着柔光:流头一团、身后一条约 11 字的光带;定稿后什么都不画、不申请重绘。 + #[test] + fn streaming_reply_carries_a_head_halo_and_a_tail_band_then_goes_completely_still() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let text = "整套已经推进到主图这一步,详情页的文案和图片都已就位。"; + let render = |time: f64, streaming: bool, reduced: bool| { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 300.0))), time: Some(time), ..Default::default() }, |ui| { + ui.set_width(320.0); + scope(ui, |ui| streaming_reply(ui, egui::Id::unique("reveal"), text, streaming, reduced)); + }) + }; + render(0.0, true, false); + let flowing = render(0.4, true, false); + assert_eq!(reply_text_shapes(&flowing, text).len(), 1, "the reply is always a single galley"); + assert!( + (2..=6).contains(&glow_mesh_count(&flowing)), + "one head halo plus one band per wrapped line, and nothing else: {}", + glow_mesh_count(&flowing) + ); + assert_eq!(requested_delay(&flowing), Some(timing::FRAME_FULL), "streaming runs at the full frame rate"); + // 定稿:柔光立刻消失;流式光标在 160ms 里退场,退场结束后一帧都不再申请。 + let settled = render(6.0, false, false); + assert_eq!(glow_mesh_count(&settled), 0, "a settled reply draws no glow"); + let resting = render(6.0 + timing::CARET_EXIT + 0.2, false, false); + assert_eq!(requested_delay(&resting), None, "and asks for no repaint at all"); + let reduced = render(10.0, true, true); + assert_eq!(glow_mesh_count(&reduced), 0, "reduced motion never starts the glow"); + } + + /// 用户气泡遵守减少动态:直接显示全文,不起柔光,也不申请重绘;入场过程中气泡尺寸不变。 + #[test] + fn user_bubble_respects_reduced_motion_and_keeps_its_size_while_revealing() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let text = "保留产品结构,让光线更加柔和。"; + let render = |time: f64, started: Option, reduced: bool, rect: &std::cell::Cell| { + ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 240.0))), time: Some(time), ..Default::default() }, |ui| { + ui.set_width(240.0); + scope(ui, |ui| rect.set(user_bubble_with_reveal(ui, text, started, reduced))); + }) + }; + let rect = std::cell::Cell::new(egui::Rect::NOTHING); + let mut bounds = Vec::new(); + let mut glows = Vec::new(); + let mut delays = Vec::new(); + for (time, started, reduced) in [(0.0, Some(0.0), false), (0.12, Some(0.0), false), (5.0, Some(0.0), false), (5.2, Some(5.2), true)] { + let output = render(time, started, reduced, &rect); + bounds.push(rect.get()); + glows.push(glow_mesh_count(&output)); + delays.push(requested_delay(&output)); + } + assert!( + bounds.windows(2).all(|pair| pair[0] == pair[1]), + "the bubble is sized to the whole message and never resizes: {bounds:?}" + ); + assert!(glows[0] == 0 && glows[1] > 0, "the reveal carries a soft glow while it runs"); + assert_eq!((glows[2], delays[2]), (0, None), "and draws nothing and requests nothing once settled"); + assert_eq!((glows[3], delays[3]), (0, None), "reduced motion shows the whole message at once"); + } + + /// 输入浮层的光涌:发送脉冲、运行、聚焦与悬停时满帧;纯待机平滑降到半帧; + /// 最小化与减少动态时零重绘。材质、流光与发送脉冲本身原样不动。 + #[test] + fn composer_glow_holds_the_full_frame_for_pulses_running_focus_and_hover_then_downshifts() { + let ctx = Context::default(); + ctx.settle_start(); + let rect = egui::Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(200.0, 60.0)); + let id = egui::Id::unique("paced-glow"); + let frame = |time: f64, new_message: bool, reduced: bool, pace: GlowPace, pointer: Option, minimized: bool| { + let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), time: Some(time), ..Default::default() }; + if let Some(at) = pointer { + input.events.push(egui::Event::PointerMoved(at)); + } + if minimized { + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().minimized = Some(true); + } + let output = ctx.settle_ui(input, |ui| sent_glow_paced(ui, id, rect, new_message, reduced, pace)); + requested_delay(&output) + }; + let idle = GlowPace::default(); + let running = GlowPace { running: true, engaged: false }; + let engaged = GlowPace { running: false, engaged: true }; + // 发送脉冲:640ms 包络内一直是满帧。 + assert_eq!(frame(10.0, true, false, idle, None, false), Some(timing::FRAME_FULL)); + assert_eq!(frame(10.3, false, false, idle, None, false), Some(timing::FRAME_FULL)); + assert_eq!(frame(10.63, false, false, idle, None, false), Some(timing::FRAME_FULL)); + // 纯待机:最后一次满帧请求 1.5s 之后才开始降频,帧间隔只增不减,最终停在半帧。 + let mut delays = Vec::new(); + for step in 0..300 { + delays.push(frame(10.64 + step as f64 / 60.0, false, false, idle, None, false).unwrap_or(std::time::Duration::MAX)); + } + assert!(delays.windows(2).all(|pair| pair[1] >= pair[0]), "帧间隔只增不减,不跳变: {delays:?}"); + assert_eq!(delays[80], timing::FRAME_FULL, "宽限期内仍是满帧"); + assert!( + delays[299] > timing::FRAME_FULL && delays[299] <= timing::FRAME_IDLE + std::time::Duration::from_millis(1), + "纯待机停在半帧: {:?}", + delays[299] + ); + // 运行、聚焦、悬停:各自立刻回到满帧。 + assert_eq!(frame(20.0, false, false, running, None, false), Some(timing::FRAME_FULL)); + assert_eq!(frame(20.1, false, false, engaged, None, false), Some(timing::FRAME_FULL)); + // egui requests an immediate frame for pointer input. Sample the held + // hover once input has settled, without sending another move event. + frame(22.0, false, false, idle, Some(rect.center()), false); + frame(22.02, false, false, idle, None, false); + assert_eq!(frame(22.04, false, false, idle, None, false), Some(timing::FRAME_FULL)); + // 最小化与减少动态:一帧都不申请。 + assert_eq!(frame(22.1, true, false, GlowPace { running: true, engaged: true }, None, true), None); + assert_eq!(frame(22.2, true, false, GlowPace { running: true, engaged: true }, None, true), None); + assert_eq!(frame(22.3, true, true, GlowPace { running: true, engaged: true }, None, false), None); + // 旧签名仍然可用:它不带运行/聚焦信息,行为等同于纯待机加自动悬停判断。 + let legacy = ctx.settle_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 200.0))), time: Some(30.0), ..Default::default() }, |ui| sent_glow(ui, id, rect, true, false)); + assert_eq!(requested_delay(&legacy), Some(timing::FRAME_FULL)); + } + + /// 焦点环只有一套画法:六种规格的内缩与颜色钉在这里,控件只选规格,不再各画各的。 + #[test] + fn focus_ring_has_one_implementation_and_six_pinned_recipes() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + let t = Tokens::get(&ctx).agent(); + assert_eq!(FocusRing::Control.place(&t), (0.5, t.text)); + assert_eq!(FocusRing::OnPrimary.place(&t), (0.5, t.primary_text)); + assert_eq!(FocusRing::OnSend.place(&t), (1.0, t.primary_text)); + assert_eq!(FocusRing::OnGlass.place(&t), (0.0, t.text_dim)); + assert_eq!(FocusRing::OnRail.place(&t), (1.0, t.text)); + assert_eq!(FocusRing::OnGlassRail.place(&t), (1.0, t.text_dim)); + let rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), vec2(80.0, 30.0)); + let rings = |ring: FocusRing, focused: bool| { + let output = ctx.settle_ui(egui::RawInput::default(), |ui| focus_ring_at(ui, rect, radius::CONTROL, ring, focused)); + output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Rect(frame) if frame.stroke.width == 1.0 && frame.stroke.color.a() == 255 => Some((frame.rect, frame.stroke.color)), + _ => None, + }).collect::>() + }; + assert!(rings(FocusRing::Control, false).is_empty(), "no focus, no ring"); + assert_eq!(rings(FocusRing::Control, true), vec![(rect.shrink(0.5), t.text)]); + assert_eq!(rings(FocusRing::OnGlassRail, true), vec![(rect.shrink(1.0), t.text_dim)]); + } + + /// 守卫:组件库自己的生产代码里不再出现字号字面量与原始颜色构造,一律走 Token。 + #[test] + fn the_library_takes_its_sizes_and_colours_from_tokens() { + let source = include_str!("stitch_ui.rs").replace("\r\n", "\n"); + let production = source.split("\n#[cfg(test)]\nmod tests").next().unwrap_or(&source); + for pattern in [ + "FontId::proportional(1", "FontId::proportional(2", "FontId::proportional(3", ".size(1", ".size(2", ".size(3", ".size(4", + ".size(5", ".size(6", ".size(7", ".size(8", ".size(9", "semibold(1", "semibold(2", "mono(1", + "Color32::from_rgb", "Color32::from_black_alpha", "Color32::from_white_alpha", "Color32::from_gray", "Color32::from_rgba", + ] { + assert!(!production.contains(pattern), "stitch_ui.rs still hard-codes {pattern} in production code"); + } + for (kind, size) in [(Type::Caption, 11.0), (Type::Meta, 12.0), (Type::Title, 13.0), (Type::Body, 14.0), (Type::Subheading, 15.0), (Type::Heading, 16.0), (Type::TitleLg, 18.0), (Type::Display, 20.0)] { + assert_eq!((kind.size(), kind.font_id().size), (size, size)); + } + } + + /// 旧的字符串入参行与新的类型化行读出来完全一样:状态文案、颜色与图标只有一份定义。 + #[test] + fn typed_and_legacy_tool_rows_read_the_same_status() { + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let t = Tokens::get(&ctx).agent(); + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 120.0))); + let status_color = |output: &egui::FullOutput, label: &str| { + output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == label => Some(text.galley.job.sections.first().map(|section| section.format.color)), + _ => None, + }).flatten().next() + }; + let mut labels = Vec::new(); + for (legacy, typed) in [ + ("pending", ToolStatus::Pending), ("started", ToolStatus::Started), ("completed", ToolStatus::Completed), + ("failed", ToolStatus::Failed), ("stopped", ToolStatus::Stopped), ("nonsense", ToolStatus::Unknown), + ] { + let legacy_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { + scope(ui, |ui| task_row(ui, egui::Id::unique("legacy"), "search", "读取画布", legacy, Some("耗时 27 毫秒"), true)).inner + }); + let typed_row = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { + scope(ui, |ui| task_status_row(ui, egui::Id::unique("typed"), tool_glyph("canvas_read"), "读取画布", typed, Some("耗时 27 毫秒"), true)).inner + }); + assert_eq!(status_color(&legacy_row, typed.label()), Some(typed.tone().color(&t)), "legacy {legacy}"); + assert_eq!(status_color(&typed_row, typed.label()), Some(typed.tone().color(&t)), "typed {legacy}"); + assert!(reply_text_shapes(&typed_row, "读取画布").len() == 1 && reply_text_shapes(&typed_row, "耗时 27 毫秒").len() == 1); + labels.push(typed.label()); + } + assert_eq!(labels, ["等待", "进行中", "已完成", "失败", "已停止", "状态未知"]); + } + + /// 旧的工具组标题垫片与新的类型化标题读出同一行字:计数与失败数只有一处拼法。 + #[test] + fn legacy_tool_group_title_and_typed_head_agree() { + let head = ToolGroupHead { total: 5, completed: 3, failed: 1, active: true }; + assert_eq!(head.count(), "3/5 已完成 · 1 项失败"); + assert_eq!(head.tone(), Tone::Failure, "a failure outranks running for the row's colour"); + assert_eq!(ToolGroupHead { total: 5, completed: 3, failed: 0, active: true }.tone(), Tone::Active); + assert_eq!(ToolGroupHead { total: 5, completed: 5, failed: 0, active: false }.tone(), Tone::Quiet); + let ctx = Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + settle_test_cjk_font(&ctx); + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 160.0))); + let texts = |title: &str| { + let output = ctx.settle_ui(egui::RawInput { screen_rect: screen, ..Default::default() }, |ui| { + scope(ui, |ui| tool_group(ui, egui::Id::unique(("title", title)), title, true, true, |_| ())); + }); + output.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.galley.text().to_owned()), + _ => None, + }).collect::>() + }; + let legacy = texts(&format!("工具调用 · {}", head.count())); + assert!(legacy.iter().any(|text| text == "工具调用") && legacy.iter().any(|text| text == "3/5 已完成 · 1 项失败"), "{legacy:?}"); + } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/test_support.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/test_support.rs new file mode 100644 index 00000000..d4a311f3 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/test_support.rs @@ -0,0 +1,35 @@ +//! 测试辅助,只在测试构建里编译。 +//! +//! 小壹各模块的界面测试共用一个"渲染一帧"的入口。egui 的 fork 在调试构建下断言 +//! "带未应用增量的输出不能被直接丢弃",而每个新的 Context 第一帧都会带出字体图集: +//! 真实应用会把它交给渲染器,测试里没有人接,于是测试一结束就 panic,把真正的断言结果盖住。 +//! 统一从这里走:测试体里只关心自己要断言的东西。 +use egui::{Context, Ui}; + +pub(crate) trait SettleUi { + /// 渲染一帧,并把这一帧的字体纹理增量标记为已处理。 + fn settle_ui(&self, input: egui::RawInput, ui: impl FnMut(&mut Ui)) -> egui::FullOutput; + + /// 先过掉新窗口开头的几次立即重绘,再开始断言重绘节奏。 + /// + /// 这些重绘与界面里谁申请了什么无关,每一帧输出的重绘延迟都是 0:启动帧本身、第一帧结束时 egui 同步窗口主题、 + /// 装过字体时字体生效后的第一个输出帧。要在字体和主题装好之后调用。 + fn settle_start(&self); +} + +impl SettleUi for Context { + fn settle_ui(&self, input: egui::RawInput, ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let mut output = self.run_ui(input, ui); + output.textures_delta.clear(); + output + } + + fn settle_start(&self) { + for _ in 0..16 { + if !self.has_requested_repaint() { + break; + } + let _ = self.settle_ui(egui::RawInput::default(), |_| {}); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs index f687472c..50dde227 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/typing_text.rs @@ -1,73 +1,514 @@ -//! Arrival timing for native text editing and sent user messages. -use egui::{Id,Ui}; +//! 逐字扩散:输入框、用户气泡与 Agent 正文共用的一套入场与柔光算法。 +//! +//! 节奏由用户定稿:单字 300ms cubic-out 入场,相邻两字步进 15ms;一次到达激起一道柔光, +//! 以每字 22ms 向回传播、按 exp(-距离/9) 衰减,在流头身后留下约 11 字宽的尾韵,流头另有一团柔光。 +//! 尚未轮到的字先以极淡的光雾占位,光标不会跑到文字前面。 +//! +//! 这里只管到达时间、柔光数学与柔光网格;字形网格的改写在 `stitch_ui::animate_galley`。 +use crate::theme::agent_scale::motion as timing; +use crate::theme::Tokens; +use egui::{Color32, Id, Mesh, Pos2, Shape, Ui, pos2, vec2}; +use std::ops::Range; use std::sync::Arc; use unicode_segmentation::UnicodeSegmentation; -fn delay(index:usize,count:usize)->f64 { - let span=(count.saturating_sub(1) as f64*0.012).min(0.65); - span*index as f64/count.saturating_sub(1).max(1) as f64 -} -pub(super) fn staggered(text:&str,started:f64)->Vec { - let clusters:Vec<_>=text.graphemes(true).collect(); - clusters.iter().enumerate().flat_map(|(index,cluster)|std::iter::repeat_n(started+delay(index,clusters.len()),cluster.chars().count())).collect() +use super::agent_motion::{Pace, schedule}; + +/// 单字入场时长:300ms cubic-out。 +pub(super) const ENTER: f64 = timing::REVEAL_ENTER; +/// 相邻两字的到达步进:15ms。 +pub(super) const STEP: f64 = timing::REVEAL_STEP; +/// 一批同时到达的字铺开后的总跨度上限,超出就压缩步进,吐字不会越拖越远。 +pub(super) const MAX_SPAN: f64 = timing::REVEAL_MAX_SPAN; +/// 尾韵宽度:流头向回约 11 个字。 +pub(super) const TAIL: usize = timing::REVEAL_TAIL; +/// 光波向回传播:每个字 22ms。 +const WAVE: f64 = timing::REVEAL_WAVE; +/// 一次到达的柔光升起、衰减的时间常数(毫秒)。 +const RISE_MS: f64 = timing::REVEAL_RISE * 1000.0; +const FADE_MS: f64 = timing::REVEAL_FADE * 1000.0; +/// 空间衰减:离光源每远一个字,柔光乘 exp(-1/9)。 +const SPREAD: f32 = timing::REVEAL_SPREAD; +/// 每个字最多叠加最近 7 次到达的柔光。 +const SOURCES: usize = 7; +/// 还没轮到的字先以极淡的光雾占位。 +pub(super) const MIST: f32 = 0.12; +/// 入场时从下方 4pt 升起。 +pub(super) const RISE_POINTS: f32 = 4.0; +/// 入场时从 1.035 倍收拢到原大。 +pub(super) const SCALE_FROM: f32 = 1.035; +/// 柔光把字轻轻托起。 +pub(super) const LIFT_POINTS: f32 = 1.4; +/// 尾韵光带与流头柔光的峰值透明度。 +pub(super) const BAND_ALPHA: f32 = 0.22; +pub(super) const HALO_ALPHA: f32 = 0.30; +/// 低于这个强度就不再画柔光,整段文字视为定稿。 +pub(super) const GLOW_LIMIT: f32 = 0.06; +/// 最后一次到达之后这么久,叠加后的柔光降到不可见。 +pub(super) const REST_AFTER: f64 = 2.05; +/// 历史消息的到达时间戳取得足够早,整段文字直接就是定稿状态。 +pub(super) const SETTLED_AGE: f64 = 2.2; +/// 柔光强于这个值时按满帧率重绘,更弱时只按待机档重绘。 +pub(super) const STRONG_GLOW: f32 = 0.25; + +/// cubic-out。 +pub(super) fn ease_out(progress: f32) -> f32 { + let remaining = 1.0 - progress.clamp(0.0, 1.0); + 1.0 - remaining * remaining * remaining } -#[derive(Clone,Default)] -struct EditorArrival {owner:Option,text:String,arrivals:Arc>,reduced:bool} +/// 一次到达激起的柔光随时间的包络:`age_ms` 是到达后的毫秒数。 +pub(super) fn wave(age_ms: f64) -> f32 { + if !age_ms.is_finite() || age_ms <= 0.0 { + return 0.0; + } + ((1.0 - (-age_ms / RISE_MS).exp()) * (-age_ms / FADE_MS).exp()) as f32 +} + +/// 流头附近一个可见的字:它在 galley 里的位置、到达时间与柔光强度。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct TrailToken { + pub row: usize, + pub glyph: usize, + pub center: Pos2, + pub advance: f32, + pub font: f32, + pub top: f32, + pub bottom: f32, + pub arrival: f64, + pub glow: f32, +} + +/// 尾韵窗口:流头向回第 6 个字以内全亮,到第 13 个字减到零,约 11 字宽。 +fn window(distance: usize) -> f32 { + let t = ((distance as f32 - 6.0) / 7.0).clamp(0.0, 1.0); + 1.0 - t * t * (3.0 - 2.0 * t) +} + +/// 给流头附近由新到旧的字填上柔光强度。第 `distance` 个字收到最近 7 次到达各自的光波, +/// 光波每向回走一个字晚 22ms、弱 exp(-1/9);叠加结果再乘尾韵窗口,尾部柔和收束。 +pub(super) fn light_trail(tokens: &mut [TrailToken], now: f64) { + let arrivals: Vec = tokens.iter().map(|token| token.arrival).collect(); + for (distance, token) in tokens.iter_mut().enumerate() { + let mut total = 0.0_f32; + for back in 0..=distance.min(SOURCES - 1) { + let age = (now - arrivals[distance - back]) * 1000.0 - back as f64 * WAVE * 1000.0; + if age > 0.0 { + total += (-(back as f32) / SPREAD).exp() * wave(age); + } + } + token.glow = total.min(1.0) * window(distance); + } +} + +/// `count` 个字逐字铺开时每个字的步进:每字 STEP,超长时压缩,总跨度恰好不超过 MAX_SPAN。 +pub(super) fn batch_step(count: usize) -> f64 { + if count <= 1 { 0.0 } else { STEP.min(MAX_SPAN / count.saturating_sub(1) as f64) } +} + +/// 一段 `count` 个字的文字从开始到完全定稿需要的时长。 +pub(super) fn duration(count: usize) -> f64 { + batch_step(count) * count.saturating_sub(1) as f64 + REST_AFTER +} + +/// 一段已知全文从 `started` 起逐字扩散的到达时间,每个字符一项(字素簇内共用一个时间)。 +pub(super) fn staggered(text: &str, started: f64) -> Vec { + let clusters: Vec<_> = text.graphemes(true).collect(); + let step = batch_step(clusters.len()); + clusters.iter().enumerate() + .flat_map(|(index, cluster)| std::iter::repeat_n(started + step * index as f64, cluster.chars().count())) + .collect() +} + +/// 这一刻之后整段文字不再有任何逐字动态。 +pub(super) fn rest_at(arrivals: &[f64]) -> f64 { + arrivals.iter().copied().fold(f64::NEG_INFINITY, f64::max) + REST_AFTER +} + +/// 把刚到达的一批字(`added`,初值都是它们的 `now`)按每字 STEP 逐字铺开。 +/// 前一个字还没轮到时,这批字接在它后面,先后顺序不乱; +/// 积压超过 MAX_SPAN 时,把这一串还没轮到的字整体压回 MAX_SPAN,吐字不会越拖越远。 +pub(super) fn spread(arrivals: &mut [f64], added: Range, now: f64) { + spread_by(arrivals, added, &[], now); +} + +/// `spread` 的按字素簇版本:`text` 是 `added` 这一段的原文,组合符号、ZWJ 序列与它的基字算一格、同时到达。 +pub(super) fn spread_text(arrivals: &mut [f64], added: Range, text: &str, now: f64) { + if text.chars().count() != added.len() { + spread(arrivals, added, now); + return; + } + let sizes: Vec = text.graphemes(true).map(|cluster| cluster.chars().count()).collect(); + spread_by(arrivals, added, &sizes, now); +} + +fn spread_by(arrivals: &mut [f64], added: Range, sizes: &[usize], now: f64) { + if added.is_empty() || added.end > arrivals.len() { + return; + } + let clustered = sizes.iter().sum::() == added.len(); + let before = if added.start == 0 { None } else { Some(arrivals[added.start - 1]) }; + let queued = before.is_some_and(|at| at > now); + let step = batch_step(if clustered { sizes.len() } else { added.len() } + usize::from(queued)); + let base = before.map_or(now, |at| now.max(at + step)); + let (mut index, mut unit) = (added.start, 0_usize); + while index < added.end { + let size = if clustered { sizes.get(unit).copied().unwrap_or(1).max(1) } else { 1 }; + let arrival = base + step * unit as f64; + for slot in &mut arrivals[index..(index + size).min(added.end)] { + *slot = arrival; + } + index += size; + unit += 1; + } + if arrivals[added.end - 1] - now <= MAX_SPAN { + return; + } + let mut start = added.start; + while start > 0 && arrivals[start - 1] > now { + start -= 1; + } + let mut end = added.end; + while end < arrivals.len() && arrivals[end] > now { + end += 1; + } + let count = (end - start) as f64; + for (offset, arrival) in arrivals[start..end].iter_mut().enumerate() { + *arrival = now + MAX_SPAN * (offset + 1) as f64 / count; + } +} + +/// 逐字柔光的用色:Agent 正文用冷月青,用户输入与用户气泡用琥珀。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct RevealInk { glow: Color32 } + +impl RevealInk { + pub(super) fn glow(self) -> Color32 { self.glow } + + pub(super) fn agent(t: Tokens) -> Self { + Self { glow: t.agent_semantic().glow_agent } + } + + pub(super) fn user(t: Tokens) -> Self { + Self { glow: t.agent_semantic().glow_user } + } +} + +/// 流头柔光与尾韵光带(galley 自身坐标)。调用方决定画在哪一层: +/// 回复正文画在字形下面,输入浮层里文字要经过光涌透镜,柔光由 `paint_glow` 画在玻璃上面。 +pub(super) fn glow_shapes(tokens: &[TrailToken], ink: Color32) -> Vec { + let mut shapes = Vec::new(); + // 流头柔光落在最新的字上,强度取它和紧随其后那个字里较亮的一个:新字刚到时它自己还在升起, + // 借后一个字的光才不会每来一个字就闪一下。 + if let Some(head) = tokens.first() { + let strength = tokens.iter().take(2).map(|token| token.glow).fold(0.0_f32, f32::max); + if strength >= GLOW_LIMIT { + shapes.push(halo(head, strength, ink)); + } + } + // 同一行里相邻的字连成一条光带,换行处断开。 + let mut run: Vec<&TrailToken> = Vec::new(); + for token in tokens.iter().rev().filter(|token| token.glow >= GLOW_LIMIT) { + if run.last().is_some_and(|last| last.row != token.row) { + shapes.extend(band(&run, ink)); + run.clear(); + } + run.push(token); + } + shapes.extend(band(&run, ink)); + shapes +} + +fn band(run: &[&TrailToken], ink: Color32) -> Option { + let (first, last) = (*run.first()?, *run.last()?); + let mut mesh = Mesh::default(); + let column = |mesh: &mut Mesh, x: f32, token: &TrailToken, amount: f32| { + let color = |level: f32| ink.gamma_multiply(BAND_ALPHA * amount * level); + let (top, bottom) = (token.top, token.bottom); + let shoulder = (bottom - top) * 0.225; + mesh.colored_vertex(pos2(x, top), Color32::TRANSPARENT); + mesh.colored_vertex(pos2(x, top + shoulder), color(0.6)); + mesh.colored_vertex(pos2(x, (top + bottom) * 0.5), color(1.0)); + mesh.colored_vertex(pos2(x, bottom - shoulder), color(0.6)); + mesh.colored_vertex(pos2(x, bottom), Color32::TRANSPARENT); + }; + column(&mut mesh, first.center.x - first.advance * 0.5, first, 0.0); + for token in run { + column(&mut mesh, token.center.x, token, token.glow); + } + column(&mut mesh, last.center.x + last.advance * 0.5 + last.font * 0.3, last, 0.0); + let columns = run.len() + 1; + for index in 0..columns { + let (a, b) = ((index * 5) as u32, ((index + 1) * 5) as u32); + for strip in 0..4_u32 { + mesh.add_triangle(a + strip, b + strip, a + strip + 1); + mesh.add_triangle(a + strip + 1, b + strip, b + strip + 1); + } + } + (!mesh.is_empty()).then(|| Shape::mesh(mesh)) +} + +fn halo(token: &TrailToken, strength: f32, ink: Color32) -> Shape { + const SEGMENTS: usize = 16; + let (rx, ry) = (token.font * 2.6, token.font * 1.2); + let tint = |level: f32| ink.gamma_multiply(HALO_ALPHA * strength * level); + let mut mesh = Mesh::default(); + mesh.colored_vertex(token.center, tint(1.0)); + for (reach, level) in [(0.45_f32, 0.6_f32), (1.0, 0.0)] { + for segment in 0..SEGMENTS { + let angle = std::f32::consts::TAU * segment as f32 / SEGMENTS as f32; + mesh.colored_vertex(token.center + vec2(angle.cos() * rx * reach, angle.sin() * ry * reach), tint(level)); + } + } + let ring = SEGMENTS as u32; + for segment in 0..SEGMENTS { + let (here, next) = (1 + segment as u32, 1 + ((segment + 1) % SEGMENTS) as u32); + mesh.add_triangle(0, here, next); + mesh.add_triangle(here, here + ring, next + ring); + mesh.add_triangle(here, next + ring, next); + } + Shape::mesh(mesh) +} + +#[derive(Clone, Default)] +struct EditorArrival { owner: Option, text: String, arrivals: Arc>, reduced: bool, rest_at: f64 } + impl EditorArrival { - fn update(&mut self,owner:Id,text:&str,now:f64,reduced:bool)->Arc> { - if self.owner==Some(owner)&&self.text==text&&self.reduced==reduced {return self.arrivals.clone();} - let arrivals=if self.owner!=Some(owner)||reduced { - vec![now-1.0;text.chars().count()] + fn update(&mut self, owner: Id, text: &str, now: f64, reduced: bool) -> Arc> { + if self.owner == Some(owner) && self.text == text && self.reduced == reduced { + return self.arrivals.clone(); + } + let arrivals = if self.owner != Some(owner) || reduced { + vec![now - SETTLED_AGE; text.chars().count()] } else { - self.edited(text,now) + self.edited(text, now) }; - self.owner=Some(owner);self.text=text.to_owned();self.arrivals=Arc::new(arrivals);self.reduced=reduced; + self.rest_at = rest_at(&arrivals); + self.owner = Some(owner); + self.text = text.to_owned(); + self.arrivals = Arc::new(arrivals); + self.reduced = reduced; self.arrivals.clone() } - fn edited(&self,text:&str,now:f64)->Vec { - let old:Vec<_>=self.text.graphemes(true).collect();let new:Vec<_>=text.graphemes(true).collect(); - let prefix=old.iter().zip(&new).take_while(|(a,b)|a==b).count(); - let suffix=old.iter().skip(prefix).rev().zip(new.iter().skip(prefix).rev()).take_while(|(a,b)|a==b).count(); - let mut offsets=vec![0];for cluster in &old {offsets.push(offsets.last().copied().unwrap_or(0)+cluster.chars().count());} - let added=new.len().saturating_sub(prefix+suffix); - let mut arrivals=Vec::with_capacity(text.chars().count()); - for (index,cluster) in new.iter().enumerate() { - let old_index=if index=new.len()-suffix {Some(old.len()-(new.len()-index))} else {None}; - let previous=old_index.and_then(|index|offsets.get(index).and_then(|offset|self.arrivals.get(*offset))).copied(); - let arrival=previous.unwrap_or_else(||now+delay(index.saturating_sub(prefix),added)); - arrivals.extend(std::iter::repeat_n(arrival,cluster.chars().count())); + + fn edited(&self, text: &str, now: f64) -> Vec { + let old: Vec<_> = self.text.graphemes(true).collect(); + let new: Vec<_> = text.graphemes(true).collect(); + let prefix = old.iter().zip(&new).take_while(|(a, b)| a == b).count(); + let suffix = old.iter().skip(prefix).rev().zip(new.iter().skip(prefix).rev()).take_while(|(a, b)| a == b).count(); + let mut offsets = vec![0]; + for cluster in &old { + offsets.push(offsets.last().copied().unwrap_or(0) + cluster.chars().count()); } + let mut arrivals = Vec::with_capacity(text.chars().count()); + for (index, cluster) in new.iter().enumerate() { + let old_index = if index < prefix { + Some(index) + } else if index >= new.len() - suffix { + Some(old.len() - (new.len() - index)) + } else { + None + }; + let previous = old_index.and_then(|index| offsets.get(index).and_then(|offset| self.arrivals.get(*offset))).copied(); + let arrival = previous.unwrap_or(now); + arrivals.extend(std::iter::repeat_n(arrival, cluster.chars().count())); + } + let first = offsets.get(prefix).copied().unwrap_or(0); + let tail = new.iter().skip(new.len() - suffix).map(|cluster| cluster.chars().count()).sum::(); + let end = arrivals.len() - tail; + // 新进的字素簇按簇铺开:簇内的字符(组合符号、ZWJ 序列)与基字同时到达。 + let sizes: Vec = new[prefix..new.len() - suffix].iter().map(|cluster| cluster.chars().count()).collect(); + spread_by(&mut arrivals, first..end, &sizes, now); arrivals } } -pub(super) fn edit(ui:&Ui,owner:Id,galley:&mut Arc,reduced:bool) { - let now=ui.input(|input|input.time); - let arrivals=ui.data_mut(|data|data.get_temp_mut_or_default::(Id::unique("composer-typing-arrivals")).update(owner,galley.text(),now,reduced)); - if super::stitch_ui::animate_galley(galley,&arrivals,now,reduced)&&ui.is_rect_visible(ui.max_rect()) { - ui.ctx().request_repaint_after(std::time::Duration::from_millis(16)); + +/// 输入框的逐字扩散。每帧在 TextEdit 的 layouter 里调用一次;IME、草稿与派发仍由调用方持有。 +pub(super) fn edit(ui: &Ui, owner: Id, galley: &mut Arc, reduced: bool) { + let now = ui.input(|input| input.time); + let (arrivals, rest_at) = ui.data_mut(|data| { + let state = data.get_temp_mut_or_default::(Id::unique("composer-typing-arrivals")); + let arrivals = state.update(owner, galley.text(), now, reduced); + (arrivals, state.rest_at) + }); + let mut glow = Vec::new(); + if !reduced && now < rest_at { + let frame = super::stitch_ui::animate_galley(galley, &arrivals, now, false, true, RevealInk::user(Tokens::get(ui.ctx()).agent())); + glow = frame.glow; + if frame.entering || frame.glowing { + schedule(ui, ui.max_rect(), Pace::Full); + } else if frame.fading { + schedule(ui, ui.max_rect(), Pace::Idle); + } + } + // 输入浮层的文字要经过光涌透镜绘制,此刻还不知道 galley 的落点; + // 柔光先存起来,由 `paint_glow` 在编辑器给出位置后画在玻璃上面、光标下面。 + ui.data_mut(|data| data.insert_temp(owner.with("typing-glow"), glow)); +} + +/// 把本帧输入框的柔光画到编辑器给出的 galley 位置上。编辑器显示之后调用一次。 +pub(super) fn paint_glow(ui: &Ui, owner: Id, pos: Pos2) { + let shapes = ui.data_mut(|data| { + let id = owner.with("typing-glow"); + let shapes = data.get_temp::>(id).unwrap_or_default(); + data.remove::>(id); + shapes + }); + for mut shape in shapes { + shape.translate(pos.to_vec2()); + ui.painter().add(shape); } } #[cfg(test)] mod tests { use super::*; + + fn token(row: usize, x: f32, arrival: f64) -> TrailToken { + TrailToken { row, glyph: 0, center: pos2(x, 11.5), advance: 14.0, font: 14.0, top: 0.0, bottom: 23.0, arrival, glow: 0.0 } + } + + #[test] + fn each_character_enters_in_300ms_with_a_15ms_step_and_bounded_span() { + assert!((ENTER - 0.300).abs() < 1e-9 && (STEP - 0.015).abs() < 1e-9 && TAIL == 11); + assert_eq!(batch_step(0), 0.0); + assert_eq!(batch_step(1), 0.0); + assert_eq!(batch_step(40), STEP); + assert!((batch_step(200) * 199.0 - MAX_SPAN).abs() < 1e-9, "a long paste still spreads out within the span cap"); + assert_eq!(ease_out(0.0), 0.0); + assert_eq!(ease_out(1.0), 1.0); + assert!((ease_out(0.5) - 0.875).abs() < 1e-6, "cubic-out: half of the time covers seven eighths of the way"); + let arrivals = staggered("保留产品结构,让光线更加柔和。", 4.0); + assert_eq!(arrivals.len(), "保留产品结构,让光线更加柔和。".chars().count()); + assert!(arrivals.windows(2).all(|pair| pair[0] < pair[1] && (pair[1] - pair[0] - STEP).abs() < 1e-9)); + assert!((arrivals[0] - 4.0).abs() < 1e-9); + let ime = staggered("👩‍💻柚木", 1.0); + assert_eq!(&ime[..3], &[1.0; 3], "an IME cluster arrives as one unit"); + assert!(ime[3] < ime[4]); + assert!(duration(60) >= batch_step(60) * 59.0 + REST_AFTER - 1e-9); + } + + #[test] + fn one_arrival_raises_and_fades_softly_and_is_gone_before_rest() { + assert_eq!(wave(0.0), 0.0); + assert_eq!(wave(-5.0), 0.0); + let peak = (0..400).map(|ms| (ms, wave(f64::from(ms)))).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap(); + assert!((120..=160).contains(&peak.0), "the glow peaks shortly after arrival: {}ms", peak.0); + assert!(peak.1 > 0.6 && peak.1 < 0.65); + assert!(wave(400.0) > wave(800.0) && wave(800.0) > wave(1200.0)); + // 最坏情况:一整批字同时到达,叠加后的柔光仍要在定稿前降到看不见。 + let mut tokens: Vec<_> = (0..TAIL).map(|index| token(0, 14.0 * index as f32, 0.0)).collect(); + light_trail(&mut tokens, REST_AFTER); + assert!(tokens.iter().all(|token| token.glow < GLOW_LIMIT), "{:?}", tokens.iter().map(|token| token.glow).collect::>()); + light_trail(&mut tokens, SETTLED_AGE); + assert!(tokens.iter().all(|token| token.glow < GLOW_LIMIT * 0.8)); + } + + #[test] + fn trail_is_brightest_at_the_head_and_fades_over_about_eleven_characters() { + // 一批字同时到达:流头自己还在升起,身后几个字叠加到最亮,再向回在约 11 字内收束。 + let mut tokens: Vec<_> = (0..20).map(|index| token(0, 14.0 * index as f32, 0.0)).collect(); + light_trail(&mut tokens, 0.138); + assert!(tokens[0].glow > 0.5, "the head is lit"); + assert!(tokens[1].glow > 0.99); + assert!(tokens[1..].windows(2).all(|pair| pair[0].glow >= pair[1].glow), "light fades away from the head"); + assert!(tokens[11].glow > 0.0 && tokens[11].glow < 0.5 * tokens[1].glow, "the tail is still present but half gone at eleven characters"); + assert_eq!(tokens[13].glow, 0.0, "nothing glows beyond the tail window"); + // 逐字到达:最新的字始终是流头,光带跟着它走。`light_trail` 按由新到旧取字,和 `animate_galley` 的收集顺序一致。 + let mut typed: Vec<_> = (0..14).map(|index| token(0, 14.0 * index as f32, (13 - index) as f64 * STEP)).collect(); + light_trail(&mut typed, 0.138 + 13.0 * STEP); + assert!(typed[0].glow > 0.5 && typed[11].glow < typed[1].glow); + // 光波向回传:最新一次到达才 60ms,它身后第 2 个字已经吃到这道光,第 6 个字还没有。 + let mut wave_back: Vec<_> = (0..8).map(|index| token(0, 14.0 * index as f32, -30.0)).collect(); + wave_back[0].arrival = -0.060; + light_trail(&mut wave_back, 0.0); + assert!(wave_back[0].glow > 0.45 && wave_back[2].glow > 0.1, "the newest arrival sends light back over the characters behind it"); + assert!(wave_back[2].glow > 10.0 * wave_back[6].glow); + let mut stale = vec![token(0, 0.0, -30.0); 12]; + light_trail(&mut stale, 0.0); + assert!(stale.iter().all(|token| token.glow < 1e-20), "history never glows"); + } + + #[test] + fn glow_shapes_are_bounded_meshes_that_break_at_line_ends_and_vanish_when_settled() { + let mut tokens = vec![token(1, 200.0, 0.0), token(1, 186.0, -0.015), token(0, 30.0, -0.030)]; + light_trail(&mut tokens, 0.138); + let shapes = glow_shapes(&tokens, Color32::WHITE); + assert_eq!(shapes.len(), 3, "one halo and one band per line"); + for shape in &shapes { + let Shape::Mesh(mesh) = shape else { panic!("glow is drawn as meshes") }; + assert!(mesh.is_valid()); + } + let settled = vec![token(0, 14.0, -SETTLED_AGE); 12]; + let mut settled = settled; + light_trail(&mut settled, 0.0); + assert!(glow_shapes(&settled, Color32::WHITE).is_empty()); + } + + #[test] + fn spread_keeps_order_and_never_lags_more_than_the_span_cap() { + let mut arrivals = vec![0.0, 0.0, 1.0, 1.0, 1.0]; + spread(&mut arrivals, 2..5, 1.0); + assert_eq!(arrivals, vec![0.0, 0.0, 1.0, 1.0 + STEP, 1.0 + 2.0 * STEP]); + // 前一个字还没轮到:新字接在它后面,先后顺序不乱。 + let mut queued = vec![1.0, 1.040, 1.010, 1.010]; + spread(&mut queued, 2..4, 1.010); + assert_eq!(queued, vec![1.0, 1.040, 1.055, 1.055 + STEP]); + // 在正文中间补一个字:前后早已显示的字不被重播。 + let mut middle = vec![-5.0, -5.0, -5.0, -5.0]; + spread(&mut middle, 1..2, 3.0); + assert_eq!(middle, vec![-5.0, 3.0, -5.0, -5.0]); + // 每帧涌进一大段:步进被压缩,总跨度不超过 MAX_SPAN,先后顺序不乱。 + let mut burst = vec![1.0; 400]; + spread(&mut burst, 0..400, 1.0); + assert!(burst.windows(2).all(|pair| pair[0] < pair[1])); + assert!(burst[399] - 1.0 <= MAX_SPAN + 1e-9); + // 积压太多:这一串还没轮到的字被整体压回 MAX_SPAN,吐字不会越拖越远。 + let mut backlog = vec![1.600; 100]; + backlog.extend(vec![1.0; 100]); + spread(&mut backlog, 100..200, 1.0); + assert!(backlog.windows(2).all(|pair| pair[0] < pair[1])); + assert!(backlog[199] - 1.0 <= MAX_SPAN + 1e-9, "the backlog is compressed into the span cap"); + let mut trailing = vec![1.0, 1.0, 1.0]; + spread(&mut trailing, 3..3, 1.0); + assert_eq!(trailing, vec![1.0, 1.0, 1.0], "an empty batch changes nothing"); + } + #[test] fn typing_text_preserves_prefix_suffix_and_deletes_without_replay() { - let mut state=EditorArrival::default();let owner=Id::unique("project"); - assert_eq!(&*state.update(owner,"保持结构",0.0,false),&[-1.0;4]); - assert_eq!(&*state.update(owner,"保持柚木结构",1.0,false),&[-1.0,-1.0,1.0,1.012,-1.0,-1.0]); - assert_eq!(&*state.update(owner,"保持结构",1.1,false),&[-1.0,-1.0,-1.0,-1.0]); - assert_eq!(&*state.update(owner,"保持结构",2.0,false),&[-1.0,-1.0,-1.0,-1.0]); + let mut state = EditorArrival::default(); + let owner = Id::unique("project"); + assert_eq!(&*state.update(owner, "保持结构", 0.0, false), &[-SETTLED_AGE; 4]); + assert_eq!(&*state.update(owner, "保持柚木结构", 1.0, false), &[-SETTLED_AGE, -SETTLED_AGE, 1.0, 1.0 + STEP, -SETTLED_AGE, -SETTLED_AGE]); + assert_eq!(&*state.update(owner, "保持结构", 1.1, false), &[-SETTLED_AGE; 4]); + assert_eq!(&*state.update(owner, "保持结构", 2.0, false), &[-SETTLED_AGE; 4]); } + #[test] fn typing_text_keeps_ime_clusters_and_restored_drafts_immediate() { - let mut state=EditorArrival::default();let first=Id::unique("first");let second=Id::unique("second"); - state.update(first,"",0.0,false); - let ime=state.update(first,"👩‍💻柚木",1.0,false);assert_eq!(&ime[..3],&[1.0;3]);assert!(ime[3] AgentSemantic { + AGENT_SEMANTIC + } + pub fn dark(&self) -> bool { self.kind.is_dark() } @@ -1433,3 +1449,351 @@ pub mod live { } } } + +/// 小壹语义色(见 [`Tokens::agent_semantic`])。只服务小壹作用域,不随宿主主题变化。 +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct AgentSemantic { + /// 成功:工具完成、已保存、已核验通过。 + pub success: Color32, + /// 已核验:进度格里"已填且已核验"的格子与徽标。 + pub verified: Color32, + /// 进度:已填但尚未核验的进度格与进度条。 + pub progress: Color32, + /// 进行中、等待结果的亮色。 + pub active: Color32, + /// 冷月青:光球冷色层。 + pub jade: Color32, + /// 琥珀:光球暖色层。 + pub amber: Color32, + /// 暖玉白:光球基底与暖白层。 + pub ivory: Color32, + /// 月芯:光球中央那一点冷白。 + pub moon: Color32, + /// Agent 正文逐字扩散的柔光,也是光球外圈柔光。 + pub glow_agent: Color32, + /// 用户输入与用户气泡逐字扩散的柔光。 + pub glow_user: Color32, + /// 菜单基底:比面板深一级的不透明黑玻璃。 + pub menu_base: Color32, + /// 黑玻璃静止底与悬停点亮底。 + pub glass_rest: Color32, + pub glass_lit: Color32, + /// 模态遮罩。 + pub backdrop: Color32, + /// 叠在图片上的文字与文字衬底。 + pub on_image_text: Color32, + pub on_image_scrim: Color32, + /// 未读圆点由外到内的四层颜色。 + pub unread_dot: [Color32; 4], +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const AGENT_SEMANTIC: AgentSemantic = AgentSemantic { + success: Color32::from_rgb(91, 192, 146), + verified: Color32::from_rgb(85, 145, 190), + progress: Color32::from_rgb(181, 133, 92), + active: Color32::from_rgb(143, 211, 198), + jade: Color32::from_rgb(108, 205, 188), + amber: Color32::from_rgb(233, 157, 72), + ivory: Color32::from_rgb(250, 246, 238), + moon: Color32::from_rgb(208, 240, 233), + glow_agent: Color32::from_rgb(150, 226, 214), + glow_user: Color32::from_rgb(255, 206, 146), + menu_base: Color32::from_rgb(11, 12, 13), + glass_rest: Color32::from_rgb(17, 18, 20), + glass_lit: Color32::from_rgb(43, 45, 50), + backdrop: Color32::from_black_alpha(100), + on_image_text: Color32::WHITE, + on_image_scrim: Color32::from_black_alpha(188), + unread_dot: [ + Color32::from_rgba_unmultiplied_const(196, 203, 227, 28), + Color32::from_rgba_unmultiplied_const(213, 218, 235, 45), + Color32::from_rgb(222, 222, 237), + Color32::WHITE, + ], +}; + +/// 小壹具名阶梯:字体、间距、圆角、控件高度、图标与动效时长。 +/// 原生编辑器有自己的 `ROW_GAP`、`TOOLTIP_DELAY` 等常量,互不相干;库内不再手写这些字面量。 +/// 这是一张词汇表:第 1 批先把库内用到的档位接上,其余档位留给第 2、3 批迁移业务代码时取用, +/// 每一档的数值都由 `theme` 的快照测试钉住。 +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod agent_scale { + #![allow(dead_code, reason = "阶梯是词汇表:第 2、3 批把业务代码迁上来时逐档取用,数值由快照测试钉住")] + + /// 字体阶梯(逻辑点)。小壹只用这八档。 + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub(crate) enum Type { + /// 11:引用胶囊、代码语言标记。 + Caption, + /// 12:时间线行、元信息、字段说明。 + Meta, + /// 13:控件、菜单行、分段、按钮。 + Title, + /// 14:回复正文、输入框。 + Body, + /// 15:小标题。 + Subheading, + /// 16:分区标题。 + Heading, + /// 18:弹窗标题、一级 Markdown 标题。 + TitleLg, + /// 20:页面标题。 + Display, + } + + impl Type { + pub(crate) const fn size(self) -> f32 { + match self { + Self::Caption => 11.0, + Self::Meta => 12.0, + Self::Title => 13.0, + Self::Body => 14.0, + Self::Subheading => 15.0, + Self::Heading => 16.0, + Self::TitleLg => 18.0, + Self::Display => 20.0, + } + } + + pub(crate) fn font_id(self) -> egui::FontId { + egui::FontId::proportional(self.size()) + } + + pub(crate) fn semibold(self) -> egui::FontId { + crate::theme::semibold(self.size()) + } + } + + /// 间距阶梯:2 / 4 / 8 / 12 / 16 / 24,另有小壹作用域的默认项间距与按钮内距。 + pub(crate) mod space { + pub(crate) const XXS: f32 = 2.0; + pub(crate) const XS: f32 = 4.0; + pub(crate) const SM: f32 = 8.0; + pub(crate) const MD: f32 = 12.0; + pub(crate) const LG: f32 = 16.0; + pub(crate) const XL: f32 = 24.0; + pub(crate) const ITEM: egui::Vec2 = egui::Vec2::new(10.0, 10.0); + pub(crate) const BUTTON_PADDING: egui::Vec2 = egui::Vec2::new(12.0, 7.0); + } + + /// 圆角阶梯。 + pub(crate) mod radius { + /// 菜单行、选中胶囊的角。 + pub(crate) const ROW: f32 = 6.0; + /// 菜单与弹层。 + pub(crate) const MENU: f32 = 8.0; + /// 按钮、字段、选项。 + pub(crate) const CONTROL: f32 = 9.0; + /// 任务卡、下拉触发器、引用胶囊、拖放区。 + pub(crate) const CHIP: f32 = 12.0; + /// 对话框与玻璃分段轨。 + pub(crate) const DIALOG: f32 = 20.0; + /// 输入浮层。 + pub(crate) const COMPOSER: f32 = 24.0; + /// 输入浮层收起时的圆角(展开时过渡到 `COMPOSER - 4`)。 + pub(crate) const COMPOSER_MIN: f32 = 28.0; + } + + /// 控件高度阶梯。 + pub(crate) mod control { + /// 时间线行、徽标、引用胶囊。 + pub(crate) const ROW: f32 = 24.0; + /// 紧凑图标钮(时间线里的停止钮)。 + pub(crate) const COMPACT: f32 = 26.0; + /// 图标钮、分段、关闭钮。 + pub(crate) const STANDARD: f32 = 28.0; + /// 发送钮(正圆)。 + pub(crate) const SEND: f32 = 30.0; + /// 菜单行、分段选项。 + pub(crate) const MENU_ROW: f32 = 32.0; + /// 按钮、下拉、筛选胶囊。 + pub(crate) const DEFAULT: f32 = 34.0; + /// 带图标的命令菜单行。 + pub(crate) const COMMAND_ROW: f32 = 36.0; + } + + /// 图标尺寸阶梯。 + pub(crate) mod icon { + pub(crate) const SM: f32 = 12.0; + pub(crate) const MD: f32 = 14.0; + /// 发送钮里的箭头。 + pub(crate) const SEND: f32 = 15.0; + pub(crate) const LG: f32 = 16.0; + } + + /// 动效时长(秒)。用户定稿的三条:逐字 300ms + 15ms 步进、停止 190ms 收敛、满帧 16ms。 + pub(crate) mod motion { + use core::time::Duration; + + /// 原生控件在作用域内的过渡时长(egui 的 `animation_time`)。 + pub(crate) const NATIVE: f32 = 0.22; + /// 表面弹簧的角频率(弧度/秒):输入框展开收缩、浮层、分段选中。 + pub(crate) const SPRING_OMEGA: f32 = 20.0; + /// 弹层入场、退场与光标退场。 + pub(crate) const OVERLAY_IN: f64 = 0.22; + pub(crate) const OVERLAY_OUT: f64 = 0.16; + pub(crate) const CARET_EXIT: f64 = 0.16; + /// 悬停起落、玻璃材质明暗、行内静默按钮。 + pub(crate) const HOVER: f64 = 0.16; + pub(crate) const MATERIAL: f64 = 0.18; + pub(crate) const QUIET: f64 = 0.12; + /// 停止:流光、光涌与光球减速定格的收敛窗口,180–200ms。 + pub(crate) const STOP_SETTLE: f64 = 0.19; + /// 细边流光一周、占位色场往返。 + pub(crate) const RIM_PERIOD: f64 = 9.0; + pub(crate) const FIELD_PERIOD: f64 = 6.0; + pub(crate) const SUBJECT: f64 = 0.22; + pub(crate) const MESSAGE: f64 = 0.22; + pub(crate) const IMAGE: f64 = 0.30; + /// 拖放虚线轮廓的脉冲周期、等待三点的周期、不确定进度的往复周期。 + pub(crate) const HALO_PERIOD: f64 = 1.8; + pub(crate) const LOADER_PERIOD: f64 = 1.2; + /// 光涌:发送包络 640ms、280ms 到峰值;等待卡的光涌节奏系数。 + pub(crate) const GLOW_SEND: f64 = 0.640; + pub(crate) const GLOW_SEND_PEAK: f64 = 0.280; + pub(crate) const GLOW_WAIT_SCALE: f64 = 0.55; + /// 光球:一圈 20 秒,呼吸 5.5 秒。 + pub(crate) const ORB_LOOP: f64 = 20.0; + pub(crate) const ORB_BREATH: f64 = 5.5; + /// 逐字扩散:单字入场 300ms cubic-out,每字步进 15ms,尾韵约 11 字。 + pub(crate) const REVEAL_ENTER: f64 = 0.300; + pub(crate) const REVEAL_STEP: f64 = 0.015; + pub(crate) const REVEAL_MAX_SPAN: f64 = 0.650; + pub(crate) const REVEAL_TAIL: usize = 11; + pub(crate) const REVEAL_WAVE: f64 = 0.022; + pub(crate) const REVEAL_RISE: f64 = 0.070; + pub(crate) const REVEAL_FADE: f64 = 0.430; + pub(crate) const REVEAL_SPREAD: f32 = 9.0; + /// 重绘档位:发送脉冲、运行、交互按满帧;纯待机降到半帧;长时间无输入再降一档。 + pub(crate) const FRAME_FULL: Duration = Duration::from_millis(16); + pub(crate) const FRAME_IDLE: Duration = Duration::from_millis(32); + pub(crate) const FRAME_DEEP: Duration = Duration::from_millis(50); + /// 最后一次满帧请求之后这么久才开始平滑降频;这么久没有任何输入再降到深待机。 + pub(crate) const IDLE_AFTER: f64 = 1.5; + pub(crate) const DEEP_AFTER: f64 = 15.0; + /// 降频的时间常数:帧间隔向目标按指数靠拢,不跳变。 + pub(crate) const PACER_TAU: f32 = 0.35; + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod agent_token_tests { + use crate::theme::agent_scale::{control, icon, motion, radius, space, Type}; + use crate::theme::{AGENT_SEMANTIC, AgentSemantic, ThemeKind, Tokens}; + use egui::{Color32, FontId}; + + /// 小壹语义色逐项钉死:每一项都是确认过的观感,改动必须是有意的。 + #[test] + fn agent_semantic_colours_are_pinned() { + let semantic = AGENT_SEMANTIC; + assert_eq!(semantic.success, Color32::from_rgb(91, 192, 146)); + assert_eq!(semantic.verified, Color32::from_rgb(85, 145, 190)); + assert_eq!(semantic.progress, Color32::from_rgb(181, 133, 92)); + assert_eq!(semantic.active, Color32::from_rgb(143, 211, 198)); + assert_eq!(semantic.jade, Color32::from_rgb(108, 205, 188)); + assert_eq!(semantic.amber, Color32::from_rgb(233, 157, 72)); + assert_eq!(semantic.ivory, Color32::from_rgb(250, 246, 238)); + assert_eq!(semantic.moon, Color32::from_rgb(208, 240, 233)); + assert_eq!(semantic.glow_agent, Color32::from_rgb(150, 226, 214)); + assert_eq!(semantic.glow_user, Color32::from_rgb(255, 206, 146)); + assert_eq!(semantic.menu_base, Color32::from_rgb(11, 12, 13)); + assert_eq!(semantic.glass_rest, Color32::from_rgb(17, 18, 20)); + assert_eq!(semantic.glass_lit, Color32::from_rgb(43, 45, 50)); + assert_eq!(semantic.backdrop, Color32::from_black_alpha(100)); + assert_eq!(semantic.on_image_text, Color32::WHITE); + assert_eq!(semantic.on_image_scrim, Color32::from_black_alpha(188)); + assert_eq!(semantic.unread_dot, [ + Color32::from_rgba_unmultiplied(196, 203, 227, 28), + Color32::from_rgba_unmultiplied(213, 218, 235, 45), + Color32::from_rgb(222, 222, 237), + Color32::WHITE, + ]); + assert_eq!(semantic.glass_rest, Color32::from_rgb(17, 18, 20)); + let _: AgentSemantic = Tokens::for_kind(ThemeKind::Studio).agent_semantic(); + } + + /// 小壹作用域补齐了此前漏掉的字段:换任何宿主主题,小壹的每个表面读出来都一样, + /// 浅色宿主的分隔线、阴影、选中行与遮罩再也不会漏进来。原生主题本身一个字节不动。 + #[test] + fn agent_scope_covers_every_surface_token_and_never_touches_the_host_theme() { + for kind in ThemeKind::ALL { + let host = Tokens::for_kind(kind); + let agent = host.agent(); + assert_eq!(agent.canvas, Color32::from_rgb(18, 19, 21), "{kind:?}"); + assert_eq!(agent.chrome, agent.canvas, "{kind:?}"); + assert_eq!(agent.canvas_dot, Color32::from_gray(34), "{kind:?}"); + assert_eq!(agent.separator, agent.card_border, "{kind:?}"); + assert_eq!(agent.shadow, Color32::from_black_alpha(96), "{kind:?}"); + assert_eq!(agent.row_selected, agent.pressed, "{kind:?}"); + assert_eq!(agent.accent_text, agent.text, "{kind:?}"); + assert_eq!(agent.scrim, Color32::from_black_alpha(100), "{kind:?}"); + assert_eq!((agent.radius_sm, agent.radius, agent.radius_lg), (8.0, 16.0, 24.0), "{kind:?}"); + assert_eq!(agent.text, Color32::from_rgb(226, 228, 233), "{kind:?}"); + assert_eq!(agent_semantic_of(&agent), AGENT_SEMANTIC); + // 取小壹作用域是纯函数:宿主 Tokens 原样不动。 + let before = host; + let _ = host.agent(); + assert_eq!(host, before, "{kind:?}"); + } + } + + fn agent_semantic_of(tokens: &Tokens) -> AgentSemantic { + tokens.agent_semantic() + } + + /// 字体、间距、圆角、控件高度与图标阶梯逐项钉死;它们此前散落在各处的字面量里,现在只有一处。 + #[test] + fn agent_type_space_radius_control_and_icon_ladders_are_pinned() { + let ladder = [Type::Caption, Type::Meta, Type::Title, Type::Body, Type::Subheading, Type::Heading, Type::TitleLg, Type::Display]; + assert_eq!(ladder.map(Type::size), [11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0]); + assert!(ladder.windows(2).all(|pair| pair[0].size() < pair[1].size()), "the ladder only climbs"); + assert_eq!(Type::Body.font_id(), FontId::proportional(14.0)); + assert_eq!(Type::Body.semibold(), crate::theme::semibold(14.0)); + assert_eq!( + (space::XXS, space::XS, space::SM, space::MD, space::LG, space::XL), + (2.0, 4.0, 8.0, 12.0, 16.0, 24.0) + ); + assert_eq!(space::ITEM, egui::Vec2::new(10.0, 10.0)); + assert_eq!(space::BUTTON_PADDING, egui::Vec2::new(12.0, 7.0)); + assert_eq!( + (radius::ROW, radius::MENU, radius::CONTROL, radius::CHIP, radius::DIALOG, radius::COMPOSER, radius::COMPOSER_MIN), + (6.0, 8.0, 9.0, 12.0, 20.0, 24.0, 28.0) + ); + // 输入浮层展开收缩时的圆角公式 `28 − 4 × morph` 的两个端点。 + assert_eq!(radius::COMPOSER_MIN - radius::COMPOSER, 4.0); + assert_eq!( + (control::ROW, control::COMPACT, control::STANDARD, control::SEND, control::MENU_ROW, control::DEFAULT, control::COMMAND_ROW), + (24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0) + ); + assert_eq!((icon::SM, icon::MD, icon::SEND, icon::LG), (12.0, 14.0, 15.0, 16.0)); + } + + /// 动效时长:对话框与浮层的进退场、表面弹簧、流光周期都保持此前的取值; + /// 用户定稿的三条(逐字 300ms + 15ms、停止 190ms、满帧 16ms)单独钉一遍。 + #[test] + fn agent_motion_tokens_keep_the_dialog_motion_and_pin_the_locked_brand_values() { + assert_eq!(motion::NATIVE, 0.22); + assert_eq!(motion::SPRING_OMEGA, 20.0); + assert_eq!((motion::OVERLAY_IN, motion::OVERLAY_OUT, motion::CARET_EXIT), (0.22, 0.16, 0.16)); + assert_eq!((motion::HOVER, motion::MATERIAL, motion::QUIET), (0.16, 0.18, 0.12)); + assert_eq!((motion::RIM_PERIOD, motion::FIELD_PERIOD), (9.0, 6.0)); + assert_eq!((motion::SUBJECT, motion::MESSAGE, motion::IMAGE), (0.22, 0.22, 0.30)); + assert_eq!((motion::HALO_PERIOD, motion::LOADER_PERIOD), (1.8, 1.2)); + assert_eq!((motion::GLOW_SEND, motion::GLOW_SEND_PEAK, motion::GLOW_WAIT_SCALE), (0.640, 0.280, 0.55)); + assert_eq!((motion::ORB_LOOP, motion::ORB_BREATH), (20.0, 5.5)); + assert_eq!((motion::REVEAL_ENTER, motion::REVEAL_STEP, motion::REVEAL_MAX_SPAN), (0.300, 0.015, 0.650)); + assert_eq!(motion::REVEAL_TAIL, 11); + assert!((10..=12).contains(&motion::REVEAL_TAIL)); + assert_eq!((motion::REVEAL_WAVE, motion::REVEAL_RISE, motion::REVEAL_FADE), (0.022, 0.070, 0.430)); + assert_eq!(motion::REVEAL_SPREAD, 9.0); + assert!((0.180..=0.200).contains(&motion::STOP_SETTLE), "停止减速定格收敛在 180–200ms"); + assert_eq!(motion::STOP_SETTLE, 0.19); + assert_eq!(motion::FRAME_FULL, core::time::Duration::from_millis(16)); + assert_eq!(motion::FRAME_IDLE, core::time::Duration::from_millis(32)); + assert_eq!(motion::FRAME_DEEP, core::time::Duration::from_millis(50)); + assert_eq!((motion::IDLE_AFTER, motion::DEEP_AFTER), (1.5, 15.0)); + assert_eq!(motion::PACER_TAU, 0.35); + } +}