From 27b93c04ab94aa3c51f46e661c982650c1275521 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Mon, 30 Nov 2026 15:49:19 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=8F=E5=A3=B9=E8=B5=84=E6=96=99=E9=A1=B5?= =?UTF-8?q?=E5=8A=A0=E7=B2=BE=E4=BF=AE=E5=BC=80=E5=85=B3=EF=BC=8C=E5=88=B6?= =?UTF-8?q?=E4=BD=9C=E8=BF=9B=E5=BA=A6=E5=A4=B4=E9=83=A8=E5=8A=A0=E5=81=9C?= =?UTF-8?q?=E6=AD=A2=E8=8F=9C=E5=8D=95=E4=B8=8E=E6=97=B6=E9=97=B4=E9=A2=84?= =?UTF-8?q?=E7=AE=97=EF=BC=88R5-Z72=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 资料页"输出内容"下方新增"精修"开关与说明;开工后只读,暂停时可改,切换时登记 production-settings 操作 - 进度头部换成一个"停止"按钮,点开菜单三选一:只暂停直接执行,停止目标、停止并交付先确认;已暂停时显示"继续制作",菜单只剩两项 - 停止中、交付中置灰并显示进度,已结束、已交付显示结果,失败用提醒色原样显示错误 - 标题行下方显示"已用 N 分钟 / 预算 M 分钟",超出后提醒色显示"已超出预算,将自动交付" - 按钮只登记 jiansun.action 同名操作,帧末经控制通道同一入口执行;停止与预算状态待停止任务合入后接上 --- .../crates/ui-egui/src/jiansun.rs | 12 +- .../crates/ui-egui/src/jiansun/agent_panel.rs | 34 +- .../crates/ui-egui/src/jiansun/creation.rs | 6 +- .../src/jiansun/production_controls.rs | 598 ++++++++++++++++++ .../ui-egui/src/jiansun/stitch_timeline.rs | 172 ++++- .../crates/ui-egui/src/jiansun/stitch_ui.rs | 41 +- 6 files changed, 850 insertions(+), 13 deletions(-) create mode 100644 apps/detail-photocraft/crates/ui-egui/src/jiansun/production_controls.rs diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index c76ef3b7..f52a43f7 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -45,6 +45,7 @@ pub mod template_preview; mod professional_mode; mod creation; mod product_production; +mod production_controls; pub(crate) use creation::creation_escape_active; mod creation_reads; mod pi_bridge; @@ -4416,6 +4417,7 @@ pub(crate) fn begin_frame(app: &mut PhotocraftApp) { } pub(crate) fn end_frame(app: &mut PhotocraftApp, ctx: &egui::Context) { + production_controls::run_queued_actions(app, ctx); let doc = app.session.active().map(|s| s.doc.id.0); let Some(w) = app.jiansun.as_mut() else { return }; w.agent_images.finish_pins(); @@ -5295,7 +5297,7 @@ mod tests { /// 外部 QA 脚本与 `jiansun.state` 控制通道读取的 `panel_geometry` 键,按字母序冻结。 /// 只许原样保留:改名、删除都会让脚本读不到矩形。新增键必须同步外部脚本并登记在这里。 - const PANEL_GEOMETRY_KEYS: [&str; 92] = [ + const PANEL_GEOMETRY_KEYS: [&str; 99] = [ "agentStatus", "attachmentRemovals", "backgroundDocument", @@ -5349,13 +5351,20 @@ mod tests { "processingLightMode", "processingOpacity", "processingPlaceholder", + "productionBudget", "productionCopyCells", "productionImageCells", "productionImagesTag", "productionProgress", "productionProgressRail", "productionProgressTag", + "productionResume", "productionShelf", + "productionStopConfirm", + "productionStopDeliver", + "productionStopEnd", + "productionStopPause", + "productionStopStatus", "productionTitle", "productionWorkers", "productionWorkersTag", @@ -5448,6 +5457,7 @@ mod tests { include_str!("jiansun/workflow_bridge.rs"), include_str!("jiansun/workflow_export.rs"), include_str!("jiansun/workspace_navigation.rs"), + include_str!("jiansun/production_controls.rs"), ]; let marker = "panel_geometry[\""; let mut found = std::collections::BTreeSet::new(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index 0f725701..2ad29077 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -2687,8 +2687,10 @@ impl Workspace { waiting_canvas: self.workflow.waiting_canvas(output), slots: if selected && show_work { slots() } else { Vec::new() } } }).collect(); + let head = super::production_controls::HeadControls::read(&self.production_control_state()); + let resume_ready = self.can_resume_product(); let budget = if let Some(run) = run { - GoalBudget::Time { elapsed: run.elapsed(), limit: None } + GoalBudget::Time { elapsed: run.elapsed(), limit: head.budget.and_then(|budget| Duration::try_from_secs_f64(budget.budget_minutes * 60.0).ok()) } } else if let Some(used) = usage_count(&progress["tokensUsed"]) { GoalBudget::Tokens { used, limit: usage_count(&progress["tokenBudget"]) } } else { @@ -2703,7 +2705,7 @@ impl Workspace { column.spacing_mut().item_spacing.y = 4.0; let result = timeline::goal_progress_panel(&mut column, id, GoalProgressPanel { title, state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, - workers: &worker_states, roadmap: Some(&stages), + workers: &worker_states, roadmap: Some(&stages), controls: run.is_some().then(|| head.view(resume_ready)), }, self.reduce_motion || self.product_view_detached(), |index| { let row = &image_source[index]; let status = match image_cells[index] { Cell::Verified => "已核验", Cell::Filled => "已上画布", Cell::Empty => "待填" }; @@ -2739,6 +2741,28 @@ impl Workspace { self.panel_geometry["taskStop"] = rect_value(stop.rect); if stop.clicked() { self.stop_production(); } } + if let Some(controls) = &result.controls { + use timeline::StopMode; + // "停止"沿用外部脚本已在读的 taskStop,点开是停止菜单;"只暂停"直接执行,另外两项先确认。 + let choice = |mode| controls.choices.iter().find(|(shown, _)| *shown == mode).map_or(Value::Null, |(_, rect)| rect_value(*rect)); + self.panel_geometry["taskStop"] = rect_value(controls.stop.rect); + self.panel_geometry["productionResume"] = controls.resume.as_ref().map_or(Value::Null, |resume| rect_value(resume.rect)); + self.panel_geometry["productionStopPause"] = choice(StopMode::Pause); + self.panel_geometry["productionStopEnd"] = choice(StopMode::End); + self.panel_geometry["productionStopDeliver"] = choice(StopMode::Deliver); + self.panel_geometry["productionStopStatus"] = controls.status.map_or(Value::Null, rect_value); + self.panel_geometry["productionBudget"] = controls.budget.map_or(Value::Null, rect_value); + if controls.resume.as_ref().is_some_and(Response::clicked) { + self.resume_product_production(app); + } + match controls.chosen { + Some(StopMode::Pause) => super::production_controls::queue_action(ui.ctx(), "production-stop", + super::production_controls::stop_input(StopMode::Pause)), + Some(mode) => super::production_controls::open_stop_confirm(ui.ctx(), mode), + None => {} + } + } + self.stop_confirm_ui(ui, head.phase().ready()); ui.advance_cursor_after_rect(column.min_rect()); ui.add_space(2.0); } @@ -2922,6 +2946,12 @@ impl Workspace { self.panel_geometry["productionProgressTag"] = Value::Null; self.panel_geometry["productionImageCells"] = Value::Null; self.panel_geometry["productionCopyCells"] = Value::Null; + self.panel_geometry["productionResume"] = Value::Null; + self.panel_geometry["productionStopPause"] = Value::Null; + self.panel_geometry["productionStopEnd"] = Value::Null; + self.panel_geometry["productionStopDeliver"] = Value::Null; + self.panel_geometry["productionStopStatus"] = Value::Null; + self.panel_geometry["productionBudget"] = Value::Null; if self.pi_review && self.busy.is_none() { self.status_row(ui, "info", "原建议未执行", t.warning, |this, ui| { if super::stitch_ui::action_button(ui, "放弃原建议", super::stitch_ui::ButtonRole::Secondary, true).on_hover_text("保留原响应和已完成的修改;不重新运行模型或工具").clicked() { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index 825df9d8..c88b55e8 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -992,7 +992,7 @@ impl Workspace { fn catalog(&mut self, app: &mut PhotocraftApp, kind: &str, query: String) { self.request_creation_catalog(app, kind, query, false); } - fn control_geometry(&mut self, name: &str, rect: egui::Rect) { + pub(super) fn control_geometry(&mut self, name: &str, rect: egui::Rect) { self.creation_view_geometry[name] = rect_value(rect); self.creation_view_geometry["controls"][name] = rect_value(rect); } @@ -1314,7 +1314,7 @@ impl Workspace { brief_section_break(ui); } - fn output_tags_ui(&mut self, ui: &mut Ui) { + pub(super) fn output_tags_ui(&mut self, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { ui.label("输出内容"); for (id, text) in READY_OUTPUT_TAGS { @@ -1368,6 +1368,8 @@ impl Workspace { ui.add_space(6.0); self.output_tags_ui(ui); ui.add_space(6.0); + self.refinement_ui(ui); + ui.add_space(6.0); self.delivery_directory_control(app, ui, editable); ui.add_space(6.0); ui.horizontal_wrapped(|ui| { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_controls.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_controls.rs new file mode 100644 index 00000000..7d6f77a5 --- /dev/null +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_controls.rs @@ -0,0 +1,598 @@ +//! 制作控制的界面:资料页的精修开关、制作进度头部的停止菜单与时间预算行。 +//! +//! 这里只做界面。状态读的是 `jiansun.state` 里约定的 `productionSettings` / `productionStop` / +//! `productionBudget`;点击时登记 `jiansun.action` 的同名操作,等本帧画完、工作台放回之后, +//! 由 `run_queued_actions` 经控制通道的同一个入口执行。动作背后的逻辑在各自的任务里。 + +use super::stitch_timeline::{ProductionControls, StopMode, StopPhase, TimeBudget}; +use super::stitch_ui as kit; +use super::{PhotocraftApp, Tokens, Ui, Value, Workspace, json}; +use crate::theme::agent_scale::Type; +use egui::RichText; + +const REFINEMENT_OFF: &str = "不精修:每个图位最多 2 张候选,约 45 分钟内交付"; +const REFINEMENT_ON: &str = "精修:每个图位最多 4 张候选,多轮复核修正,约 2 小时内交付"; +pub(super) const END_CONFIRM: &str = "将结束本轮制作,不交付。已做的内容保留在画布上,之后可以重新一键生成。确定吗?"; +pub(super) const DELIVER_CONFIRM: &str = "将停止制作,把当前成果连同未解决的问题一起交付到成品目录。确定吗?"; + +pub(super) fn refinement_caption(refinement: bool) -> &'static str { + if refinement { REFINEMENT_ON } else { REFINEMENT_OFF } +} + +/// `production-stop` 的输入:`mode` 取 `pause` / `end` / `deliver`。 +pub(super) fn stop_input(mode: StopMode) -> Value { + json!({"mode": match mode { StopMode::Pause => "pause", StopMode::End => "end", StopMode::Deliver => "deliver" }}) +} + +/// 本帧界面登记、待执行的操作。只放在界面内存里:不进工程状态,也不跨帧保留。 +fn queue_id() -> egui::Id { + egui::Id::unique("xiaoyi-production-control-actions") +} + +pub(super) fn queue_action(ctx: &egui::Context, method: &str, input: Value) { + ctx.data_mut(|data| data.get_temp_mut_or_default::>(queue_id()).push((method.to_owned(), input))); +} + +#[cfg(test)] +pub(super) fn queued_actions(ctx: &egui::Context) -> Vec<(String, Value)> { + ctx.data(|data| data.get_temp::>(queue_id())).unwrap_or_default() +} + +/// 帧末执行界面登记的操作:与控制通道 `jiansun.action` 走同一个入口,失败时原样提示。 +pub(super) fn run_queued_actions(app: &mut PhotocraftApp, ctx: &egui::Context) { + let actions = ctx.data_mut(|data| data.remove_temp::>(queue_id())).unwrap_or_default(); + for (method, input) in actions { + if let Err(error) = super::action_in_ui(app, ctx, &method, input) + && let Some(workspace) = app.jiansun.as_mut() + { + workspace.error = error; + } + } +} + +/// 约定的三项状态,形状与 `jiansun.state` 里的同名字段一致。 +pub(super) struct ControlState { + pub settings: Value, + pub stop: Value, + pub budget: Value, +} + +/// 进度头部要显示的制作控制,从约定状态里读出、自己持有失败原文。 +pub(super) struct HeadControls { + stop: String, + error: String, + pub budget: Option, +} + +impl HeadControls { + pub(super) fn read(state: &ControlState) -> Self { + let error = match &state.stop["error"] { + Value::String(text) => text.clone(), + Value::Null => "停止没有完成".into(), + other => other.to_string(), + }; + let budget = state.budget["budgetMinutes"].as_f64().filter(|minutes| minutes.is_finite() && *minutes > 0.0) + .zip(state.budget["elapsedMinutes"].as_f64().filter(|minutes| minutes.is_finite())) + .map(|(budget_minutes, elapsed_minutes)| TimeBudget { elapsed_minutes, budget_minutes }); + Self { stop: state.stop["state"].as_str().unwrap_or("idle").to_owned(), error, budget } + } + + pub(super) fn phase(&self) -> StopPhase<'_> { + match self.stop.as_str() { + "stopping" => StopPhase::Stopping, + "paused" => StopPhase::Paused, + "ended" => StopPhase::Ended, + "delivering" => StopPhase::Delivering, + "delivered" => StopPhase::Delivered, + "failed" => StopPhase::Failed(&self.error), + _ => StopPhase::Idle, + } + } + + pub(super) fn view(&self, resume_ready: bool) -> ProductionControls<'_> { + ProductionControls { stop: self.phase(), budget: self.budget, resume_ready } + } +} + +/// 确认浮层的状态:哪种停法、是否打开。关闭后仍保留停法,退场动画才画得出原来的内容。 +fn stop_confirm_id() -> egui::Id { + egui::Id::unique("xiaoyi-production-stop-confirm") +} + +pub(super) fn open_stop_confirm(ctx: &egui::Context, mode: StopMode) { + ctx.data_mut(|data| data.insert_temp(stop_confirm_id(), (mode, true))); +} + +impl Workspace { + /// 读取约定的制作控制状态。精修设置由宿主写在模板工作流里;停止与预算的状态由停止任务提供, + /// 合入前这里读到的是空值,界面按"空闲、未报预算"显示。合入时把 `stop` / `budget` 换成对方的状态读取。 + pub(super) fn production_control_state(&self) -> ControlState { + ControlState { + settings: self.template_workflow.get("productionSettings").cloned().unwrap_or(Value::Null), + stop: Value::Null, + budget: Value::Null, + } + } + + /// 精修设置只在未开工或暂停时可改;宿主还没给出设置时只显示缺省值。 + fn refinement_editable(&self, settings: &Value) -> bool { + settings.is_object() && self.busy.is_none() && !self.unknown + && (self.product_production.is_none() || self.has_paused_production()) + } + + /// 资料页"输出内容"下方的精修开关与说明。开工后只读显示当前模式,暂停时可以改。 + pub(super) fn refinement_ui(&mut self, ui: &mut Ui) { + let settings = self.production_control_state().settings; + let reported = settings["refinement"] == true; + // 请求发出到宿主回执之间,开关停在用户选的位置;回执到了或请求没被受理,就以宿主状态为准。 + let hold = egui::Id::unique("xiaoyi-refinement-requested"); + let requested = ui.data(|data| data.get_temp::(hold)) + .filter(|value| self.busy.as_deref() == Some("production-settings") && *value != reported); + if requested.is_none() { + ui.data_mut(|data| { data.remove_temp::(hold); }); + } + let shown = requested.unwrap_or(reported); + let editable = self.refinement_editable(&settings); + let t = Tokens::get(ui.ctx()).agent(); + let row = ui.horizontal(|ui| { + ui.label("精修"); + let mut value = shown; + let switch = kit::bare_switch(ui, egui::Id::unique("xiaoyi-refinement-switch"), &mut value, "精修", editable, self.reduce_motion); + if switch.changed() { + queue_action(ui.ctx(), "production-settings", json!({"refinement": value})); + ui.data_mut(|data| data.insert_temp(hold, value)); + } + switch + }); + let caption = ui.add(egui::Label::new(RichText::new(refinement_caption(shown)).size(Type::Title.size()).color(t.text_dim)).wrap()); + self.control_geometry("refinement", row.inner.rect); + self.control_geometry("refinement-row", row.response.rect); + self.control_geometry("refinement-caption", caption.rect); + } + + /// "停止目标"与"停止并交付"的确认浮层,沿用完结项目的确认样式。每帧都要调用,关闭时的退场动画才走得完。 + pub(super) fn stop_confirm_ui(&mut self, ui: &mut Ui, ready: bool) { + let id = stop_confirm_id(); + let (mode, mut open) = ui.data(|data| data.get_temp::<(StopMode, bool)>(id)).unwrap_or((StopMode::Deliver, false)); + let (text, action) = match mode { + StopMode::End => (END_CONFIRM, "结束制作"), + StopMode::Pause | StopMode::Deliver => (DELIVER_CONFIRM, "确定交付"), + }; + let (mut confirm, mut cancel) = (None, None); + let closed = kit::dialog(ui, id.with("dialog"), mode.title(), open, self.reduce_motion, 360.0, |ui| { + ui.label(text); + ui.add_space(8.0); + ui.horizontal(|ui| { + cancel = Some(kit::action_button(ui, "取消", kit::ButtonRole::Secondary, true)); + confirm = Some(kit::action_button(ui, action, kit::ButtonRole::Primary, ready)); + }); + }); + self.panel_geometry["productionStopConfirm"] = confirm.as_ref().map_or(Value::Null, |button| super::agent_panel::rect_value(button.rect)); + if open && confirm.as_ref().is_some_and(egui::Response::clicked) { + queue_action(ui.ctx(), "production-stop", stop_input(mode)); + open = false; + } + if closed || cancel.as_ref().is_some_and(egui::Response::clicked) { + open = false; + } + ui.data_mut(|data| data.insert_temp(id, (mode, open))); + } +} + +#[cfg(test)] +mod tests { + use super::super::stitch_timeline::{GoalBudget, GoalProgressPanel, GoalProgressResponse, StagePhase, goal_progress_panel}; + use super::super::stitch_state::RunState; + use super::super::agent_stream::Cell; + use super::super::{Event, Request, creation}; + use super::*; + use egui::vec2; + use std::sync::mpsc; + use std::time::Duration; + + struct Fixture { w: Workspace, app: PhotocraftApp, requests: mpsc::Receiver, _events: mpsc::Sender } + + fn workspace() -> Fixture { + let (tx, requests) = mpsc::channel(); + let (events, rx) = mpsc::channel(); + let mut w = Workspace::new(tx, rx); + while requests.try_recv().is_ok() {} + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":1440,"height":1800})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + w.busy = None; + w.unknown = false; + w.reduce_motion = true; + w.creation_brief = creation::empty_brief(); + Fixture { w, app, requests, _events: events } + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(&ctx); + ctx + } + + fn frame(ctx: &egui::Context, events: Vec, size: egui::Vec2, mut paint: impl FnMut(&mut Ui)) { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + ctx.run_ui(input, |ui| { kit::scope(ui, |ui| paint(ui)); }).drop_without_applying_deltas(); + } + + fn rect_of(value: &Value) -> egui::Rect { + let rect = value.as_array().unwrap_or_else(|| panic!("missing rect {value}")); + let at = |index: usize| rect[index].as_f64().unwrap() as f32; + egui::Rect::from_min_size(egui::pos2(at(0), at(1)), vec2(at(2), at(3))) + } + + fn click(pos: egui::Pos2) -> Vec { + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }, + ] + } + + fn control(w: &Workspace, name: &str) -> egui::Rect { + rect_of(&w.creation_view_geometry["controls"][name]) + } + + fn texts(ctx: &egui::Context, size: egui::Vec2, events: Vec, mut paint: impl FnMut(&mut Ui)) -> Vec { + let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }; + let output = ctx.run_ui(input, |ui| { kit::scope(ui, |ui| paint(ui)); }); + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &output.shapes { + walk(&clipped.shape, &mut out); + } + output.drop_without_applying_deltas(); + out + } + + fn state(stop: Value, budget: Value) -> ControlState { + ControlState { settings: Value::Null, stop, budget } + } + + #[test] + fn refinement_captions_follow_the_design_copy() { + assert_eq!(refinement_caption(false), "不精修:每个图位最多 2 张候选,约 45 分钟内交付"); + assert_eq!(refinement_caption(true), "精修:每个图位最多 4 张候选,多轮复核修正,约 2 小时内交付"); + } + + #[test] + fn stop_modes_map_to_the_agreed_action_input() { + assert_eq!(stop_input(StopMode::Pause), json!({"mode":"pause"})); + assert_eq!(stop_input(StopMode::End), json!({"mode":"end"})); + assert_eq!(stop_input(StopMode::Deliver), json!({"mode":"deliver"})); + assert_eq!(StopPhase::Idle.choices(), &[StopMode::Pause, StopMode::End, StopMode::Deliver]); + assert_eq!(StopPhase::Paused.choices(), &[StopMode::End, StopMode::Deliver], "a paused run cannot pause again"); + assert_eq!((StopMode::Pause.title(), StopMode::Pause.detail()), ("只暂停", "停在当前步骤,进度保留,随时可以继续")); + assert_eq!((StopMode::End.title(), StopMode::End.detail()), ("停止目标", "结束本轮制作,不交付,已做的内容保留在画布上")); + assert_eq!((StopMode::Deliver.title(), StopMode::Deliver.detail()), ("停止并交付", "把现有成果交付,没做完的写进已知问题")); + } + + #[test] + fn budget_and_stop_state_read_the_agreed_shapes() { + let idle = HeadControls::read(&state(Value::Null, Value::Null)); + assert_eq!(idle.view(true), ProductionControls { stop: StopPhase::Idle, budget: None, resume_ready: true }); + for (name, phase) in [("stopping", StopPhase::Stopping), ("paused", StopPhase::Paused), ("ended", StopPhase::Ended), + ("delivering", StopPhase::Delivering), ("delivered", StopPhase::Delivered), ("idle", StopPhase::Idle)] { + let head = HeadControls::read(&state(json!({"mode":"end","state":name,"reason":null,"error":null}), Value::Null)); + assert_eq!(head.phase(), phase, "{name}"); + } + let failed = HeadControls::read(&state(json!({"mode":"deliver","state":"failed","reason":"用户手动停止并交付","error":"成品目录不可写:D:\\成品"}), Value::Null)); + assert_eq!(failed.phase(), StopPhase::Failed("成品目录不可写:D:\\成品"), "the host error is shown verbatim"); + assert!(failed.phase().ready() && StopPhase::Paused.ready() && StopPhase::Idle.ready()); + for busy in [StopPhase::Stopping, StopPhase::Delivering, StopPhase::Ended, StopPhase::Delivered] { + assert!(!busy.ready(), "{busy:?}"); + } + let structured = HeadControls::read(&state(json!({"state":"failed","error":{"code":"E1"}}), Value::Null)); + assert_eq!(structured.phase(), StopPhase::Failed(r#"{"code":"E1"}"#)); + let budget = HeadControls::read(&state(Value::Null, json!({"startedAt":1,"budgetMinutes":45,"elapsedMinutes":23.6}))).budget.unwrap(); + assert_eq!(budget.text(), "已用 23 分钟 / 预算 45 分钟"); + assert!(!budget.over()); + let over = HeadControls::read(&state(Value::Null, json!({"startedAt":1,"budgetMinutes":45,"elapsedMinutes":45.5}))).budget.unwrap(); + assert!(over.over()); + assert_eq!(over.text(), "已超出预算,将自动交付"); + for invalid in [json!({"budgetMinutes":0,"elapsedMinutes":3}), json!({"budgetMinutes":45}), json!({"elapsedMinutes":3}), json!(null)] { + assert!(HeadControls::read(&state(Value::Null, invalid.clone())).budget.is_none(), "{invalid}"); + } + } + + #[test] + fn refinement_switch_requests_the_agreed_action_and_holds_until_the_reply() { + let Fixture { mut w, requests, .. } = workspace(); + let ctx = context(); + let size = vec2(720.0, 200.0); + w.template_workflow = json!({"productionSettings":{"refinement":false,"timeBudgetMinutes":45}}); + frame(&ctx, vec![], size, |ui| w.refinement_ui(ui)); + let switch = control(&w, "refinement"); + assert!(switch.width() <= 44.0, "the switch keeps its own width instead of the whole row: {switch:?}"); + assert!(control(&w, "refinement-row").bottom() <= control(&w, "refinement-caption").top() + 0.5, "the caption sits under its row"); + frame(&ctx, click(switch.center()), size, |ui| w.refinement_ui(ui)); + assert_eq!(queued_actions(&ctx), vec![("production-settings".to_owned(), json!({"refinement":true}))]); + assert!(requests.try_recv().is_err(), "the switch only registers the action; it never talks to the host itself"); + // 回执前:宿主仍报"不精修",开关与说明停在用户选的"精修"。 + ctx.data_mut(|data| data.remove_temp::>(queue_id())); + w.busy = Some("production-settings".into()); + let drawn = texts(&ctx, size, vec![], |ui| w.refinement_ui(ui)); + assert!(drawn.iter().any(|text| text == refinement_caption(true)), "{drawn:?}"); + // 请求没被受理:开关回到宿主状态。 + w.busy = None; + let drawn = texts(&ctx, size, vec![], |ui| w.refinement_ui(ui)); + assert!(drawn.iter().any(|text| text == refinement_caption(false)), "{drawn:?}"); + assert!(queued_actions(&ctx).is_empty()); + } + + #[test] + fn refinement_is_read_only_once_production_runs_and_editable_while_paused() { + let Fixture { mut w, .. } = workspace(); + let ctx = context(); + let size = vec2(720.0, 200.0); + // 宿主还没给出设置:显示缺省的"不精修",不能改。 + frame(&ctx, vec![], size, |ui| w.refinement_ui(ui)); + let drawn = texts(&ctx, size, vec![], |ui| w.refinement_ui(ui)); + assert!(drawn.iter().any(|text| text == refinement_caption(false))); + frame(&ctx, click(control(&w, "refinement").center()), size, |ui| w.refinement_ui(ui)); + assert!(queued_actions(&ctx).is_empty(), "no settings from the host yet"); + w.template_workflow = json!({"productionSettings":{"refinement":true,"timeBudgetMinutes":120}}); + w.product_checkpoint = json!({"active":true,"phase":"paused"}); + assert!(w.refinement_editable(&w.production_control_state().settings), "a paused production can change its mode"); + w.busy = Some("pi-agent".into()); + assert!(!w.refinement_editable(&w.production_control_state().settings), "busy work keeps the mode read-only"); + w.busy = None; + frame(&ctx, vec![], size, |ui| w.refinement_ui(ui)); + let drawn = texts(&ctx, size, vec![], |ui| w.refinement_ui(ui)); + assert!(drawn.iter().any(|text| text == refinement_caption(true)), "the current mode is shown: {drawn:?}"); + frame(&ctx, click(control(&w, "refinement").center()), size, |ui| w.refinement_ui(ui)); + assert_eq!(queued_actions(&ctx), vec![("production-settings".to_owned(), json!({"refinement":false}))]); + } + + #[test] + fn queued_actions_run_through_the_control_entry_and_report_failures() { + let Fixture { w, mut app, .. } = workspace(); + app.jiansun = Some(w); + let ctx = egui::Context::default(); + queue_action(&ctx, "production-stop", stop_input(StopMode::Pause)); + run_queued_actions(&mut app, &ctx); + assert!(queued_actions(&ctx).is_empty(), "each registered action runs once"); + let error = app.jiansun.as_ref().unwrap().error.clone(); + match super::super::action_in_ui(&mut app, &ctx, "production-stop", stop_input(StopMode::Pause)) { + Ok(_) => assert!(error.is_empty(), "an accepted action leaves no error"), + Err(message) => assert_eq!(error, message, "a refused action is reported as the control entry words it"), + } + } + + struct Panel { pipeline: Vec<(&'static str, StagePhase)>, image_cells: Vec, copy_cells: Vec } + + fn panel_fixture() -> Panel { + Panel { + pipeline: vec![("详情", StagePhase::Current(0.4)), ("主图", StagePhase::Queued), ("SKU", StagePhase::Queued)], + image_cells: vec![Cell::Verified, Cell::Verified, Cell::Filled, Cell::Empty, Cell::Empty, Cell::Empty], + copy_cells: vec![Cell::Verified, Cell::Filled, Cell::Filled, Cell::Empty], + } + } + + fn show(ui: &mut Ui, id: &str, fixture: &Panel, controls: Option>) -> GoalProgressResponse { + let (state, title) = match controls.map(|controls| controls.stop) { + Some(StopPhase::Paused) => (RunState::WaitingResume, "详情页首屏"), + Some(StopPhase::Ended) => (RunState::Stopped, "详情页首屏"), + Some(StopPhase::Delivered) => (RunState::Completed, "详情页首屏"), + _ => (RunState::Running, "正在制作详情页首屏"), + }; + goal_progress_panel(ui, egui::Id::unique(id), GoalProgressPanel { + title, state, + budget: GoalBudget::Time { elapsed: Duration::from_secs(23 * 60), limit: None }, + pipeline: &fixture.pipeline, image_cells: &fixture.image_cells, copy_cells: &fixture.copy_cells, + workers: &[], roadmap: None, controls, + }, true, |index| format!("图片 {}", index + 1)) + } + + fn controls(stop: StopPhase<'_>, budget: Option) -> Option> { + Some(ProductionControls { stop, budget, resume_ready: true }) + } + + #[test] + fn one_stop_button_replaces_the_icon_and_reports_each_state() { + let fixture = panel_fixture(); + let budget = Some(TimeBudget { elapsed_minutes: 23.0, budget_minutes: 45.0 }); + for width in [250.0, 520.0] { + let ctx = context(); + let size = vec2(width, 480.0); + let mut result = None; + let drawn = texts(&ctx, size, vec![], |ui| result = Some(show(ui, "idle", &fixture, controls(StopPhase::Idle, budget)))); + let result = result.unwrap(); + assert!(result.stop.is_none(), "{width}: the labelled stop button replaces the stop icon"); + let head = result.controls.unwrap(); + assert!(head.stop.enabled() && head.resume.is_none() && head.choices.is_empty(), "{width}: one stop button, menu closed"); + assert!(head.stop.rect.right() <= result.rect.right() + 0.5 && head.stop.rect.top() >= result.title.bottom() - 0.5); + assert!(drawn.iter().any(|text| text == "已用 23 分钟 / 预算 45 分钟"), "{width}: {drawn:?}"); + assert!(!drawn.iter().any(|text| text == "已用 23m"), "{width}: the budget is not repeated in the pipeline row"); + let budget_rect = head.budget.unwrap(); + assert!(budget_rect.right() <= head.stop.rect.left() + 0.5 || budget_rect.bottom() <= head.stop.rect.top() + 0.5, + "{width}: the budget line never overlaps the button"); + for (phase, label) in [(StopPhase::Stopping, "正在停止…"), (StopPhase::Delivering, "正在交付…"), + (StopPhase::Ended, "已结束本轮制作"), (StopPhase::Delivered, "已交付")] { + let mut busy = None; + let drawn = texts(&ctx, size, vec![], |ui| busy = Some(show(ui, "busy", &fixture, controls(phase, budget)))); + let busy = busy.unwrap().controls.unwrap(); + assert!(!busy.stop.enabled() && busy.resume.is_none(), "{width}: {label} greys the stop button"); + assert!(drawn.iter().any(|text| text == label), "{width}: {drawn:?}"); + assert!(busy.status.unwrap().right() <= busy.stop.rect.left() + 0.5, "{width}: the state sits beside the button"); + } + let mut paused = None; + let _ = texts(&ctx, size, vec![], |ui| paused = Some(show(ui, "paused", &fixture, controls(StopPhase::Paused, budget)))); + let paused = paused.unwrap().controls.unwrap(); + let resume = paused.resume.unwrap(); + assert!(resume.enabled() && paused.stop.enabled(), "{width}: a paused run can continue or stop"); + assert!(paused.stop.rect.right() <= resume.rect.left() + 0.5, "{width}: 继续制作 takes the stop button's place, 停止 moves beside it"); + let mut failed = None; + let drawn = texts(&ctx, size, vec![], |ui| failed = Some(show(ui, "failed", &fixture, controls(StopPhase::Failed("成品目录不可写"), None)))); + assert!(failed.unwrap().controls.unwrap().stop.enabled(), "a failed stop can be retried"); + assert!(drawn.iter().any(|text| text == "成品目录不可写")); + assert!(drawn.iter().any(|text| text == "已用 23m"), "without a reported budget the pipeline row keeps the elapsed time"); + let drawn = texts(&ctx, size, vec![], |ui| { show(ui, "over", &fixture, + controls(StopPhase::Idle, Some(TimeBudget { elapsed_minutes: 47.0, budget_minutes: 45.0 }))); }); + assert!(drawn.iter().any(|text| text == "已超出预算,将自动交付"), "{width}: {drawn:?}"); + } + } + + /// 点开停止菜单,返回菜单展开那一帧的结果与画出的文字。 + fn open_menu(ctx: &egui::Context, size: egui::Vec2, fixture: &Panel, phase: StopPhase<'_>) -> (super::super::stitch_timeline::ControlsResponse, Vec) { + let mut first = None; + let _ = texts(ctx, size, vec![], |ui| first = Some(show(ui, "menu", fixture, controls(phase, None)))); + let stop = first.unwrap().controls.unwrap().stop.rect.center(); + let _ = texts(ctx, size, click(stop), |ui| { show(ui, "menu", fixture, controls(phase, None)); }); + let mut opened = None; + let drawn = texts(ctx, size, vec![], |ui| opened = Some(show(ui, "menu", fixture, controls(phase, None)))); + (opened.unwrap().controls.unwrap(), drawn) + } + + #[test] + fn the_stop_menu_lists_three_choices_and_two_once_paused() { + let fixture = panel_fixture(); + let size = vec2(520.0, 600.0); + let ctx = context(); + let (menu, drawn) = open_menu(&ctx, size, &fixture, StopPhase::Idle); + assert_eq!(menu.choices.iter().map(|(mode, _)| *mode).collect::>(), vec![StopMode::Pause, StopMode::End, StopMode::Deliver]); + for mode in [StopMode::Pause, StopMode::End, StopMode::Deliver] { + assert!(drawn.iter().any(|text| text == mode.title()) && drawn.iter().any(|text| text == mode.detail()), "{mode:?}: {drawn:?}"); + } + let stop = menu.stop.rect; + assert!(menu.choices.iter().all(|(_, rect)| rect.top() >= stop.bottom() - 0.5), "the menu opens below the button"); + let line = ctx.fonts_mut(|fonts| fonts.row_height(&Type::Meta.font_id())); + let title = ctx.fonts_mut(|fonts| fonts.row_height(&Type::Title.font_id())); + assert!(menu.choices.iter().all(|(_, rect)| rect.height() < title + 1.5 * line + 14.0), "each description stays on one line: {:?}", menu.choices); + let pause = menu.choices[0].1; + let mut chosen = None; + let _ = texts(&ctx, size, click(pause.center()), |ui| chosen = show(ui, "menu", &fixture, controls(StopPhase::Idle, None)).controls.unwrap().chosen); + assert_eq!(chosen, Some(StopMode::Pause)); + let ctx = context(); + let (menu, drawn) = open_menu(&ctx, size, &fixture, StopPhase::Paused); + assert_eq!(menu.choices.iter().map(|(mode, _)| *mode).collect::>(), vec![StopMode::End, StopMode::Deliver]); + assert!(!drawn.iter().any(|text| text == "只暂停"), "{drawn:?}"); + } + + #[test] + fn a_goal_without_production_controls_keeps_its_stop_icon() { + let fixture = panel_fixture(); + let ctx = context(); + let mut result = None; + let _ = texts(&ctx, vec2(520.0, 400.0), vec![], |ui| result = Some(show(ui, "plain", &fixture, None))); + let result = result.unwrap(); + assert!(result.stop.is_some() && result.controls.is_none()); + } + + #[test] + fn end_and_deliver_register_only_after_their_confirmation() { + for (mode, text, action, input) in [ + (StopMode::End, END_CONFIRM, "结束制作", json!({"mode":"end"})), + (StopMode::Deliver, DELIVER_CONFIRM, "确定交付", json!({"mode":"deliver"})), + ] { + let Fixture { mut w, requests, .. } = workspace(); + let ctx = context(); + let size = vec2(900.0, 700.0); + frame(&ctx, vec![], size, |ui| w.stop_confirm_ui(ui, true)); + assert!(w.panel_geometry["productionStopConfirm"].is_null(), "closed until asked for"); + open_stop_confirm(&ctx, mode); + let mut drawn = Vec::new(); + for _ in 0..3 { + drawn = texts(&ctx, size, vec![], |ui| w.stop_confirm_ui(ui, true)); + } + assert!(drawn.iter().any(|shown| shown == text) && drawn.iter().any(|shown| shown == mode.title()), "{drawn:?}"); + assert!(drawn.iter().any(|shown| shown == action) && drawn.iter().any(|shown| shown == "取消")); + assert!(queued_actions(&ctx).is_empty(), "opening the confirmation does not stop anything"); + let confirm = rect_of(&w.panel_geometry["productionStopConfirm"]); + frame(&ctx, click(confirm.center()), size, |ui| w.stop_confirm_ui(ui, true)); + assert_eq!(queued_actions(&ctx), vec![("production-stop".to_owned(), input)]); + assert_eq!(ctx.data(|data| data.get_temp::<(StopMode, bool)>(stop_confirm_id())), Some((mode, false)), "the confirmation closes"); + assert!(requests.try_recv().is_err()); + } + } + + fn visual_directory() -> std::path::PathBuf { + let directory = std::env::var_os("PHOTOCRAFT_AGENT_QA_OUT").map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("xiaoyi-production-controls")); + std::fs::create_dir_all(&directory).unwrap(); + directory + } + + fn visual_setup(ctx: &egui::Context) { + PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium); + crate::cjk_fonts::install_system_provider_for_tests(ctx); + } + + struct HeadVisual { panel: Panel, head: HeadControls, open_menu: bool } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore = "offscreen GPU visual evidence; writes to PHOTOCRAFT_AGENT_QA_OUT"] + fn production_controls_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); + let directory = visual_directory(); + for (name, refinement) in [("refinement-off", false), ("refinement-on", true)] { + let Fixture { mut w, .. } = workspace(); + w.template_workflow = json!({"productionSettings":{"refinement":refinement,"timeBudgetMinutes":if refinement { 120 } else { 45 }}}); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(720.0, 150.0)).with_context_setup(visual_setup).wgpu() + .build_ui_state(|ui, w: &mut Workspace| { + egui::Frame::NONE.inner_margin(egui::Margin::same(16)).show(ui, |ui| { + kit::scope(ui, |ui| { + w.output_tags_ui(ui); + ui.add_space(6.0); + w.refinement_ui(ui); + }); + }); + }, w); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } + let budget = |elapsed: f64| json!({"startedAt":1_764_480_000,"budgetMinutes":45,"elapsedMinutes":elapsed}); + let stop = |state: &str, error: Value| json!({"mode":"deliver","state":state,"reason":"用户手动停止并交付","error":error}); + let cases = [ + ("stop-idle", 420.0, 240.0, stop("idle", Value::Null), budget(23.4), false), + ("stop-menu", 420.0, 420.0, stop("idle", Value::Null), budget(23.4), true), + ("stop-stopping", 420.0, 240.0, stop("stopping", Value::Null), budget(23.4), false), + ("stop-paused", 420.0, 240.0, stop("paused", Value::Null), budget(23.4), false), + ("stop-paused-menu", 420.0, 380.0, stop("paused", Value::Null), budget(23.4), true), + ("stop-ended", 420.0, 240.0, stop("ended", Value::Null), budget(31.0), false), + ("stop-delivering", 420.0, 240.0, stop("delivering", Value::Null), budget(23.4), false), + ("stop-delivered", 420.0, 240.0, stop("delivered", Value::Null), budget(23.4), false), + ("stop-failed", 420.0, 260.0, stop("failed", json!("成品目录不可写:D:\\成品\\餐椅 拒绝访问")), budget(23.4), false), + ("budget-normal", 250.0, 260.0, stop("idle", Value::Null), budget(23.4), false), + ("budget-over", 250.0, 260.0, stop("idle", Value::Null), budget(55.2), false), + ]; + for (name, width, height, stop, budget, open_menu) in cases { + let head = HeadControls::read(&ControlState { settings: Value::Null, stop, budget }); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, height)).with_context_setup(visual_setup).wgpu() + .build_ui_state(|ui, visual: &mut HeadVisual| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(16, 10)).show(ui, |ui| { + kit::scope(ui, |ui| { + let result = show(ui, "visual-head", &visual.panel, Some(visual.head.view(true))); + if let Some(controls) = result.controls.filter(|_| visual.open_menu) + && !egui::Popup::is_id_open(ui.ctx(), controls.stop.id.with("popup")) { + egui::Popup::toggle_id(ui.ctx(), controls.stop.id.with("popup")); + } + }); + }); + }, HeadVisual { panel: panel_fixture(), head, open_menu }); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } + for (name, mode) in [("confirm-end", StopMode::End), ("confirm-deliver", StopMode::Deliver)] { + let Fixture { w, .. } = workspace(); + let mut harness = egui_kittest::Harness::builder().with_size(vec2(720.0, 360.0)).with_context_setup(visual_setup).wgpu() + .build_ui_state(move |ui, w: &mut Workspace| { + open_stop_confirm(ui.ctx(), mode); + w.stop_confirm_ui(ui, true); + }, w); + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs index efd81ee5..be71ebfb 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_timeline.rs @@ -417,14 +417,110 @@ pub(super) struct GoalProgressPanel<'a> { pub workers: &'a [WorkerState<'a>], /// `Some` 时路线图抽屉展开。 pub roadmap: Option<&'a [GoalStage<'a>]>, + /// 整套制作的停止钮与时间预算行;给出时取代主条上的停止图标。 + pub controls: Option>, +} + +/// 停止制作的进度,原样对应调用方给出的停止状态;`Failed` 带原始错误。 +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum StopPhase<'a> { Idle, Stopping, Paused, Ended, Delivering, Delivered, Failed(&'a str) } + +impl StopPhase<'_> { + /// 停止钮能否点开菜单:空闲、已暂停或上一次停止失败时可以。 + pub(super) fn ready(self) -> bool { + matches!(self, Self::Idle | Self::Paused | Self::Failed(_)) + } + + /// 按钮旁的进度文字;失败的原始错误另起一行。 + fn status(self) -> Option<&'static str> { + match self { + Self::Stopping => Some("正在停止…"), + Self::Delivering => Some("正在交付…"), + Self::Ended => Some("已结束本轮制作"), + Self::Delivered => Some("已交付"), + Self::Idle | Self::Paused | Self::Failed(_) => None, + } + } + + /// 停止菜单里列出的选项:已暂停时不再列"只暂停"。 + pub(super) fn choices(self) -> &'static [StopMode] { + if self == Self::Paused { &[StopMode::End, StopMode::Deliver] } else { &[StopMode::Pause, StopMode::End, StopMode::Deliver] } + } +} + +/// 停止菜单的三种停法。 +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum StopMode { Pause, End, Deliver } + +impl StopMode { + pub(super) fn title(self) -> &'static str { + match self { Self::Pause => "只暂停", Self::End => "停止目标", Self::Deliver => "停止并交付" } + } + + pub(super) fn detail(self) -> &'static str { + match self { + Self::Pause => "停在当前步骤,进度保留,随时可以继续", + Self::End => "结束本轮制作,不交付,已做的内容保留在画布上", + Self::Deliver => "把现有成果交付,没做完的写进已知问题", + } + } +} + +/// 时间预算:已用与预算,单位分钟。超出后由宿主自动停止并交付,这里只报告。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct TimeBudget { pub elapsed_minutes: f64, pub budget_minutes: f64 } + +impl TimeBudget { + pub(super) fn over(self) -> bool { + self.elapsed_minutes > self.budget_minutes + } + + pub(super) fn text(self) -> String { + if self.over() { + "已超出预算,将自动交付".into() + } else { + format!("已用 {} 分钟 / 预算 {} 分钟", self.elapsed_minutes.max(0.0).floor(), self.budget_minutes.round()) + } + } +} + +/// 整套制作的控制:停止进度、可选的时间预算,以及暂停后能否继续。 +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct ProductionControls<'a> { + pub stop: StopPhase<'a>, + pub budget: Option, + /// 已暂停时"继续制作"能否点。 + pub resume_ready: bool, +} + +pub(super) const STOP_LABEL: &str = "停止"; +pub(super) const RESUME_LABEL: &str = "继续制作"; +/// 停止菜单的宽度:每项的说明都能排成一行。 +const STOP_MENU_WIDTH: f32 = 312.0; + +#[derive(Debug)] +pub(super) struct ControlsResponse { + /// 点开停止菜单的按钮。 + pub stop: Response, + /// 已暂停时的"继续制作"。 + pub resume: Option, + /// 这一帧在停止菜单里点中的一项。 + pub chosen: Option, + /// 停止菜单展开时每一项的位置。 + pub choices: Vec<(StopMode, Rect)>, + /// 停止进度文字或失败原因。 + pub status: Option, + pub budget: Option, } #[derive(Debug)] pub(super) struct GoalProgressResponse { /// 展开或收起路线图的按钮。 pub toggle: Response, - /// 只有任务还在本地推进时才有。 + /// 只有任务还在本地推进、且没有给出制作控制时才有。 pub stop: Option, + /// 给出制作控制时的停止钮与预算行。 + pub controls: Option, pub rect: Rect, pub title: Rect, pub rail: Option, @@ -593,6 +689,66 @@ fn roadmap(ui: &mut Ui, id: egui::Id, stages: &[GoalStage<'_>], panel: &GoalProg clicked } +/// 停止菜单:挂在"停止"下方,每项一行标题、一行说明。返回点中的一项与各项位置。 +fn stop_menu(ui: &mut Ui, stop: &Response, choices: &[StopMode], reduced: bool) -> (Option, Vec<(StopMode, Rect)>) { + let (mut chosen, mut rects) = (None, Vec::new()); + kit::select_popup(ui, stop, STOP_MENU_WIDTH, reduced, |ui| { + for mode in choices { + let item = kit::menu_choice(ui, mode.title(), mode.detail(), true); + if item.clicked() { chosen = Some(*mode); } + rects.push((*mode, item.rect)); + } + }); + (chosen, rects) +} + +/// 制作控制行:左边时间预算,右边"停止"(已暂停时是"继续制作"与"停止")。一行放不下时预算单独占一行、 +/// 按钮另起一行靠右;停止失败的原始错误用提醒色另起一行。 +fn production_controls(ui: &mut Ui, controls: ProductionControls<'_>, reduced: bool) -> ControlsResponse { + let t = Tokens::get(ui.ctx()).agent(); + let width = ui.available_width(); + let meta = Type::Meta.font_id(); + let paused = controls.stop == StopPhase::Paused; + let budget = controls.budget.map(|budget| (budget.text(), if budget.over() { t.warning } else { t.text_dim })); + let status = controls.stop.status() + .map(|text| (text, if controls.stop == StopPhase::Delivered { AGENT_SEMANTIC.success } else { t.text_dim })); + let measure = |text: &str, font: egui::FontId| ui.painter().layout_no_wrap(text.to_owned(), font, t.text).size().x; + let padding = 2.0 * ui.spacing().button_padding.x; + let resume_width = if paused { measure(RESUME_LABEL, Type::Title.font_id()) + padding + space::XS } else { 0.0 }; + let buttons = measure(STOP_LABEL, Type::Title.font_id()) + padding + resume_width; + let status_width = status.map_or(0.0, |(text, _)| measure(text, meta.clone()) + space::SM); + let budget_width = budget.as_ref().map_or(0.0, |(text, _)| measure(text, meta.clone()) + space::SM); + let shared = budget_width + status_width + buttons <= width; + let mut budget_rect = None; + if !shared && let Some((text, color)) = &budget { + budget_rect = Some(ui.add(egui::Label::new(RichText::new(text).font(meta.clone()).color(*color)).wrap()).rect); + } + let ready = controls.stop.ready(); + let row = ui.allocate_ui_with_layout(vec2(width, control::COMPACT), Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = space::XS; + // 已暂停时"继续制作"占住停止钮原来的位置,停止钮挪到它旁边。 + let resume = paused.then(|| kit::action_button_height(ui, RESUME_LABEL, kit::ButtonRole::Primary, controls.resume_ready, control::COMPACT)); + let stop = kit::action_button_height(ui, STOP_LABEL, kit::ButtonRole::Secondary, ready, control::COMPACT); + let status = status.map(|(text, color)| { + ui.add_space(space::XS); + ui.label(RichText::new(text).font(meta.clone()).color(color)).rect + }); + if shared && let Some((text, color)) = &budget { + let rest = ui.available_width().max(1.0); + budget_rect = Some(ui.allocate_ui_with_layout(vec2(rest, control::COMPACT), Layout::left_to_right(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(text).font(meta.clone()).color(*color)).truncate()).rect + }).inner); + } + (stop, resume, status) + }); + let (stop, resume, mut status) = row.inner; + let (chosen, choices) = stop_menu(ui, &stop, controls.stop.choices(), reduced); + if let StopPhase::Failed(error) = controls.stop { + status = Some(ui.add(egui::Label::new(RichText::new(error).font(meta).color(t.warning)).wrap()).rect); + } + ControlsResponse { stop, resume, chosen, choices, status, budget: budget_rect } +} + /// 目标驾驶舱。`describe` 给出每个图片格的悬停说明。布局、展开状态与停止钮都在这里, /// 业务层只负责把真实进度归约成 `GoalProgressPanel` 并登记返回的几何。 pub(super) fn goal_progress_panel(ui: &mut Ui, id: egui::Id, panel: GoalProgressPanel<'_>, reduced: bool, describe: D) -> GoalProgressResponse @@ -613,6 +769,7 @@ where let (mut rail, mut slot_clicked) = (None, None); let (mut toggle, mut toggle_clicked, mut stop, mut title) = (None, false, None, Rect::NOTHING); let (mut image_cells, mut copy_cells, mut workers) = (Value::Null, Value::Null, Vec::new()); + let mut controls = None; let card = kit::surface(ui, kit::SurfaceRole::Task, |ui| { let background = super::agent_motion::reserve_background(ui); let width = ui.available_width(); @@ -620,7 +777,7 @@ where // 主条:左边状态与进度,右边展开钮与停止钮。 ui.allocate_ui_with_layout(vec2(width, agent_stream::ROW), Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = space::XS; - if can_stop { + if can_stop && panel.controls.is_none() { stop = Some(stop_button(ui, StopSize::Compact)); } let button = kit::icon_button(ui, if expanded { "chevron-up" } else { "chevron-down" }, control::COMPACT, expanded, @@ -636,7 +793,9 @@ where .rect; }); }); - let budget = panel.budget.text(); + // 制作控制紧跟主条:预算行在左,停止钮在右;有了预算行,流水线那行不再重复报时间。 + controls = panel.controls.map(|production| production_controls(ui, production, reduced)); + let budget = if panel.controls.is_some_and(|production| production.budget.is_some()) { String::new() } else { panel.budget.text() }; if !panel.pipeline.is_empty() || !budget.is_empty() { ui.horizontal_wrapped(|ui| { for (index, (name, phase)) in panel.pipeline.iter().enumerate() { @@ -698,6 +857,7 @@ where GoalProgressResponse { toggle: toggle.unwrap_or_else(|| ui.allocate_response(vec2(0.0, 0.0), egui::Sense::hover())), stop, + controls, rect: card.response.rect, title, rail, @@ -1098,7 +1258,7 @@ mod tests { let show = |ui: &mut Ui, state: RunState| { kit::scope(ui, |ui| { goal_progress_panel(ui, egui::Id::unique("goal"), GoalProgressPanel { - title: "整套", state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &workers, roadmap: Some(&stages), + title: "整套", state, budget, pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &workers, roadmap: Some(&stages), controls: None, }, false, |index| format!("图片 {}", index + 1)) }).inner }; @@ -1170,12 +1330,12 @@ mod tests { kit::scope(ui, |ui| { done = Some(goal_progress_panel(ui, egui::Id::unique("done"), GoalProgressPanel { title: "整套", state: RunState::Completed, budget: GoalBudget::Tokens { used: 1200, limit: Some(8000) }, - pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &[], roadmap: None, + pipeline: &pipeline, image_cells: &image_cells, copy_cells: ©_cells, workers: &[], roadmap: None, controls: None, }, true, |_| String::new())); failed = Some(goal_progress_panel(ui, egui::Id::unique("failed"), GoalProgressPanel { title: "整套", state: RunState::Failed, budget: GoalBudget::Tokens { used: 1200, limit: None }, pipeline: &[], image_cells: &[], copy_cells: &[], - workers: &[WorkerState { number: 1, stage: WorkerStage::Reviewing, slot: "主图", active: false }], roadmap: None, + workers: &[WorkerState { number: 1, stage: WorkerStage::Reviewing, slot: "主图", active: false }], roadmap: None, controls: None, }, true, |_| String::new())); }); }); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 09ee86fb..55fa9c03 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -1801,6 +1801,33 @@ pub(super) fn menu_item(ui: &mut Ui, label: &str, enabled: bool) -> Response { menu_row(ui, label, false, enabled, vec2(ui.available_width().max(0.0), control::MENU_ROW), egui::Role::Button) } +/// 带说明的菜单项:一行标题、一行次要说明,整项是同一个点击与键盘目标;悬停与按下的底色同 `menu_item`。 +pub(super) fn menu_choice(ui: &mut Ui, title: &str, detail: &str, enabled: bool) -> Response { + let enabled = enabled && ui.is_enabled(); + let t = Tokens::get(ui.ctx()).agent(); + let width = ui.available_width().max(1.0); + let padding = vec2(10.0, 6.0); + let wrap = (width - 2.0 * padding.x).max(1.0); + let title_galley = ui.painter().layout(title.to_owned(), Type::Title.font_id(), if enabled { t.text } else { t.text_faint }, wrap); + let detail_galley = ui.painter().layout(detail.to_owned(), Type::Meta.font_id(), if enabled { t.text_dim } else { t.text_faint }, wrap); + let height = (title_galley.size().y + space::XXS + detail_galley.size().y + 2.0 * padding.y).max(control::MENU_ROW); + let (rect, response) = ui.allocate_exact_size(vec2(width, height), if enabled { egui::Sense::click() } else { egui::Sense::hover() }); + if ui.is_rect_visible(rect) { + let fill = if !enabled { None } else if response.is_pointer_button_down_on() { Some(t.pressed) } + else if response.hovered() || response.has_focus() { Some(t.hover) } else { None }; + if let Some(fill) = fill { ui.painter().rect_filled(rect, MENU_ITEM_RADIUS, fill); } + let left = rect.left() + padding.x; + let detail_top = rect.top() + padding.y + title_galley.size().y + space::XXS; + ui.painter().galley(egui::pos2(left, rect.top() + padding.y), title_galley, t.text); + ui.painter().galley(egui::pos2(left, detail_top), detail_galley, t.text_dim); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, title)); + if enabled && response.has_focus() { + focus_ring(ui, &response, f32::from(MENU_ITEM_RADIUS), FocusRing::OnGlass); + } + response +} + /// Floating command menu surface shared by compact composer actions. pub(super) fn command_menu_frame(ctx: &Context) -> Frame { surface_frame(ctx, SurfaceRole::Menu).corner_radius(radius::CHIP) @@ -2262,13 +2289,23 @@ pub(super) fn search_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: /// target and reports its real checkbox state to assistive technology. #[cfg_attr(not(test), expect(dead_code, reason = "Halo 开关原语:库内先行并通过单测,暂无生产调用方;接入后编译器会要求移除这一行"))] pub(super) fn switch(ui: &mut Ui, id: egui::Id, value: &mut bool, label: &str, enabled: bool, reduced: bool) -> Response { + switch_with(ui, id, value, label, true, enabled, reduced) +} + +/// 只有开关本身:文字标签由调用方排在左侧,`name` 仍是读屏名称。宽度固定,不占满整行。 +pub(super) fn bare_switch(ui: &mut Ui, id: egui::Id, value: &mut bool, name: &str, enabled: bool, reduced: bool) -> Response { + switch_with(ui, id, value, name, false, enabled, reduced) +} + +fn switch_with(ui: &mut Ui, id: egui::Id, value: &mut bool, label: &str, show_label: bool, enabled: bool, reduced: bool) -> Response { ui.push_id(id, |ui| { let enabled = enabled && ui.is_enabled(); ui.add_enabled_ui(enabled, |ui| { let t = Tokens::get(ui.ctx()).agent(); - let width = ui.available_width().max(42.0); + let width = if show_label { ui.available_width().max(42.0) } else { 42.0 }; let label_color = if enabled { t.text } else { t.text_faint }; - let galley = ui.painter().layout(label.to_owned(), Type::Title.font_id(), label_color, (width - 52.0).max(1.0)); + let shown = if show_label { label } else { "" }; + let galley = ui.painter().layout(shown.to_owned(), Type::Title.font_id(), label_color, (width - 52.0).max(1.0)); let height = galley.size().y.max(32.0); let (rect, mut response) = ui.allocate_exact_size(vec2(width, height), egui::Sense::click()); if response.clicked() {