feat(xiaoyi): consolidate Stitch components and conversation motion
This commit is contained in:
parent
aa4c9868de
commit
ef2c97a76f
2
apps/detail-photocraft/Cargo.lock
generated
2
apps/detail-photocraft/Cargo.lock
generated
@ -4993,11 +4993,11 @@ dependencies = [
|
||||
"dispatch2",
|
||||
"eframe",
|
||||
"egui",
|
||||
"flate2",
|
||||
"fmv-macos-events",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"keyring",
|
||||
"flate2",
|
||||
"log",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
|
||||
@ -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` 维持原状。
|
||||
|
||||
@ -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<Request>, mpsc::Sender<Event>) {
|
||||
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<Request>, mpsc::Sender<Event>) {
|
||||
@ -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<egui::Event>| {
|
||||
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();
|
||||
|
||||
@ -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<f64>,
|
||||
last_input: Option<f64>,
|
||||
last: Option<f64>,
|
||||
}
|
||||
|
||||
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::<Pacer>(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<Duration> {
|
||||
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::<Vec<_>>()
|
||||
@ -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::<Vec<_>>()
|
||||
};
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -141,63 +141,28 @@ fn final_handoff(ui: &Ui, id: Id, text: &str) -> Option<ReplyHandoff> {
|
||||
|
||||
/// 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<Turn<'_>> {
|
||||
/// 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<f64>) -> 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<f64>, 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<R>(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<egui::Event>) -> 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<egui::Event>, seen: &mut Vec<String>, dots_out: &mut Vec<egui::Pos2>| {
|
||||
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<egui::Event>, lit: &mut Vec<Rect>| {
|
||||
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<String>| {
|
||||
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<egui::Event>) -> 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<egui::Event>) -> 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>(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::<AgentNotifications>(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::<Vec<_>>().join("\n");
|
||||
assert!(text.contains("历史通知") && !text.contains("当前问题"));
|
||||
assert_eq!(ctx.data(|data|data.get_temp::<AgentNotifications>(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::<AgentNotifications>(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<egui::Event>| {
|
||||
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();
|
||||
|
||||
@ -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<Tone> 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));
|
||||
}
|
||||
}
|
||||
|
||||
@ -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::<Clocks>(Id::unique("stitch-waiting-blob-clocks"))).is_none());
|
||||
assert!(ui.data(|data| data.get_temp::<Meshes>(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::<Clocks>(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::<Clocks>(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());
|
||||
|
||||
@ -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<std::ops::Range<usize>>)->Vec<egui::epaint::ClippedShape> {
|
||||
fn extract(shape:&mut egui::Shape,text:&mut Vec<egui::Shape>) {
|
||||
|
||||
@ -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::<usize>()
|
||||
};
|
||||
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);
|
||||
|
||||
@ -1,162 +1,305 @@
|
||||
//! Native Siri-style orb for the 小壹 panel.
|
||||
//! 小壹的液态微光核心:原生网格,没有音频输入,也不暗示语音能力。
|
||||
//!
|
||||
//! Adapted visually from SmoothUI's MIT-licensed Siri Orb by Eduardo Calvo:
|
||||
//! <https://smoothui.dev/r/siri-orb.json>. 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,
|
||||
//! <https://smoothui.dev/r/siri-orb.json>),许可证保留在 `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<f64>,
|
||||
}
|
||||
|
||||
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<Mesh> {
|
||||
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<Mesh> {
|
||||
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<Mesh> {
|
||||
fn get(&mut self, size: Vec2, phase: f32) -> Option<Mesh> {
|
||||
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<Animation> {
|
||||
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::<PhaseClock>(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::<MovingMeshes>(id.with("siri-orb-moving-mesh")).get(animation.phase)
|
||||
} else {
|
||||
data.get_temp_mut_or_default::<StaticMeshes>(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::<MovingMeshes>(id.with("siri-orb-moving-mesh")).get(animation.phase)
|
||||
} else {
|
||||
data.get_temp_mut_or_default::<StaticMeshes>(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<Animation>, Option<Duration>) {
|
||||
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();
|
||||
}
|
||||
|
||||
@ -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<T> {
|
||||
environment: Option<Arc<FontEnvironment>>,
|
||||
entries: VecDeque<(Id, u64, usize, Arc<T>)>,
|
||||
}
|
||||
|
||||
impl<T> Default for Settled<T> {
|
||||
fn default() -> Self {
|
||||
Self { environment: None, entries: VecDeque::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Settled<T> {
|
||||
/// 缓存此刻记住的字体环境。核对环境要读字体,而 `ui.fonts` 与 `ui.data` 取的是同一把锁,
|
||||
/// 写锁里再读就是死锁,所以要先在锁外用 [`changed_environment`] 核对,再把结论交给 [`Self::get`]。
|
||||
pub(super) fn held(&self) -> Option<Arc<FontEnvironment>> {
|
||||
self.environment.clone()
|
||||
}
|
||||
|
||||
/// 命中条件:同一个归属、同一个内容键,并且字体环境没变。
|
||||
/// `fresh` 是进锁之前核对出的新字体环境,`None` 表示没变。
|
||||
pub(super) fn get(&mut self, owner: Id, key: u64, fresh: Option<&FontEnvironment>) -> Option<Arc<T>> {
|
||||
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<T>) {
|
||||
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::<usize>() + 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<T>) {
|
||||
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<FontEnvironment> {
|
||||
held.is_none_or(|held| !held.matches(ui)).then(|| environment(ui))
|
||||
}
|
||||
|
||||
/// 取出某个缓存记住的字体环境(一次读锁),交给 [`changed_environment`] 核对。
|
||||
fn held_environment<T: 'static + Clone>(ui: &Ui, cache: Id) -> Option<Arc<FontEnvironment>> {
|
||||
ui.data(|data| data.get_temp::<Settled<T>>(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<Galley>,
|
||||
) -> Arc<Galley> {
|
||||
let fresh = changed_environment(held_environment::<Galley>(ui, galleys()).as_deref(), ui);
|
||||
if let Some(galley) = ui.data_mut(|data| data.get_temp_mut_or_default::<Settled<Galley>>(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::<Settled<Galley>>(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::<Settled<Galley>>(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<Galley> {
|
||||
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::<Settled<Galley>>(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));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
533
apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs
Normal file
533
apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_kit.rs
Normal file
@ -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<egui::WidgetText>, 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<egui::WidgetText>) -> 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<Response>,
|
||||
pub orb: Option<Rect>,
|
||||
}
|
||||
|
||||
/// 生图等待卡:玻璃光涌打底,光球与状态左对齐成一行,右侧是停止钮,图位说明压在左下角的衬底上。
|
||||
/// 只表达真实的等待:排队时光球静止、光涌不起伏;最小化或不可见时不安排任何重绘。
|
||||
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<R>(
|
||||
ui: &mut Ui,
|
||||
id: egui::Id,
|
||||
columns: GridColumns,
|
||||
gap: f32,
|
||||
items: usize,
|
||||
mut cell: impl FnMut(&mut Ui, usize) -> R,
|
||||
) -> egui::InnerResponse<Vec<R>> {
|
||||
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<String> {
|
||||
fn walk(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
@ -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<char> {
|
||||
(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::<String>(), "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 秒");
|
||||
}
|
||||
}
|
||||
1060
apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs
Normal file
1060
apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -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(), |_| {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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<f64> {
|
||||
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<Id>,text:String,arrivals:Arc<Vec<f64>>,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<f64> = 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<f64> {
|
||||
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<usize>, now: f64) {
|
||||
spread_by(arrivals, added, &[], now);
|
||||
}
|
||||
|
||||
/// `spread` 的按字素簇版本:`text` 是 `added` 这一段的原文,组合符号、ZWJ 序列与它的基字算一格、同时到达。
|
||||
pub(super) fn spread_text(arrivals: &mut [f64], added: Range<usize>, text: &str, now: f64) {
|
||||
if text.chars().count() != added.len() {
|
||||
spread(arrivals, added, now);
|
||||
return;
|
||||
}
|
||||
let sizes: Vec<usize> = text.graphemes(true).map(|cluster| cluster.chars().count()).collect();
|
||||
spread_by(arrivals, added, &sizes, now);
|
||||
}
|
||||
|
||||
fn spread_by(arrivals: &mut [f64], added: Range<usize>, sizes: &[usize], now: f64) {
|
||||
if added.is_empty() || added.end > arrivals.len() {
|
||||
return;
|
||||
}
|
||||
let clustered = sizes.iter().sum::<usize>() == 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<Shape> {
|
||||
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<Shape> {
|
||||
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<Id>, text: String, arrivals: Arc<Vec<f64>>, reduced: bool, rest_at: f64 }
|
||||
|
||||
impl EditorArrival {
|
||||
fn update(&mut self,owner:Id,text:&str,now:f64,reduced:bool)->Arc<Vec<f64>> {
|
||||
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<Vec<f64>> {
|
||||
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<f64> {
|
||||
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<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_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<f64> {
|
||||
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::<usize>();
|
||||
let end = arrivals.len() - tail;
|
||||
// 新进的字素簇按簇铺开:簇内的字符(组合符号、ZWJ 序列)与基字同时到达。
|
||||
let sizes: Vec<usize> = 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<egui::Galley>,reduced:bool) {
|
||||
let now=ui.input(|input|input.time);
|
||||
let arrivals=ui.data_mut(|data|data.get_temp_mut_or_default::<EditorArrival>(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<egui::Galley>, 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::<EditorArrival>(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::<Vec<Shape>>(id).unwrap_or_default();
|
||||
data.remove::<Vec<Shape>>(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::<Vec<_>>());
|
||||
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]<ime[4]);
|
||||
let restored=state.update(second,"已恢复的草稿",2.0,false);assert!(restored.iter().all(|at|*at<=1.0));
|
||||
state.update(second,"已恢复的草稿新",3.0,false);
|
||||
let reduced=state.update(second,"已恢复的草稿新",3.05,true);assert!(reduced.iter().all(|at|*at<3.0));
|
||||
assert_eq!(state.update(second,"已恢复的草稿新",3.1,false),reduced);
|
||||
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] < ime[4]);
|
||||
let restored = state.update(second, "已恢复的草稿", 2.0, false);
|
||||
assert!(restored.iter().all(|at| *at <= 1.0));
|
||||
state.update(second, "已恢复的草稿新", 3.0, false);
|
||||
let reduced = state.update(second, "已恢复的草稿新", 3.05, true);
|
||||
assert!(reduced.iter().all(|at| *at < 3.0));
|
||||
assert_eq!(state.update(second, "已恢复的草稿新", 3.1, false), reduced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resting_editor_reports_when_nothing_is_left_to_animate() {
|
||||
let mut state = EditorArrival::default();
|
||||
let owner = Id::unique("rest");
|
||||
state.update(owner, "你好", 0.0, false);
|
||||
assert!(state.rest_at < 0.0, "a restored draft starts out settled");
|
||||
state.update(owner, "你好世界", 0.5, false);
|
||||
assert!((state.rest_at - (0.5 + STEP + REST_AFTER)).abs() < 1e-9, "the two new characters arrive at 0.5 and one step later; the editor rests a fixed while after the last");
|
||||
assert!(rest_at(&[]) < 0.0, "an empty editor has nothing to animate");
|
||||
}
|
||||
}
|
||||
|
||||
@ -876,9 +876,25 @@ impl Tokens {
|
||||
self.radius_sm = 8.0;
|
||||
self.radius = 16.0;
|
||||
self.radius_lg = 24.0;
|
||||
// 此前这些字段在 Agent 作用域里仍是宿主主题的值:浅色宿主下会拿到浅色的分隔线、
|
||||
// 阴影、选中行与遮罩。小壹是独立的深色材质,在这里一次补齐;库内目前没有读取点,外观不变。
|
||||
self.chrome = self.canvas;
|
||||
self.canvas_dot = Color32::from_gray(34);
|
||||
self.separator = self.card_border;
|
||||
self.shadow = Color32::from_black_alpha(96);
|
||||
self.row_selected = self.pressed;
|
||||
self.accent_text = self.text;
|
||||
self.scrim = Color32::from_black_alpha(100);
|
||||
self
|
||||
}
|
||||
|
||||
/// 小壹语义色:`agent()` 没有覆盖的成功、已核验、进度、叠图等具名颜色。
|
||||
/// 它们不进入原生 `Tokens`,原生十四套主题一个字节不动;库与业务代码不再手写 RGB。
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn agent_semantic(&self) -> 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);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user