dialogs-w9: net change of 3 commits

- dialogs-w9: written by an agent
- dialogs-w9: finished by an agent
- dialogs-w9: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-27 14:51:30 +00:00
parent 705d90e2ad
commit 5a30677b03
6 changed files with 440 additions and 698 deletions
+81 -126
View File
@@ -1,86 +1,32 @@
use super::{Value, json};
use craft::text::ui::hyperlink::{CurrentLink, Hyperlink, HyperlinkAnswer, HyperlinkDialog, HyperlinkParts, LinkPlace, LinkPlaceGroup, LinkTarget};
use craft::ui::dialog::{DialogHost, DialogId};
use deckcraft_model::SlideId;
use egui::Context;
use serde_json::{Value, json};
/// What Insert Hyperlink would edit on the current selection.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum CurrentLink {
/// Nothing is linked. OK sets a new link (a caret at a word boundary inserts text).
None,
/// One link covers the text span or every selected shape.
One(deckcraft_model::text::Hyperlink),
/// The selection mixes different links. OK must not replace them until a new target is chosen.
Mixed,
}
use crate::SlideApp;
/// Fields the Insert Hyperlink dialog opens with.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct HyperlinkSeed {
/// `url`, `email` or `slide`.
pub(super) mode: &'static str,
pub(super) url: String,
pub(super) email: String,
pub(super) slide: usize,
pub(super) tip: String,
pub(super) highlight: bool,
/// The action is not a web address, email or slide this dialog edits (or the selection mixes
/// links). OK leaves it in place until the user picks a different target.
pub(super) preserve: bool,
}
impl HyperlinkSeed {
/// A new link: the address starts at `https://`, as the dialog always did.
pub(super) fn blank() -> Self {
HyperlinkSeed { mode: "url", url: "https://".into(), email: String::new(), slide: 0, tip: String::new(), highlight: false, preserve: false }
}
}
/// Turn one hyperlink into dialog fields. A slide that is no longer in the deck, and actions this
/// dialog does not edit (next slide, a program, …), are preserved so OK does not retarget them.
pub(super) fn seed_of_link(link: &deckcraft_model::text::Hyperlink, slide_ids: &[deckcraft_model::SlideId]) -> HyperlinkSeed {
fn current_of_link(link: &deckcraft_model::text::Hyperlink, slide_ids: &[SlideId]) -> CurrentLink {
use deckcraft_model::text::Action;
let mut seed = HyperlinkSeed {
mode: "url",
url: String::new(),
email: String::new(),
slide: 0,
tip: link.tooltip.clone(),
highlight: link.highlight_click,
preserve: true,
let target = match &link.action {
Action::Url { url } => match url.strip_prefix("mailto:") {
Some(address) => LinkTarget::email(address, None),
None => LinkTarget::Url(url.clone()),
},
Action::Slide { slide } => match slide_ids.iter().position(|id| id == slide) {
Some(index) => LinkTarget::Place(index),
None => return CurrentLink::Other,
},
_ => return CurrentLink::Other,
};
match &link.action {
Action::Url { url } => {
seed.preserve = false;
if let Some(email) = url.strip_prefix("mailto:") {
seed.mode = "email";
seed.email = email.to_string();
seed.url = "https://".into();
} else {
seed.url = url.clone();
}
}
Action::Slide { slide } => {
if let Some(i) = slide_ids.iter().position(|id| id == slide) {
seed.preserve = false;
seed.mode = "slide";
seed.slide = i;
seed.url = "https://".into();
}
}
_ => {}
}
seed
}
pub(super) fn seed_from(current: CurrentLink, slide_ids: &[deckcraft_model::SlideId]) -> HyperlinkSeed {
match current {
CurrentLink::None => HyperlinkSeed::blank(),
CurrentLink::Mixed => HyperlinkSeed { preserve: true, url: String::new(), ..HyperlinkSeed::blank() },
CurrentLink::One(link) => seed_of_link(&link, slide_ids),
}
let mut current = Hyperlink::new(target).tooltip(link.tooltip.clone());
current.highlight_click = link.highlight_click;
CurrentLink::One(current)
}
/// Links on the half-open span `[a, b)`. A point span is a new link: Insert Hyperlink inserts
/// there instead of editing a neighbouring run.
pub(super) fn link_covering(body: &deckcraft_model::text::TextBody, a: (usize, usize), b: (usize, usize)) -> CurrentLink {
pub(crate) fn link_covering(body: &deckcraft_model::text::TextBody, a: (usize, usize), b: (usize, usize), slides: &[SlideId]) -> CurrentLink {
if a == b {
return CurrentLink::None;
}
@@ -118,12 +64,13 @@ pub(super) fn link_covering(body: &deckcraft_model::text::TextBody, a: (usize, u
}
}
match seen {
Some(Some(link)) => CurrentLink::One(link),
Some(Some(link)) => current_of_link(&link, slides),
_ => CurrentLink::None,
}
}
pub(super) fn common_click(clicks: impl IntoIterator<Item = Option<deckcraft_model::text::Hyperlink>>) -> CurrentLink {
/// Compares complete model links before converting their shared action to an editable target.
pub(crate) fn common_click(clicks: impl IntoIterator<Item = Option<deckcraft_model::text::Hyperlink>>, slides: &[SlideId]) -> CurrentLink {
let mut clicks = clicks.into_iter();
let Some(first) = clicks.next() else { return CurrentLink::None };
for next in clicks {
@@ -132,69 +79,77 @@ pub(super) fn common_click(clicks: impl IntoIterator<Item = Option<deckcraft_mod
}
}
match first {
Some(link) => CurrentLink::One(link),
Some(link) => current_of_link(&link, slides),
None => CurrentLink::None,
}
}
/// The link Insert Hyperlink would edit: text when a caret or selection is active, otherwise the
/// click action shared by the selected shapes.
pub(super) fn hyperlink_seed_of(st: Option<&deckcraft_engine::DocState>) -> HyperlinkSeed {
let Some(st) = st else { return HyperlinkSeed::blank() };
pub(crate) fn current_link_of(st: Option<&deckcraft_engine::DocState>) -> CurrentLink {
let Some(st) = st else { return CurrentLink::None };
let ids: Vec<deckcraft_model::SlideId> = st.doc.slides.iter().map(|s| s.id).collect();
let current = if let Some(t) = &st.selection.text {
if let Some(t) = &st.selection.text {
match deckcraft_engine::cmd::text::body_of(st, t) {
Some(body) => {
let (a, b) = deckcraft_engine::cmd::text::format_range(st, t);
link_covering(body, a, b)
link_covering(body, a, b, &ids)
}
None => CurrentLink::None,
}
} else {
common_click(st.selected_shapes().into_iter().map(|sh| sh.click.clone()))
common_click(st.selected_shapes().into_iter().map(|sh| sh.click.clone()), &ids)
}
}
/// Opens the selection's link with the deck's slides in one flat place group.
pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result<Option<DialogId>, String> {
let places = app
.session
.active()
.map(|st| st.doc.slides.iter().enumerate().map(|(i, slide)| LinkPlace::new(format!("{}. {}", i + 1, slide.title()), 0)).collect())
.unwrap_or_default();
Ok(Some(host.open(
HyperlinkDialog::new(current_link_of(app.session.active()), None)
.key("hyperlink".to_owned())
.place_groups(vec![LinkPlaceGroup::new("Slide Titles", places)])
.parts(HyperlinkParts::Basic)
.held_ok(),
)))
}
/// Applies each held answer once and leaves refused commands open with their reason.
pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) {
let _ = host.take::<HyperlinkDialog>();
let Some(answer) = host.get_mut::<HyperlinkDialog>().and_then(HyperlinkDialog::take_ok) else { return };
let result = match answer {
HyperlinkAnswer::Keep => Ok(()),
HyperlinkAnswer::Set { link, .. } => {
let mut params = json!({"tooltip": link.tooltip, "highlightClick": link.highlight_click});
let target = match link.target {
LinkTarget::Url(url) => {
params["url"] = json!(url);
Ok(())
}
LinkTarget::Email { address, .. } => {
params["url"] = json!(format!("mailto:{address}"));
Ok(())
}
LinkTarget::Top => {
params["slide"] = json!(0);
Ok(())
}
LinkTarget::Place(index) => {
params["slide"] = json!(index);
Ok(())
}
_ => Err("Unsupported hyperlink target".to_owned()),
};
target.and_then(|()| app.run("insert.hyperlink", params).map(|_| ()))
}
_ => Err("Unsupported hyperlink action".to_owned()),
};
seed_from(current, &ids)
}
/// OK writes a link unless the dialog is holding an action it does not edit and the user has not
/// chosen a new target.
pub(super) fn hyperlink_should_apply(seed: &HyperlinkSeed, mode: &str, url: &str, email: &str, slide: usize) -> bool {
if !seed.preserve {
return true;
}
if mode != seed.mode {
return true;
}
match mode {
"email" => email != seed.email,
"slide" => slide != seed.slide,
_ => url != seed.url,
if let Some(dialog) = host.get_mut::<HyperlinkDialog>() {
dialog.answer_ok(result.map_err(Into::into));
}
}
pub(super) fn hyperlink_command(mode: &str, url: &str, email: &str, slide: usize, tip: &str, highlight: bool) -> Value {
match mode {
"slide" => json!({"slide": slide, "tooltip": tip, "highlightClick": highlight}),
"email" => json!({"url": format!("mailto:{email}"), "tooltip": tip, "highlightClick": highlight}),
_ => json!({"url": url, "tooltip": tip, "highlightClick": highlight}),
}
}
/// Opens this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn open(
app: &mut crate::SlideApp,
ctx: &egui::Context,
host: &mut craft::ui::dialog::DialogHost,
params: &serde_json::Value,
) -> Result<Option<craft::ui::dialog::DialogId>, String> {
let _ = (app, ctx, host, params);
todo!("dl.A10")
}
/// Advances this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) {
let _ = (app, ctx, host);
todo!("dl.A10")
}
+90 -201
View File
@@ -1,218 +1,107 @@
use super::{Dialog, SlideApp, Ui, Value, buttons, choice, finite_pt, inches_text, json, json_text, labeled_text, pt_text, seed_once, vec2};
use craft::text::ui::character::{LineSpacing, ParagraphAlign, ParagraphDialog, ParagraphFormat, SpacingKind, SpecialIndent};
use craft::ui::dialog::{DialogHost, DialogId};
use egui::Context;
use serde_json::{Value, json};
fn seed_paragraph_fields(d: &mut Dialog) {
seed_once(d, "align", json_text(d.params.get("align"), "left"));
seed_once(d, "before", inches_text(d.params.get("indentLeft")));
seed_once(d, "after", inches_text(d.params.get("indentRight")));
seed_once(d, "special", json_text(d.params.get("special"), "none"));
seed_once(d, "by", inches_text(d.params.get("specialBy")));
seed_once(d, "spaceBefore", pt_text(d.params.get("spaceBefore"), 0.0));
seed_once(d, "spaceBeforeSeed", pt_text(d.params.get("spaceBefore"), 0.0));
seed_once(d, "spaceAfter", pt_text(d.params.get("spaceAfter"), 0.0));
seed_once(d, "spaceAfterSeed", pt_text(d.params.get("spaceAfter"), 0.0));
seed_once(d, "lineKind", json_text(d.params.get("lineKind"), "multiple"));
seed_once(d, "lineValue", pt_text(d.params.get("lineValue"), 1.0));
use crate::SlideApp;
/// Opens the paragraph format supplied by the engine, whose lengths are points.
pub(crate) fn open(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost, params: &Value) -> Result<Option<DialogId>, String> {
Ok(Some(reopen(app, ctx, host, format_of(params))))
}
fn paragraph_return_params(d: &mut Dialog) -> Value {
let before = finite_pt(&d.get("before", "0")).unwrap_or(0.0) * 72.0;
let after = finite_pt(&d.get("after", "0")).unwrap_or(0.0) * 72.0;
let by = finite_pt(&d.get("by", "0")).unwrap_or(0.0) * 72.0;
let space_before = finite_pt(&d.get("spaceBefore", "0")).unwrap_or(0.0);
let space_after = finite_pt(&d.get("spaceAfter", "0")).unwrap_or(0.0);
let line_value = finite_pt(&d.get("lineValue", "1")).unwrap_or(1.0);
let before_same = d.get("spaceBefore", "") == d.get("spaceBeforeSeed", "");
let after_same = d.get("spaceAfter", "") == d.get("spaceAfterSeed", "");
json!({
"align": d.get("align", "left"),
"indentLeft": before,
"indentRight": after,
"special": d.get("special", "none"),
"specialBy": by,
"spaceBefore": space_before,
"spaceBeforeKind": if before_same { d.params.get("spaceBeforeKind").and_then(Value::as_str).unwrap_or("pts") } else { "pts" },
"spaceAfter": space_after,
"spaceAfterKind": if after_same { d.params.get("spaceAfterKind").and_then(Value::as_str).unwrap_or("pts") } else { "pts" },
"lineKind": d.get("lineKind", "multiple"),
"lineValue": line_value,
"tabs": d.params.get("tabs").cloned().unwrap_or_else(|| json!([])),
"defaultTab": d.params.get("defaultTab").cloned().unwrap_or_else(|| json!(72.0)),
})
/// Restores an unapplied paragraph draft after the Tabs dialog finishes.
pub(crate) fn reopen(_app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, draft: ParagraphFormat) -> DialogId {
host.open(ParagraphDialog::new(draft).key("paragraph".to_owned()).held_ok())
}
fn line_preset_label(kind: &str, value: &str) -> &'static str {
if kind == "exactly" {
"Exactly"
/// Applies paragraph formatting or opens Tabs with the unapplied draft.
pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
let _ = host.take::<ParagraphDialog>();
let Some(answer) = host.get_mut::<ParagraphDialog>().and_then(ParagraphDialog::take_ok) else { return };
let result = if answer.open_tabs {
super::tabs::open_from_paragraph(app, ctx, host, answer.format).map(|_| ())
} else {
match value {
"1" => "Single",
"1.5" => "1.5 lines",
"2" => "Double",
_ => "Multiple",
}
params_of(&answer.format).and_then(|params| app.run("format.paragraphDialog", params).map(|_| ()))
};
if let Some(dialog) = host.get_mut::<ParagraphDialog>() {
dialog.answer_ok(result.map_err(Into::into));
}
}
/// Home › Paragraph launcher. One OK applies alignment, indentation and spacing together.
pub(super) fn paragraph_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
ui.set_min_width(460.0);
seed_paragraph_fields(d);
ui.horizontal(|ui| {
ui.add_sized(vec2(110.0, 20.0), egui::Label::new("Alignment"));
choice(
ui,
d,
"paragraph_align",
"Alignment",
"align",
&[
("left", "Left"),
("center", "Center"),
("right", "Right"),
("justify", "Justify"),
("justLow", "Justify low"),
("distributed", "Distributed"),
],
);
fn format_of(params: &Value) -> ParagraphFormat {
let number = |key: &str, default| params[key].as_f64().filter(|n| n.is_finite()).unwrap_or(default) as f32;
let mut format = ParagraphFormat::default();
format.align = Some(match params["align"].as_str() {
Some("center" | "ctr") => ParagraphAlign::Center,
Some("right" | "r") => ParagraphAlign::Right,
Some("justify" | "just") => ParagraphAlign::Justify,
Some("justLow") => ParagraphAlign::JustifyLow,
Some("distributed" | "dist") => ParagraphAlign::Distributed,
_ => ParagraphAlign::Left,
});
ui.label(egui::RichText::new("Indentation").strong());
ui.horizontal(|ui| {
let _ = labeled_text(ui, d, "Before text", "before", 64.0);
ui.label("in");
ui.add_space(12.0);
let _ = labeled_text(ui, d, "After text", "after", 64.0);
ui.label("in");
format.before_text = Some(number("indentLeft", 0.0));
format.after_text = Some(Some(number("indentRight", 0.0)));
format.special = Some(match params["special"].as_str() {
Some("first") => SpecialIndent::FirstLine,
Some("hanging") => SpecialIndent::Hanging,
_ => SpecialIndent::None,
});
ui.horizontal(|ui| {
ui.add_sized(vec2(110.0, 20.0), egui::Label::new("Special"));
choice(ui, d, "paragraph_special", "Special", "special", &[("none", "None"), ("first", "First line"), ("hanging", "Hanging")]);
ui.add_space(8.0);
let _ = labeled_text(ui, d, "By", "by", 64.0);
ui.label("in");
format.by = Some(number("specialBy", 0.0));
format.space_before = Some(number("spaceBefore", 0.0));
format.space_after = Some(number("spaceAfter", 0.0));
format.space_before_kind = spacing_kind(&params["spaceBeforeKind"]);
format.space_after_kind = spacing_kind(&params["spaceAfterKind"]);
format.line_spacing = Some(if params["lineKind"] == "exactly" {
LineSpacing::Exactly(number("lineValue", 18.0))
} else {
LineSpacing::Multiple(number("lineValue", 1.0))
});
ui.label(egui::RichText::new("Spacing").strong());
ui.horizontal(|ui| {
let _ = labeled_text(ui, d, "Spacing before", "spaceBefore", 64.0);
ui.label("pt");
ui.add_space(12.0);
let _ = labeled_text(ui, d, "Spacing after", "spaceAfter", 64.0);
ui.label("pt");
});
let mut picked: Option<(&'static str, Option<&'static str>)> = None;
ui.horizontal(|ui| {
let field = ui.add_sized(vec2(110.0, 20.0), egui::Label::new("Line spacing"));
let kind = d.get("lineKind", "multiple");
let value = d.get("lineValue", "1");
let combo =
// P3(dialogs-w9): earlier framework ComboBox removal (no contract id)
egui::ComboBox::from_id_salt("paragraph_line").selected_text(line_preset_label(&kind, &value)).width(140.0).show_ui(ui, |ui| {
for (label, k, v) in [
("Single", "multiple", Some("1")),
("1.5 lines", "multiple", Some("1.5")),
("Double", "multiple", Some("2")),
("Multiple", "multiple", None),
("Exactly", "exactly", None),
] {
if ui.selectable_label(line_preset_label(&kind, &value) == label, label).clicked() {
picked = Some((k, v));
}
}
});
let _ = combo.response.labelled_by(field.id);
ui.add_space(8.0);
let _ = labeled_text(ui, d, "At", "lineValue", 64.0);
});
if let Some((kind, value)) = picked {
d.fields.insert("lineKind".into(), kind.into());
if let Some(v) = value {
d.fields.insert("lineValue".into(), v.into());
} else if kind == "exactly" && finite_pt(&d.get("lineValue", "1")).is_some_and(|n| n <= 9.99) {
d.fields.insert("lineValue".into(), "18".into());
} else if kind == "multiple" && finite_pt(&d.get("lineValue", "1")).is_some_and(|n| n > 9.99) {
d.fields.insert("lineValue".into(), "1".into());
}
}
let mut open_tabs = false;
ui.horizontal(|ui| {
if ui.button("Tabs…").clicked() {
open_tabs = true;
}
});
let (ok, cancel) = buttons(ui, "OK");
if open_tabs {
let mut tabs = Dialog::new("tabs");
tabs.params = json!({
"tabs": d.params.get("tabs").cloned().unwrap_or_else(|| json!([])),
"defaultTab": d.params.get("defaultTab").cloned().unwrap_or_else(|| json!(72.0)),
"returnId": "paragraph",
"returnParams": paragraph_return_params(d),
format
}
fn spacing_kind(value: &Value) -> SpacingKind {
if value == "pct" { SpacingKind::Lines } else { SpacingKind::Points }
}
fn params_of(format: &ParagraphFormat) -> Result<Value, String> {
let mut params = json!({});
if let Some(align) = format.align {
params["align"] = json!(match align {
ParagraphAlign::Center => "center",
ParagraphAlign::Right => "right",
ParagraphAlign::Justify => "justify",
ParagraphAlign::JustifyLow => "justLow",
ParagraphAlign::Distributed => "distributed",
_ => "left",
});
app.dialog = Some(tabs);
return true;
}
if ok {
let Some(before_in) = finite_pt(&d.get("before", "")) else {
app.set_status("Indent before text must be a number of inches");
return false;
};
let Some(after_in) = finite_pt(&d.get("after", "")) else {
app.set_status("Indent after text must be a number of inches");
return false;
};
let Some(by_in) = finite_pt(&d.get("by", "")) else {
app.set_status("Special indent must be a number of inches");
return false;
};
let Some(space_before) = finite_pt(&d.get("spaceBefore", "")) else {
app.set_status("Spacing before must be a number");
return false;
};
let Some(space_after) = finite_pt(&d.get("spaceAfter", "")) else {
app.set_status("Spacing after must be a number");
return false;
};
let Some(line_value) = finite_pt(&d.get("lineValue", "")) else {
app.set_status("Line spacing must be a number");
return false;
};
let mut params = json!({
"align": d.get("align", "left"),
"indentLeft": before_in * 72.0,
"indentRight": after_in * 72.0,
"special": d.get("special", "none"),
"specialBy": by_in * 72.0,
"spaceBefore": space_before,
"spaceAfter": space_after,
"spaceBeforeKind": if d.get("spaceBefore", "") == d.get("spaceBeforeSeed", "") { d.params.get("spaceBeforeKind").and_then(Value::as_str).unwrap_or("pts") } else { "pts" },
"spaceAfterKind": if d.get("spaceAfter", "") == d.get("spaceAfterSeed", "") { d.params.get("spaceAfterKind").and_then(Value::as_str).unwrap_or("pts") } else { "pts" },
for (key, value) in [
("indentLeft", format.before_text),
("indentRight", format.after_text.flatten()),
("specialBy", format.by),
("spaceBefore", format.space_before),
("spaceAfter", format.space_after),
] {
if let Some(value) = value {
params[key] = json!(value);
}
}
if let Some(special) = format.special {
params["special"] = json!(match special {
SpecialIndent::FirstLine => "first",
SpecialIndent::Hanging => "hanging",
_ => "none",
});
if d.get("lineKind", "multiple") == "exactly" {
params["lineSpacingPt"] = json!(line_value);
} else {
params["lineSpacing"] = json!(line_value);
}
if app.run("format.paragraphDialog", params).is_err() {
return false;
}
}
ok || cancel
}
/// Opens this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn open(
app: &mut crate::SlideApp,
ctx: &egui::Context,
host: &mut craft::ui::dialog::DialogHost,
params: &serde_json::Value,
) -> Result<Option<craft::ui::dialog::DialogId>, String> {
let _ = (app, ctx, host, params);
todo!("dl.A10")
}
/// Advances this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) {
let _ = (app, ctx, host);
todo!("dl.A10")
for (key, kind) in [("spaceBeforeKind", format.space_before_kind), ("spaceAfterKind", format.space_after_kind)] {
params[key] = json!(if matches!(kind, SpacingKind::Lines) { "pct" } else { "pts" });
}
match format.line_spacing {
Some(LineSpacing::Exactly(value)) => params["lineSpacingPt"] = json!(value),
Some(LineSpacing::Multiple(value)) => params["lineSpacing"] = json!(value),
Some(_) => return Err("Only multiple or exact line spacing is supported".to_owned()),
None => {}
}
Ok(params)
}
@@ -12,15 +12,7 @@ fn harness() -> Harness<'static, SlideApp> {
let mut s = Session::with_new();
s.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 320.0, 80.0], "text": "Hello"})).unwrap();
let _ = s.execute("text.exit", &json!({}));
// P3(dialogs-w9): sh.A2
let app = SlideApp::new_base(s, Services::default());
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
let mut h = crate::test_harness::harness(s, Services::default());
h.run_steps(4);
h
}
@@ -50,15 +42,27 @@ fn tabs_of(h: &Harness<'_, SlideApp>) -> Vec<(f64, String)> {
#[test]
fn paragraph_button_aligns_text_in_one_undo() {
let mut h = harness();
let before = align_of(&h);
let undo = h.state().session.active().unwrap().history.undo.len();
let label = h.state().session.commands().into_iter().find(|cmd| cmd.id == "format.paragraphDialog").unwrap().label;
h.get_by_label("Paragraph…").click();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("paragraph"));
h.state_mut().dialog.as_mut().unwrap().fields.insert("align".into(), "right".into());
h.get_by_label("OK").click_accesskit();
h.run_steps(1);
assert!(h.state().dialog.is_none(), "status {:?}", h.state().status);
assert_eq!(align_of(&h).as_deref(), Some("r"));
assert_eq!(h.state().session.active().unwrap().history.undo.last().unwrap().label, "Paragraph…");
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "paragraph"));
let indent = 0.5 * 72.0;
dialog(&mut h, "ui.dialog.set", json!({"dialog": "top", "fields": [
{"field": "align", "value": "Right"}, {"field": "before_text", "value": indent}
]}));
dialog(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
assert!(super::open_keys(&h.ctx).is_empty(), "status {:?}", h.state().status);
assert_eq!(align_of(&h).as_deref(), Some(deckcraft_model::text::Align::Right.xml()));
let st = h.state().session.active().unwrap();
let paragraph = &st.selected_shapes()[0].text.as_ref().unwrap().paragraphs[0];
assert_eq!(paragraph.props.margin_left, Some(indent));
assert_eq!(st.history.undo.len(), undo + 1);
assert_eq!(st.history.undo.last().unwrap().label, label);
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(align_of(&h), before);
assert_eq!(h.state().session.active().unwrap().history.undo.len(), undo);
}
/// Paragraph-dialog tab settings apply the chosen stop and return to the paragraph controls.
@@ -67,32 +71,39 @@ fn tabs_from_paragraph_applies_a_stop_and_returns() {
let mut h = harness();
h.get_by_label("Paragraph…").click();
h.run_steps(2);
h.state_mut().dialog.as_mut().unwrap().fields.insert("align".into(), "right".into());
// Settle the anchored window's geometry before hit-testing the button with the real pointer
// path. egui 0.37 keeps a window invisible for its first sizing frame; AccessKit can activate
// such a node, but a pointer must actually hit the visible button inside the window.
h.run_steps(3);
let tabs = h.get_by_label("Tabs…");
let rect = tabs.rect();
assert!(rect.min.x >= 0.0 && rect.max.x <= 1440.0 && rect.min.y >= 0.0 && rect.max.y <= 900.0, "Tabs… has settled on screen: {rect:?}");
tabs.click();
// The click switches the dialog at the end of one pass; wait for that and the first visible
// frame before querying the Tabs window's buttons.
h.run_steps(3);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("tabs"), "status {:?}", h.state().status);
{
let d = h.state_mut().dialog.as_mut().unwrap();
d.fields.insert("stops".into(), "2:ctr".into());
}
h.get_by_role_and_label(egui::accesskit::Role::Button, "OK").click_accesskit();
// The Tabs OK frame restores Paragraph; the next frame fills its fields.
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("paragraph"), "status {:?}", h.state().status);
assert_eq!(h.state().dialog.as_ref().unwrap().fields.get("align").map(String::as_str), Some("right"));
assert_eq!(tabs_of(&h), vec![(144.0, "ctr".into())]);
assert_eq!(h.state().session.active().unwrap().history.undo.last().unwrap().label, "Tabs…");
h.get_by_role_and_label(egui::accesskit::Role::Button, "Cancel").click_accesskit();
h.run_steps(1);
assert!(h.state().dialog.is_none());
assert_eq!(align_of(&h).as_deref(), Some("ctr"), "cancelling Paragraph leaves the alignment shape.insert wrote");
let before = align_of(&h);
let undo = h.state().session.active().unwrap().history.undo.len();
let label = h.state().session.commands().into_iter().find(|cmd| cmd.id == "format.tabs").unwrap().label;
let draft = json!("Right");
dialog(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "align", "value": draft}));
h.get_by_label("Tabs…").click();
h.run_steps(4);
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "tabs"), "status {:?}", h.state().status);
assert_eq!(align_of(&h), before, "Tabs leaves the paragraph draft unapplied");
let position = 2.0 * 72.0;
let stop = craft::text::ui::ruler::TabStop::new(
position as f32,
craft::text::ui::ruler::TabAlign::Center,
craft::text::ui::ruler::TabLeader::None,
);
dialog(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "stops", "value": [stop]}));
dialog(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "paragraph"), "status {:?}", h.state().status);
let dialogs = super::inspect(&h.ctx);
let id = craft::ui::dialog::dialog_id("paragraph").value().to_string();
let paragraph = dialogs.as_array().unwrap().iter().find(|dialog| dialog["id"] == id).unwrap();
assert_eq!(paragraph["fields"]["align"], draft);
assert_eq!(tabs_of(&h), vec![(position, "ctr".into())]);
let st = h.state().session.active().unwrap();
assert_eq!(st.history.undo.len(), undo + 1);
assert_eq!(st.history.undo.last().unwrap().label, label);
dialog(&mut h, "ui.dialog.cancel", json!({"dialog": "top"}));
assert!(super::open_keys(&h.ctx).is_empty());
assert_eq!(align_of(&h), before, "cancelling Paragraph leaves the document's alignment");
}
fn dialog(h: &mut Harness<'_, SlideApp>, method: &str, params: serde_json::Value) {
let ctx = h.ctx.clone();
super::control(h.state_mut(), &ctx, method, &params).unwrap().unwrap();
h.run_steps(4);
}
+105 -199
View File
@@ -1,17 +1,17 @@
use super::{Dialog, SlideApp, Ui, Value, buttons, check, edited, exact_of, field_of, json, num_text, parse_shown, text_row};
use craft::behavior::Mixed;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::dialog::DialogHost;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, follow_ratio};
use egui::Context;
use serde_json::{Value, json};
fn put_dim(d: &mut Dialog, key: &str, exact: f64, shown: String) {
d.fields.insert(key.into(), shown.clone());
d.fields.insert(format!("seed{key}"), shown.clone());
d.fields.insert(format!("prev{key}"), shown);
d.fields.insert(format!("{key}Pt"), exact.to_string());
}
use crate::SlideApp;
fn publish_dim(d: &mut Dialog, key: &str, exact: f64, shown: String) {
d.fields.insert(key.into(), shown.clone());
d.fields.insert(format!("seed{key}"), shown);
d.fields.insert(format!("{key}Pt"), exact.to_string());
}
// The component, opening bases and percentage companions share Height, Width order.
const DIMENSIONS: [(&str, &str, &str, &str); 2] = [("h", "scaleH", "Height", "Scale Height"), ("w", "scaleW", "Width", "Scale Width")];
const BASE_FIELDS: [&str; 2] = ["baseH", "baseW"];
fn selection_xfrm(app: &SlideApp) -> Option<deckcraft_geom::Xfrm> {
let st = app.session.active()?;
@@ -20,206 +20,112 @@ fn selection_xfrm(app: &SlideApp) -> Option<deckcraft_geom::Xfrm> {
Some(deckcraft_engine::cmd::xfrm_of(&st.doc, &st.selection, sh))
}
fn seed_size_position(app: &SlideApp, d: &mut Dialog) {
if d.fields.contains_key("baseW") {
return;
/// Opens lengths in points with inch views and percentages of the opening dimensions.
pub(crate) fn open(app: &SlideApp, ctx: &Context, params: &Value) -> HostedParamDialog {
let selection = selection_xfrm(app);
let number = |key: &str, fallback| params[key].as_f64().filter(|value| value.is_finite()).unwrap_or(fallback);
let x = number("x", selection.map_or(0.0, |x| x.x));
let y = number("y", selection.map_or(0.0, |x| x.y));
let w = number("w", selection.map_or(72.0, |x| x.w));
let h = number("h", selection.map_or(72.0, |x| x.h));
let rot = number("rot", selection.map_or(0.0, |x| x.rot));
let mut fields = DialogFields::from_pairs([
("x", x), ("y", y), ("w", w), ("h", h), ("rot", rot), ("scaleH", 100.0), ("scaleW", 100.0),
]);
fields.set("lock", params["lockAspect"].as_bool().unwrap_or(false));
let base = [h, w];
for (key, value) in BASE_FIELDS.into_iter().zip(base) {
fields.set(key, value);
}
let num = |k: &str| d.params.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
let sel = selection_xfrm(app);
let x = num("x").or_else(|| sel.map(|b| b.x)).unwrap_or(0.0);
let y = num("y").or_else(|| sel.map(|b| b.y)).unwrap_or(0.0);
let w = num("w").or_else(|| sel.map(|b| b.w)).unwrap_or(72.0);
let h = num("h").or_else(|| sel.map(|b| b.h)).unwrap_or(72.0);
let rot = num("rot").or_else(|| sel.map(|b| b.rot)).unwrap_or(0.0);
let sw = num("scaleW").unwrap_or(100.0);
let sh = num("scaleH").unwrap_or(100.0);
let lock = d.params.get("lockAspect").and_then(Value::as_bool).unwrap_or(false);
put_dim(d, "x", x, num_text(x / 72.0));
put_dim(d, "y", y, num_text(y / 72.0));
put_dim(d, "w", w, num_text(w / 72.0));
put_dim(d, "h", h, num_text(h / 72.0));
put_dim(d, "rot", rot, num_text(rot));
put_dim(d, "scaleW", sw, num_text(sw));
put_dim(d, "scaleH", sh, num_text(sh));
d.fields.insert("baseW".into(), w.to_string());
d.fields.insert("baseH".into(), h.to_string());
let bit = if lock { "1" } else { "0" };
d.fields.insert("lock".into(), bit.into());
d.fields.insert("prevlock".into(), bit.into());
}
fn scale_of(pt: f64, base: f64) -> f64 {
if base > 0.0 { pt / base * 100.0 } else { 100.0 }
}
fn current_points(d: &Dialog, key: &str) -> Option<f64> {
if edited(d, key) { parse_shown(&field_of(d, key)).map(|inches| inches * 72.0) } else { exact_of(d, key) }
}
/// Keep scale tied to size, and the other side tied when aspect is locked.
fn reconcile_size_fields(d: &mut Dialog) {
let lock = field_of(d, "lock") == "1";
let was_locked = field_of(d, "prevlock") == "1";
let base_w = parse_shown(&field_of(d, "baseW")).unwrap_or(1.0);
let base_h = parse_shown(&field_of(d, "baseH")).unwrap_or(1.0);
let ar = if base_h > 0.0 { base_w / base_h } else { 1.0 };
let (w_s, h_s, sw_s, sh_s) = (field_of(d, "w"), field_of(d, "h"), field_of(d, "scaleW"), field_of(d, "scaleH"));
let (prev_w, prev_h, prev_sw, prev_sh) = (field_of(d, "prevw"), field_of(d, "prevh"), field_of(d, "prevscaleW"), field_of(d, "prevscaleH"));
if w_s != prev_w {
if let Some(inches) = parse_shown(&w_s) {
let w_pt = inches * 72.0;
d.fields.insert("wPt".into(), w_pt.to_string());
let pct = scale_of(w_pt, base_w);
publish_dim(d, "scaleW", pct, num_text(pct));
if lock {
let h_pt = if ar > 0.0 { w_pt / ar } else { w_pt };
publish_dim(d, "h", h_pt, num_text(h_pt / 72.0));
let hp = scale_of(h_pt, base_h);
publish_dim(d, "scaleH", hp, num_text(hp));
let units = LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0);
let rows = vec![
Param::number(BASE_FIELDS[0], "", base[0], 1.0, 2).shown(false),
Param::number(BASE_FIELDS[1], "", base[1], 1.0, 2).shown(false),
Param::section("Size"),
Param::custom("size", "Size", move |ui, fields, context| {
let mut sizes = DIMENSIONS.map(|(key, _, _, _)| Mixed::Same(fields.number(key)));
let mut lock = fields.bool("lock").unwrap_or(false);
let output = LinkedFields::new("Size", Bind::bound(&mut sizes), Bind::bound(&mut lock))
.captions(DIMENSIONS.map(|(_, _, caption, _)| caption))
.mode(LinkMode::Ratio)
.layout(LinkedLayout::Column)
.lengths(units)
.scales(base, DIMENSIONS.map(|(_, _, _, caption)| caption.into()))
.show(ui);
context.gesture(&output.events);
context.gesture(&output.link);
context.unparsed(output.unparsed);
if fields.bool("lock") != Some(lock) {
fields.set("lock", lock);
}
}
} else if h_s != prev_h {
if let Some(inches) = parse_shown(&h_s) {
let h_pt = inches * 72.0;
d.fields.insert("hPt".into(), h_pt.to_string());
let pct = scale_of(h_pt, base_h);
publish_dim(d, "scaleH", pct, num_text(pct));
if lock {
let w_pt = h_pt * ar;
publish_dim(d, "w", w_pt, num_text(w_pt / 72.0));
let wp = scale_of(w_pt, base_w);
publish_dim(d, "scaleW", wp, num_text(wp));
if !output.events.is_empty() {
couple(fields, base, sizes);
}
}
} else if sw_s != prev_sw {
if let Some(pct) = parse_shown(&sw_s) {
let w_pt = base_w * pct / 100.0;
d.fields.insert("scaleWPt".into(), pct.to_string());
publish_dim(d, "w", w_pt, num_text(w_pt / 72.0));
if lock {
let h_pt = if ar > 0.0 { w_pt / ar } else { w_pt };
publish_dim(d, "h", h_pt, num_text(h_pt / 72.0));
publish_dim(d, "scaleH", pct, num_text(pct));
}
}
} else if sh_s != prev_sh {
if let Some(pct) = parse_shown(&sh_s) {
let h_pt = base_h * pct / 100.0;
d.fields.insert("scaleHPt".into(), pct.to_string());
publish_dim(d, "h", h_pt, num_text(h_pt / 72.0));
if lock {
let w_pt = h_pt * ar;
publish_dim(d, "w", w_pt, num_text(w_pt / 72.0));
publish_dim(d, "scaleW", pct, num_text(pct));
}
}
} else if lock
&& !was_locked
&& let Some(w_pt) = current_points(d, "w")
{
let h_pt = if ar > 0.0 { w_pt / ar } else { w_pt };
publish_dim(d, "h", h_pt, num_text(h_pt / 72.0));
let hp = scale_of(h_pt, base_h);
publish_dim(d, "scaleH", hp, num_text(hp));
let wp = scale_of(w_pt, base_w);
publish_dim(d, "scaleW", wp, num_text(wp));
}
for key in ["x", "y", "w", "h", "rot", "scaleW", "scaleH"] {
let v = field_of(d, key);
d.fields.insert(format!("prev{key}"), v);
}
d.fields.insert("prevlock".into(), if lock { "1".into() } else { "0".into() });
output.edit.response
})
.companions(["w", "h", "scaleW", "scaleH", "lock"])
.on_set(set_size_field)
.full_width(),
Param::new("rot", "Rotation", ParamKind::angle(rot)),
Param::section("Position"),
Param::read_only_text("origin", "", "From the top-left corner of the slide").full_width(),
Param::number("x", "Horizontal", x, 1.0, 2).length(units),
Param::number("y", "Vertical", y, 1.0, 2).length(units),
];
HostedParamDialog::new(ctx, "sizePosition", fields, move |fields| {
ParamDialog::command("sizePosition", "Size and Position", rows.clone()).values(Bind::bound(fields))
})
}
fn shown_points(d: &Dialog, key: &str, label: &str) -> Result<f64, String> {
if edited(d, key) {
let n = parse_shown(&field_of(d, key)).ok_or_else(|| format!("{label} must be a number"))?;
return Ok(n * 72.0);
fn couple(fields: &mut DialogFields, base: [f64; 2], sizes: [Mixed<Option<f64>>; 2]) {
for (i, (key, scale, _, _)) in DIMENSIONS.iter().enumerate() {
if let Mixed::Same(Some(size)) = sizes[i] {
fields.set(*key, size);
fields.set(*scale, if base[i] > 0.0 { size / base[i] * 100.0 } else { 100.0 });
}
}
exact_of(d, key).ok_or_else(|| format!("{label} must be a number"))
}
fn shown_number(d: &Dialog, key: &str, label: &str) -> Result<f64, String> {
if edited(d, key) {
return parse_shown(&field_of(d, key)).ok_or_else(|| format!("{label} must be a number"));
fn set_size_field(fields: &mut DialogFields, key: &str, value: Value) -> Result<(), String> {
if key == "lock" {
fields.set(key, value.as_bool().ok_or_else(|| "Lock aspect ratio must be true or false".to_owned())?);
return Ok(());
}
exact_of(d, key).ok_or_else(|| format!("{label} must be a number"))
}
fn size_position_value(d: &Dialog) -> Result<Value, String> {
let x = shown_points(d, "x", "Horizontal")?;
let y = shown_points(d, "y", "Vertical")?;
let rot = shown_number(d, "rot", "Rotation")?;
let base_w = parse_shown(&field_of(d, "baseW")).unwrap_or(1.0);
let base_h = parse_shown(&field_of(d, "baseH")).unwrap_or(1.0);
let mut w = if edited(d, "w") {
shown_points(d, "w", "Width")?
} else if edited(d, "scaleW") {
base_w * shown_number(d, "scaleW", "Scale width")? / 100.0
let changed = DIMENSIONS
.iter()
.position(|(dimension, scale, _, _)| key == *dimension || key == *scale)
.ok_or_else(|| "Unknown size field".to_owned())?;
let value = value.as_f64().filter(|value| value.is_finite()).ok_or_else(|| "Size and scale must be finite numbers".to_owned())?;
let base = BASE_FIELDS.map(|key| fields.number(key).unwrap_or(0.0));
let mut sizes = DIMENSIONS.map(|(key, _, _, _)| fields.number(key).unwrap_or(0.0));
let is_scale = key == DIMENSIONS[changed].1;
let proposed = if is_scale {
if !base[changed].is_finite() || base[changed] <= 0.0 {
return Err("Scaling requires a positive opening dimension".to_owned());
}
base[changed] * value / 100.0
} else {
shown_points(d, "w", "Width")?
value
};
let mut h = if edited(d, "h") {
shown_points(d, "h", "Height")?
} else if edited(d, "scaleH") {
base_h * shown_number(d, "scaleH", "Scale height")? / 100.0
if !proposed.is_finite() {
return Err("The resulting size must be finite".to_owned());
}
if is_scale && fields.bool("lock").unwrap_or(false) {
let ranges = std::array::from_fn(|_| f64::NEG_INFINITY..=f64::INFINITY);
sizes = follow_ratio(sizes, changed, proposed, &ranges);
} else {
shown_points(d, "h", "Height")?
};
if field_of(d, "lock") == "1" {
let ar = if base_h > 0.0 { base_w / base_h } else { 1.0 };
let width_drives = edited(d, "w") || edited(d, "scaleW") || (!edited(d, "h") && !edited(d, "scaleH"));
if width_drives {
h = if ar > 0.0 { w / ar } else { h };
} else {
w = h * ar;
}
sizes[changed] = proposed;
}
Ok(json!({"x": x, "y": y, "w": w, "h": h, "rot": rot, "lockAspect": field_of(d, "lock") == "1"}))
couple(fields, base, Mixed::each(sizes.map(Some)));
Ok(())
}
pub(super) fn size_position_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
seed_size_position(app, d);
ui.label(egui::RichText::new("Size").strong());
text_row(ui, d, "Height (in):", "h");
text_row(ui, d, "Width (in):", "w");
text_row(ui, d, "Rotation (°):", "rot");
text_row(ui, d, "Scale height (%):", "scaleH");
text_row(ui, d, "Scale width (%):", "scaleW");
check(ui, d, "Lock aspect ratio", "lock", false);
ui.add_space(8.0);
ui.label(egui::RichText::new("Position").strong());
ui.label("From the top-left corner of the slide");
text_row(ui, d, "Horizontal (in):", "x");
text_row(ui, d, "Vertical (in):", "y");
reconcile_size_fields(d);
let (ok, cancel) = buttons(ui, "OK");
if ok {
match size_position_value(d) {
Ok(p) => return app.run("shape.sizePosition", p).is_ok(),
Err(msg) => {
app.set_status(msg);
return false;
}
}
}
cancel
}
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
/// Opens this hosted form with the supplied parameters.
#[allow(dead_code)] // P3(dialogs-w9): dl.A9
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, params: &serde_json::Value) -> HostedParamDialog {
let _ = (app, ctx, params);
todo!("dl.A9")
}
/// Applies an accepted form result.
#[allow(dead_code)] // P3(dialogs-w9): dl.A9
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
// P3(dialogs-w9): dl.A9
let _ = host;
let _ = (app, result);
todo!("dl.A9")
/// Applies resolved dimensions without asking the engine to reapply the document's original ratio.
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
let fields = &result.fields;
app.run(
"shape.sizePosition",
json!({"x": fields.number("x"), "y": fields.number("y"), "w": fields.number("w"), "h": fields.number("h"), "rot": fields.number("rot"), "lockAspect": false}),
)
.map(|_| ())
}
@@ -7,13 +7,11 @@ use serde_json::json;
use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
// P3(dialogs-w9): sh.A2
SlideApp::new_base(deckcraft_engine::Session::with_new(), Services::default()),
let mut h = crate::test_harness::harness_with(
deckcraft_engine::Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0),
|_| {},
);
h.run_steps(2);
h
@@ -33,24 +31,28 @@ fn size_button_sets_width_in_one_undo() {
.unwrap();
h.state_mut().ui.tab = "Shape Format".into();
h.run_steps(2);
let before = box_of(h.state(), id);
let before_undo = h.state().session.active().unwrap().history.undo.len();
let label = h.state().session.commands().into_iter().find(|cmd| cmd.id == "shape.sizePosition").unwrap().label;
h.get_by_label("Size and Position…").click();
h.run_steps(2);
let dlg = h.state().dialog.as_ref().unwrap();
assert_eq!(dlg.id, "sizePosition");
assert_eq!(dlg.fields.get("w").map(String::as_str), Some("2.78"));
assert_eq!(dlg.fields.get("h").map(String::as_str), Some("1.39"));
assert_eq!(dlg.fields.get("lock").map(String::as_str), Some("0"));
h.state_mut().dialog.as_mut().unwrap().fields.insert("w".into(), "4".into());
h.run_steps(1);
h.get_by_label("OK").click_accesskit();
h.run_steps(2);
assert!(h.state().dialog.is_none());
assert_eq!(box_of(h.state(), id), (40.0, 50.0, 288.0, 100.0, 0.0));
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "sizePosition"));
let dialogs = super::inspect(&h.ctx);
let dlg = dialogs.as_array().unwrap().iter().find(|dialog| dialog["key"] == "sizePosition").unwrap();
assert_eq!(dlg["fields"]["w"].as_f64(), Some(before.2));
assert_eq!(dlg["fields"]["h"].as_f64(), Some(before.3));
assert_eq!(dlg["fields"]["lock"].as_bool(), Some(false));
let width = 4.0 * 72.0;
dialog(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "w", "value": width}));
dialog(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
assert!(super::open_keys(&h.ctx).is_empty());
assert_eq!(box_of(h.state(), id), (before.0, before.1, width, before.3, before.4));
let undo = &h.state().session.active().unwrap().history.undo;
assert_eq!(undo.last().unwrap().label, "Size and Position…");
assert_eq!(undo.last().unwrap().label, label);
assert_eq!(undo.len(), before_undo + 1);
let n = undo.len();
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
assert_eq!(box_of(h.state(), id), (40.0, 50.0, 200.0, 100.0, 0.0));
assert_eq!(box_of(h.state(), id), before);
assert_eq!(h.state().session.active().unwrap().history.undo.len(), n - 1);
}
@@ -60,15 +62,27 @@ fn lock_aspect_from_the_dialog_scales_height() {
let id = h.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [40.0, 50.0, 200.0, 100.0]})).unwrap()["id"]
.as_u64()
.unwrap();
let before = box_of(h.state(), id);
h.state_mut().run("shape.sizePosition", json!({})).unwrap();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().unwrap().id, "sizePosition");
{
let fields = &mut h.state_mut().dialog.as_mut().unwrap().fields;
fields.insert("lock".into(), "1".into());
fields.insert("w".into(), "4".into());
}
h.get_by_label("OK").click_accesskit();
dialog(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "lock", "value": true}));
h.get_by_label("Width").click();
h.run_steps(2);
assert_eq!(box_of(h.state(), id), (40.0, 50.0, 288.0, 144.0, 0.0));
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
h.get_by_label("Width").type_text("4 in");
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(2);
dialog(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
let after = box_of(h.state(), id);
let width = 4.0 * 72.0;
assert_eq!(after, (before.0, before.1, width, before.3 * width / before.2, before.4));
assert!(after.3 > before.3, "typing the width scales the height through the linked gesture");
}
fn dialog(h: &mut Harness<'_, SlideApp>, method: &str, params: serde_json::Value) {
let ctx = h.ctx.clone();
super::control(h.state_mut(), &ctx, method, &params).unwrap().unwrap();
h.run_steps(4);
}
+67 -100
View File
@@ -1,110 +1,77 @@
use super::{Dialog, SlideApp, Ui, Value, buttons, field, json, num, vec2};
use craft::text::ui::character::ParagraphFormat;
use craft::text::ui::ruler::{TabAlign, TabLeader, TabStop};
use craft::text::ui::tabs_dialog::{TabStopsDialog, TabStopsParts};
use craft::ui::dialog::{DialogHost, DialogId};
use egui::Context;
use serde_json::{Value, json};
const TAB_KINDS: [(&str, &str); 4] = [("l", "Left"), ("ctr", "Center"), ("r", "Right"), ("dec", "Decimal")];
use crate::SlideApp;
/// Format › Tabs: the default spacing and the tab stops of the selected paragraphs, edited as a
/// list (inches, as PowerPoint's dialog) and applied together with OK.
pub(super) fn tabs_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
if !d.fields.contains_key("stops") {
// Opened from Paragraph (or by `format.tabs` with no fields) the stops come with the
// dialog; otherwise they are read from the caret's paragraph.
let r = if d.params.get("tabs").is_some() { d.params.clone() } else { app.session.execute("format.ruler", &json!({})).unwrap_or_default() };
let stops: Vec<String> = r["tabs"]
.as_array()
.map(|a| a.iter().filter_map(|t| Some(format!("{}:{}", t["pos"].as_f64()? / 72.0, t["align"].as_str().unwrap_or("l")))).collect())
.unwrap_or_default();
d.fields.insert("stops".into(), stops.join("|"));
d.fields.insert("default".into(), format!("{}", r["defaultTab"].as_f64().unwrap_or(72.0) / 72.0));
/// Opens seeded tab stops, or asks the engine to enqueue its selection's seed.
pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, params: &Value) -> Result<Option<DialogId>, String> {
if params.get("tabs").is_none() {
// format.tabs emits UiRequest::Dialog with tabs_params, including after text.exit.
app.run("format.tabs", json!({}))?;
return Ok(None);
}
let mut stops: Vec<(f64, String)> = d
.get("stops", "")
.split('|')
.filter_map(|x| {
let (p, a) = x.split_once(':')?;
Some((p.parse::<f64>().ok().filter(|v| v.is_finite())?, a.to_string()))
let stops = params["tabs"]
.as_array()
.into_iter()
.flatten()
.filter_map(|stop| {
Some(TabStop::new(
stop["pos"].as_f64()? as f32,
match stop["align"].as_str() {
Some("ctr") => TabAlign::Center,
Some("r") => TabAlign::Right,
Some("dec") => TabAlign::Decimal,
_ => TabAlign::Left,
},
TabLeader::None,
))
})
.collect();
field(ui, d, "Default tab stops (in):", "default", "1");
ui.add_space(6.0);
ui.label("Tab stops:");
let mut remove = None;
egui::Grid::new("tab_stops").num_columns(3).spacing(vec2(12.0, 4.0)).show(ui, |ui| {
if stops.is_empty() {
ui.label("(none)");
ui.end_row();
}
for (i, (pos, align)) in stops.iter().enumerate() {
ui.label(format!("{pos:.2}\""));
ui.label(TAB_KINDS.iter().find(|k| k.0 == align).map(|k| k.1).unwrap_or("Left"));
if ui.small_button("Clear").on_hover_text(format!("Clear the tab at {pos:.2}\"")).clicked() {
remove = Some(i);
}
ui.end_row();
}
});
if let Some(i) = remove {
stops.remove(i);
}
ui.add_space(6.0);
ui.horizontal(|ui| {
let l = ui.label("Tab stop position (in):");
let mut v = d.get("newpos", "");
ui.add(egui::TextEdit::singleline(&mut v).desired_width(60.0)).labelled_by(l.id);
d.fields.insert("newpos".into(), v);
});
let cur = d.get("newalign", "l");
ui.horizontal(|ui| {
ui.label("Alignment:");
for (k, label) in TAB_KINDS {
if ui.radio(cur == k, label).clicked() {
d.fields.insert("newalign".into(), k.into());
}
}
});
ui.horizontal(|ui| {
if ui.button("Set").clicked()
&& let Some(p) = Some(num(d, "newpos", f64::NAN)).filter(|v| v.is_finite() && *v >= 0.0 && *v <= 56.0)
{
stops.retain(|(q, _)| (q - p).abs() > 0.005);
stops.push((p, d.get("newalign", "l")));
stops.sort_by(|a, b| a.0.total_cmp(&b.0));
d.fields.insert("newpos".into(), String::new());
}
if ui.button("Clear All").clicked() {
stops.clear();
}
});
d.fields.insert("stops".into(), stops.iter().map(|(p, a)| format!("{p}:{a}")).collect::<Vec<_>>().join("|"));
let (ok, cancel) = buttons(ui, "OK");
if ok {
let set: Vec<Value> = stops.iter().map(|(p, a)| json!({"pos": p * 72.0, "align": a})).collect();
let dt = num(d, "default", 1.0).clamp(0.02, 56.0) * 72.0;
if let Err(e) = app.run("format.tabs", json!({"set": set, "defaultTab": dt})) {
app.set_status(e);
} else if let Some(ret) = d.params.get_mut("returnParams").and_then(Value::as_object_mut) {
// Back in Paragraph, its Tabs… shows what was just applied.
ret.insert("tabs".into(), json!(set));
ret.insert("defaultTab".into(), json!(dt));
}
}
ok || cancel
let default_tab = params["defaultTab"].as_f64().unwrap_or(72.0) as f32;
Ok(Some(host.open(TabStopsDialog::new(stops, default_tab).key("tabs".to_owned()).parts(TabStopsParts::Basic).held_ok())))
}
/// Opens this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn open(
app: &mut crate::SlideApp,
ctx: &egui::Context,
host: &mut craft::ui::dialog::DialogHost,
params: &serde_json::Value,
) -> Result<Option<craft::ui::dialog::DialogId>, String> {
let _ = (app, ctx, host, params);
todo!("dl.A10")
/// Keeps Paragraph's unapplied format while the engine supplies the Tabs seed.
pub(crate) fn open_from_paragraph(
app: &mut SlideApp,
ctx: &Context,
host: &mut DialogHost,
draft: ParagraphFormat,
) -> Result<Option<DialogId>, String> {
app.dialogs.paragraph_draft = Some(draft);
let result = open(app, ctx, host, &json!({}));
if result.is_err() {
app.dialogs.paragraph_draft = None;
}
result
}
/// Advances this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w9): dl.A10
pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) {
let _ = (app, ctx, host);
todo!("dl.A10")
/// Applies each held answer once and restores Paragraph on either successful OK or Cancel.
pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
if host.take::<TabStopsDialog>().is_some()
&& let Some(draft) = app.dialogs.paragraph_draft.take()
{
super::paragraph::reopen(app, ctx, host, draft);
}
let Some(answer) = host.get_mut::<TabStopsDialog>().and_then(TabStopsDialog::take_ok) else { return };
let set: Vec<Value> = answer
.stops
.iter()
.map(|stop| {
json!({"pos": stop.position, "align": match stop.align {
TabAlign::Center => "ctr",
TabAlign::Right => "r",
TabAlign::Decimal => "dec",
_ => "l",
}})
})
.collect();
let result = app.run("format.tabs", json!({"set": set, "defaultTab": answer.default_interval})).map(|_| ());
if let Some(dialog) = host.get_mut::<TabStopsDialog>() {
dialog.answer_ok(result.map_err(Into::into));
}
}