mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 10:47:56 +01:00
dialogs-w8: net change of 3 commits
- dialogs-w8: written by an agent - dialogs-w8: finished by an agent - dialogs-w8: review fixes (review-1)
This commit is contained in:
1 parent
bc7ac9b3ff
commit
e8fdf539e4
9 files changed
+333
-373
No files matched your search
@@ -21,6 +21,9 @@ pub(super) fn scale_shapes(shapes: &mut [Shape], sx: f64, sy: f64, k: f64, ox: f
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported slide dimensions in points.
|
||||
pub const SLIDE_SIZE_RANGE: std::ops::RangeInclusive<f64> = 72.0..=4032.0;
|
||||
|
||||
pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let size = if let Some(pre) = str_param(p, "preset") {
|
||||
let k = pre.to_ascii_lowercase();
|
||||
@@ -29,8 +32,8 @@ pub(super) fn slide_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Size::new(*w, *h)
|
||||
} else {
|
||||
Size::new(
|
||||
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(72.0, 4032.0),
|
||||
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(72.0, 4032.0),
|
||||
f64_param(p, "w").ok_or_else(|| bad("design.slideSize", "missing `w`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()),
|
||||
f64_param(p, "h").ok_or_else(|| bad("design.slideSize", "missing `h`"))?.clamp(*SLIDE_SIZE_RANGE.start(), *SLIDE_SIZE_RANGE.end()),
|
||||
)
|
||||
};
|
||||
let size = match str_param(p, "orientation") {
|
||||
|
||||
@@ -114,8 +114,7 @@ pub(super) fn level(s: &mut Session, d: i32) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sp =
|
||||
if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(pt.clamp(0.0, 1584.0)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) };
|
||||
let sp = if let Some(pt) = f64_param(p, "pt") { Spacing::Pts(clamp_pt(pt)) } else { Spacing::Pct(f64_or(p, "lines", 1.0).clamp(0.0, 9.99)) };
|
||||
format_para(s, &move |para| para.props.line_spacing = Some(sp))
|
||||
}
|
||||
|
||||
@@ -169,8 +168,14 @@ pub(super) fn finite_key(p: &Value, cmd: &str, key: &str) -> Result<Option<f64>>
|
||||
}
|
||||
}
|
||||
|
||||
/// The supported paragraph spacing in points.
|
||||
pub const PARAGRAPH_PT_RANGE: std::ops::RangeInclusive<f64> = 0.0..=1584.0;
|
||||
|
||||
/// The supported first-line and hanging indent in points: the paragraph spacing range on both sides of zero.
|
||||
pub const PARAGRAPH_INDENT_RANGE: std::ops::RangeInclusive<f64> = -*PARAGRAPH_PT_RANGE.end()..=*PARAGRAPH_PT_RANGE.end();
|
||||
|
||||
pub(super) fn clamp_pt(v: f64) -> f64 {
|
||||
v.clamp(0.0, 1584.0)
|
||||
v.clamp(*PARAGRAPH_PT_RANGE.start(), *PARAGRAPH_PT_RANGE.end())
|
||||
}
|
||||
|
||||
fn parse_align(cmd: &str, s: &str) -> Result<Align> {
|
||||
@@ -260,7 +265,7 @@ pub(super) fn paragraph_dialog(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indent_right = finite_key(p, CMD, "indentRight")?.map(clamp_pt);
|
||||
let special_by = finite_key(p, CMD, "specialBy")?.map(|v| clamp_pt(v.max(0.0)));
|
||||
let indent = match p.get("special") {
|
||||
None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(-1584.0, 1584.0)),
|
||||
None => finite_key(p, CMD, "indentFirst")?.map(|v| v.clamp(*PARAGRAPH_INDENT_RANGE.start(), *PARAGRAPH_INDENT_RANGE.end())),
|
||||
Some(Value::String(kind)) => {
|
||||
let by = special_by.unwrap_or(0.0);
|
||||
Some(match kind.as_str() {
|
||||
@@ -358,9 +363,12 @@ fn current_columns(s: &Session) -> (u32, f64) {
|
||||
Some(c) => resolve::body(&c, sh),
|
||||
None => sh.text.as_ref().map(|b| b.body.clone()).unwrap_or_default(),
|
||||
};
|
||||
(body.columns.unwrap_or(1).clamp(1, 16), body.col_spacing.unwrap_or(0.0).max(0.0))
|
||||
(body.columns.unwrap_or(1).clamp(*COLUMN_COUNT_RANGE.start(), *COLUMN_COUNT_RANGE.end()), body.col_spacing.unwrap_or(0.0).max(0.0))
|
||||
}
|
||||
|
||||
/// The supported text column counts.
|
||||
pub const COLUMN_COUNT_RANGE: std::ops::RangeInclusive<u32> = 1..=16;
|
||||
|
||||
pub(super) fn columns(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "format.columns";
|
||||
let count = match p.get("count") {
|
||||
@@ -368,8 +376,10 @@ pub(super) fn columns(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(v) => {
|
||||
let n = v
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && (1.0..=16.0).contains(n))
|
||||
.ok_or_else(|| bad(CMD, "`count` must be a whole number from 1 to 16"))?;
|
||||
.filter(|n| n.fract() == 0.0 && (f64::from(*COLUMN_COUNT_RANGE.start())..=f64::from(*COLUMN_COUNT_RANGE.end())).contains(n))
|
||||
.ok_or_else(|| {
|
||||
bad(CMD, format!("`count` must be a whole number from {} to {}", COLUMN_COUNT_RANGE.start(), COLUMN_COUNT_RANGE.end()))
|
||||
})?;
|
||||
Some(n as u32)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,74 +1,42 @@
|
||||
use super::{Color32, Dialog, SlideApp, Ui, Value, buttons, field, field_of, json, num_text};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind, Word};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The Columns dialog's changed fields as `format.columns` params: Number and Spacing (inches,
|
||||
/// sent in points). A field left as the dialog showed it is left out, so each selected text box
|
||||
/// keeps its own value; `None` when neither field changed.
|
||||
fn columns_value(d: &Dialog, shown_count: &str, shown_spacing: &str) -> Result<Option<Value>, String> {
|
||||
let mut p = serde_json::Map::new();
|
||||
let count = field_of(d, "count");
|
||||
if count != shown_count {
|
||||
let n = count.trim().parse::<u32>().ok().filter(|n| (1..=16).contains(n)).ok_or("Number must be a whole number from 1 to 16")?;
|
||||
p.insert("count".into(), json!(n));
|
||||
}
|
||||
let spacing = field_of(d, "spacing");
|
||||
if spacing != shown_spacing {
|
||||
let inches = spacing
|
||||
.trim()
|
||||
.trim_end_matches("in")
|
||||
.trim_end_matches('"')
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.filter(|v| v.is_finite() && (0.0..=22.0).contains(v))
|
||||
.ok_or("Spacing must be from 0 to 22 inches")?;
|
||||
p.insert("spacing".into(), json!(inches * 72.0));
|
||||
}
|
||||
Ok((!p.is_empty()).then_some(Value::Object(p)))
|
||||
// PLAN: assumed deckcraft_engine::cmd::format::{COLUMN_COUNT_RANGE, PARAGRAPH_PT_RANGE} re-exports (ribbon-w3)
|
||||
use deckcraft_engine::cmd::format::{COLUMN_COUNT_RANGE, PARAGRAPH_PT_RANGE};
|
||||
|
||||
/// Opens Columns with hidden opening values so untouched fields preserve mixed selections.
|
||||
pub(crate) fn open(_app: &crate::SlideApp, ctx: &egui::Context, params: &Value) -> HostedParamDialog {
|
||||
let count = params.get("count").and_then(Value::as_i64).unwrap_or(1);
|
||||
let spacing = params.get("spacing").and_then(Value::as_f64).unwrap_or(0.0);
|
||||
let count_kind = ParamKind::int(Some(i64::from(*COLUMN_COUNT_RANGE.start())), Some(i64::from(*COLUMN_COUNT_RANGE.end())), count);
|
||||
let rows = vec![
|
||||
Param::new("count", Word::plain("Number:"), count_kind.clone()),
|
||||
Param::number("spacing", Word::plain("Spacing (in):"), spacing, 0.01, 2)
|
||||
.length(LengthUnits::new(UnitKind::Points, UnitKind::Inches, 72.0))
|
||||
.bounds(Some(*PARAGRAPH_PT_RANGE.start()), Some(*PARAGRAPH_PT_RANGE.end())),
|
||||
Param::new("shownCount", "", count_kind).shown(false),
|
||||
Param::number("shownSpacing", "", spacing, 0.01, 2).shown(false),
|
||||
];
|
||||
HostedParamDialog::new(ctx, "columns", DialogFields::new(), move |fields| {
|
||||
ParamDialog::new("columns", Word::plain("Columns"), rows.clone())
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.values(Bind::bound(fields))
|
||||
})
|
||||
.held_ok()
|
||||
}
|
||||
|
||||
/// Columns: the number of columns in the text box and the space between them. OK applies one
|
||||
/// `format.columns` call with the fields that changed, or none when neither did; Cancel leaves
|
||||
/// the text box as it was.
|
||||
pub(super) fn columns_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
let count = d.params.get("count").and_then(Value::as_u64).unwrap_or(1).to_string();
|
||||
let spacing = num_text(d.params.get("spacing").and_then(Value::as_f64).unwrap_or(0.0) / 72.0);
|
||||
field(ui, d, "Number:", "count", &count);
|
||||
field(ui, d, "Spacing (in):", "spacing", &spacing);
|
||||
if let Some(err) = d.fields.get("error").cloned().filter(|s| !s.is_empty()) {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(err).color(Color32::from_rgb(0xB0, 0x30, 0x30)));
|
||||
/// Applies only edited column properties in one command, leaving untouched boxes' values intact.
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, _host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
let fields = &result.fields;
|
||||
let mut params = serde_json::Map::new();
|
||||
if fields.int("count") != fields.int("shownCount") {
|
||||
params.insert("count".into(), json!(fields.int("count")));
|
||||
}
|
||||
let (ok, cancel) = buttons(ui, "OK");
|
||||
if ok {
|
||||
let applied = columns_value(d, &count, &spacing).and_then(|p| match p {
|
||||
Some(p) => app.run("format.columns", p).map(|_| ()),
|
||||
None => Ok(()),
|
||||
});
|
||||
match applied {
|
||||
Ok(()) => return true,
|
||||
Err(e) => {
|
||||
d.fields.insert("error".into(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if fields.number("spacing") != fields.number("shownSpacing") {
|
||||
params.insert("spacing".into(), json!(fields.number("spacing")));
|
||||
}
|
||||
cancel
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): 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-w8): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w8): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
if params.is_empty() { Ok(()) } else { app.run("format.columns", Value::Object(params)).map(|_| ()) }
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
//! The Columns dialog: Home › Columns › More Columns… and Format Shape › Text Box › Columns… open it
|
||||
//! with the text box's values, and OK sets the number and spacing in one undo step.
|
||||
//! The Columns dialog preserves untouched properties and groups both edits in one undo step.
|
||||
|
||||
use deckcraft_engine::Session;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Services, SlideApp};
|
||||
|
||||
@@ -30,15 +29,8 @@ fn two_boxes() -> Harness<'static, SlideApp> {
|
||||
}
|
||||
|
||||
fn harness_of(s: Session) -> Harness<'static, SlideApp> {
|
||||
// P3(dialogs-w8): 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: Harness<'static, SlideApp> = crate::test_harness::harness(s, Services::default());
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
@@ -54,115 +46,81 @@ fn columns_of_each(h: &Harness<'_, SlideApp>) -> Vec<(Option<u32>, Option<f64>)>
|
||||
st.selected_shapes().iter().map(|sh| sh.text.as_ref().map(|t| (t.body.columns, t.body.col_spacing)).unwrap_or_default()).collect()
|
||||
}
|
||||
|
||||
/// Opens the dialog on `h`'s selection, types `fields` into it and presses OK.
|
||||
fn ok_with(h: &mut Harness<'_, SlideApp>, fields: &[(&str, &str)]) {
|
||||
h.state_mut().run("format.columns", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
let d = h.state_mut().dialog.as_mut().unwrap();
|
||||
for (key, value) in fields {
|
||||
d.fields.insert((*key).into(), (*value).into());
|
||||
}
|
||||
h.get_by_label("OK").click_accesskit();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none(), "status {:?}", h.state().status);
|
||||
fn dialog_method(h: &mut Harness<'_, SlideApp>, method: &str, params: Value) {
|
||||
let ctx = h.ctx.clone();
|
||||
super::control(h.state_mut(), &ctx, method, ¶ms).unwrap().unwrap();
|
||||
}
|
||||
|
||||
/// With text boxes whose columns differ, the dialog shows the first one's values, and a field
|
||||
/// left as shown does not overwrite the others' own values.
|
||||
fn confirm(h: &mut Harness<'_, SlideApp>) {
|
||||
dialog_method(h, "ui.dialog.confirm", json!({"dialog": "top"}));
|
||||
for _ in 0..8 {
|
||||
h.run_steps(1);
|
||||
if !super::open_keys(&h.ctx).iter().any(|key| key == "columns") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!super::open_keys(&h.ctx).iter().any(|key| key == "columns"), "status {:?}", h.state().status);
|
||||
}
|
||||
|
||||
/// Opens Columns on the selection and accepts edits through the hosted dialog's input path.
|
||||
fn ok_with(h: &mut Harness<'_, SlideApp>, fields: &[(&str, Value)]) {
|
||||
h.state_mut().run("format.columns", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
for (key, value) in fields {
|
||||
dialog_method(h, "ui.dialog.set", json!({"dialog": "top", "field": key, "value": value}));
|
||||
}
|
||||
confirm(h);
|
||||
}
|
||||
|
||||
/// A field left as shown preserves each selected text box's own property.
|
||||
#[test]
|
||||
fn a_field_left_as_shown_keeps_each_text_box_s_own_value() {
|
||||
let mut h = two_boxes();
|
||||
assert_eq!(columns_of_each(&h), [(Some(2), Some(9.0)), (Some(3), Some(36.0))]);
|
||||
ok_with(&mut h, &[("count", "4")]);
|
||||
assert_eq!(columns_of_each(&h), [(Some(4), Some(9.0)), (Some(4), Some(36.0))], "Number only");
|
||||
let before = columns_of_each(&h);
|
||||
let count = 4;
|
||||
ok_with(&mut h, &[("count", json!(count))]);
|
||||
assert_eq!(columns_of_each(&h), before.iter().map(|(_, spacing)| (Some(count), *spacing)).collect::<Vec<_>>(), "Number only");
|
||||
|
||||
let mut h = two_boxes();
|
||||
ok_with(&mut h, &[("spacing", "0.5")]);
|
||||
assert_eq!(columns_of_each(&h), [(Some(2), Some(36.0)), (Some(3), Some(36.0))], "Spacing only");
|
||||
}
|
||||
let before = columns_of_each(&h);
|
||||
let spacing = 36.0;
|
||||
ok_with(&mut h, &[("spacing", json!(spacing))]);
|
||||
assert_eq!(columns_of_each(&h), before.iter().map(|(count, _)| (*count, Some(spacing))).collect::<Vec<_>>(), "Spacing only");
|
||||
|
||||
#[test]
|
||||
fn ok_with_nothing_changed_closes_without_an_edit() {
|
||||
let mut h = two_boxes();
|
||||
let before = columns_of_each(&h);
|
||||
let n = h.state().session.active().unwrap().history.undo.len();
|
||||
ok_with(&mut h, &[]);
|
||||
assert_eq!(h.state().session.active().unwrap().history.undo.len(), n);
|
||||
assert_eq!(columns_of_each(&h), [(Some(2), Some(9.0)), (Some(3), Some(36.0))]);
|
||||
assert_eq!(columns_of_each(&h), before);
|
||||
}
|
||||
|
||||
fn field(h: &Harness<'_, SlideApp>, key: &str) -> Option<String> {
|
||||
h.state().dialog.as_ref().and_then(|d| d.fields.get(key).cloned())
|
||||
fn field(h: &Harness<'_, SlideApp>, key: &str) -> Option<Value> {
|
||||
super::inspect(&h.ctx).as_array()?.iter().find(|dialog| dialog["key"] == "columns")?.get("fields")?.get(key).cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_columns_sets_the_number_and_spacing_in_one_undo() {
|
||||
let mut h = harness();
|
||||
h.state_mut().session.execute("format.columns", &json!({"count": 3, "spacing": 9.0})).unwrap();
|
||||
let before = columns_of(&h);
|
||||
let label = h.state().session.commands().into_iter().find(|command| command.id == "format.columns").unwrap().label;
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Columns").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("More Columns…").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("columns"), "status {:?}", h.state().status);
|
||||
assert_eq!(field(&h, "count").as_deref(), Some("3"));
|
||||
assert_eq!(field(&h, "spacing").as_deref(), Some("0.12"));
|
||||
{
|
||||
let d = h.state_mut().dialog.as_mut().unwrap();
|
||||
d.fields.insert("count".into(), "2".into());
|
||||
d.fields.insert("spacing".into(), "0.5".into());
|
||||
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "columns"), "status {:?}", h.state().status);
|
||||
assert_eq!(field(&h, "count").and_then(|value| value.as_u64()), before.0.map(u64::from));
|
||||
assert_eq!(field(&h, "spacing").and_then(|value| value.as_f64()), before.1);
|
||||
let (count, spacing) = (2, 36.0);
|
||||
for (key, value) in [("count", json!(count)), ("spacing", json!(spacing))] {
|
||||
dialog_method(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": key, "value": value}));
|
||||
}
|
||||
let n = h.state().session.active().unwrap().history.undo.len();
|
||||
h.get_by_label("OK").click_accesskit();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none(), "status {:?}", h.state().status);
|
||||
assert_eq!(columns_of(&h), (Some(2), Some(36.0)));
|
||||
confirm(&mut h);
|
||||
assert_eq!(columns_of(&h), (Some(count), Some(spacing)));
|
||||
let undo = &h.state().session.active().unwrap().history.undo;
|
||||
assert_eq!(undo.len(), n + 1);
|
||||
assert_eq!(undo.last().unwrap().label, "Columns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_with_the_spacing_unchanged_keeps_the_exact_spacing() {
|
||||
let mut h = harness();
|
||||
h.state_mut().session.execute("format.columns", &json!({"count": 3, "spacing": 9.0})).unwrap();
|
||||
h.state_mut().run("format.columns", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert_eq!(field(&h, "spacing").as_deref(), Some("0.12"), "shown rounded to two places");
|
||||
h.state_mut().dialog.as_mut().unwrap().fields.insert("count".into(), "4".into());
|
||||
h.get_by_label("OK").click_accesskit();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none(), "status {:?}", h.state().status);
|
||||
assert_eq!(columns_of(&h), (Some(4), Some(9.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_shape_columns_button_opens_the_dialog() {
|
||||
let mut h = harness();
|
||||
h.state_mut().ui.pane = Some("format".into());
|
||||
h.state_mut().ui.format_tab = "text".into();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Columns…").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("columns"), "status {:?}", h.state().status);
|
||||
assert_eq!(field(&h, "count").as_deref(), Some("1"));
|
||||
assert_eq!(field(&h, "spacing").as_deref(), Some("0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_number_keeps_the_dialog_open_and_changes_nothing() {
|
||||
let mut h = harness();
|
||||
h.state_mut().run("format.columns", json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
for (count, spacing) in [("0", "0.25"), ("17", "0.25"), ("two", "0.25"), ("2", "-1"), ("2", "wide")] {
|
||||
{
|
||||
let d = h.state_mut().dialog.as_mut().unwrap();
|
||||
d.fields.insert("count".into(), count.into());
|
||||
d.fields.insert("spacing".into(), spacing.into());
|
||||
}
|
||||
h.get_by_label("OK").click_accesskit();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("columns"), "{count} / {spacing}");
|
||||
assert!(field(&h, "error").is_some_and(|e| !e.is_empty()), "{count} / {spacing}");
|
||||
assert_eq!(columns_of(&h), (None, None), "{count} / {spacing}");
|
||||
}
|
||||
assert_eq!(undo.last().unwrap().label, label);
|
||||
}
|
||||
@@ -1,60 +1,43 @@
|
||||
use super::{Color32, Dialog, SlideApp, Ui, buttons, check, field, json, num, theme};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::{UnitKind, Word};
|
||||
use serde_json::json;
|
||||
|
||||
fn format_spacing(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "6".into();
|
||||
}
|
||||
if (v - v.round()).abs() < 1e-6 && v.abs() < 1.0e6 { format!("{}", v.round() as i64) } else { format!("{v:.2}") }
|
||||
// PLAN: assumed pub(crate) const GRID_SPACING_RANGE: RangeInclusive<f64> (shell-w4, re-exported by shell-w11)
|
||||
use crate::app::GRID_SPACING_RANGE;
|
||||
|
||||
/// Opens Grid Options with the current snapping and display preferences.
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, _params: &serde_json::Value) -> HostedParamDialog {
|
||||
let prefs = &app.session.prefs;
|
||||
let rows = vec![
|
||||
Param::section(Word::plain("Snap")),
|
||||
Param::new("snap", Word::plain("Snap objects to grid"), ParamKind::bool(prefs.snap_to_grid)),
|
||||
Param::new("smart", Word::plain("Snap objects to other objects"), ParamKind::bool(prefs.smart_guides)),
|
||||
Param::number("spacing", Word::plain("Spacing (pt):"), prefs.grid_spacing, 1.0, 2)
|
||||
.unit(UnitKind::Points)
|
||||
.bounds(Some(*GRID_SPACING_RANGE.start()), Some(*GRID_SPACING_RANGE.end())),
|
||||
Param::section(Word::plain("Display")),
|
||||
Param::new("gridlines", Word::plain("Display grid on screen"), ParamKind::bool(app.ui.gridlines)),
|
||||
Param::new("guides", Word::plain("Display drawing guides on screen"), ParamKind::bool(app.ui.guides)),
|
||||
];
|
||||
HostedParamDialog::new(ctx, "gridOptions", DialogFields::new(), move |fields| {
|
||||
ParamDialog::new("gridOptions", Word::plain("Grid Options"), rows.clone())
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.values(Bind::bound(fields))
|
||||
})
|
||||
.held_ok()
|
||||
}
|
||||
|
||||
/// Grid Options: spacing, snap and whether the grid and guides are drawn. OK applies one
|
||||
/// `view.gridOptions` call; Cancel leaves the presentation as it was.
|
||||
pub(super) fn grid_options(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
ui.label(egui::RichText::new("Snap").font(theme::bold(13.0)));
|
||||
let snap = check(ui, d, "Snap objects to grid", "snap", app.session.prefs.snap_to_grid);
|
||||
let smart = check(ui, d, "Snap objects to other objects", "smart", app.session.prefs.smart_guides);
|
||||
let spacing_default = format_spacing(app.session.prefs.grid_spacing);
|
||||
field(ui, d, "Spacing (pt):", "spacing", &spacing_default);
|
||||
ui.add_space(6.0);
|
||||
ui.label(egui::RichText::new("Display").font(theme::bold(13.0)));
|
||||
let gridlines = check(ui, d, "Display grid on screen", "gridlines", app.ui.gridlines);
|
||||
let guides = check(ui, d, "Display drawing guides on screen", "guides", app.ui.guides);
|
||||
if let Some(err) = d.fields.get("error").cloned().filter(|s| !s.is_empty()) {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(err).color(Color32::from_rgb(0xB0, 0x30, 0x30)));
|
||||
}
|
||||
let (ok, cancel) = buttons(ui, "OK");
|
||||
if ok {
|
||||
let spacing = num(d, "spacing", app.session.prefs.grid_spacing);
|
||||
match app.run("view.gridOptions", json!({"spacing": spacing, "snap": snap, "smartGuides": smart, "gridlines": gridlines, "guides": guides})) {
|
||||
Ok(_) => return true,
|
||||
Err(e) => {
|
||||
d.fields.insert("error".into(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
cancel
|
||||
/// Applies grid preferences, returning a command refusal to the held form.
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, _host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
let fields = &result.fields;
|
||||
app.run(
|
||||
"view.gridOptions",
|
||||
json!({
|
||||
"spacing": fields.number("spacing"), "snap": fields.bool("snap"), "smartGuides": fields.bool("smart"),
|
||||
"gridlines": fields.bool("gridlines"), "guides": fields.bool("guides"),
|
||||
}),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): 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-w8): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w8): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
}
|
||||
|
||||
/// The supported grid spacing in points.
|
||||
#[allow(dead_code)] // P3(dialogs-w7): dl.A15
|
||||
pub(crate) const GRID_SPACING_RANGE: std::ops::RangeInclusive<f64> = 1.0..=288.0;
|
||||
@@ -1,17 +1,47 @@
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::Word;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use serde_json::json;
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): dl.A9
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, params: &serde_json::Value) -> HostedParamDialog {
|
||||
let _ = (app, ctx, params);
|
||||
todo!("dl.A9")
|
||||
/// Opens Header and Footer with dependent rows nested under their check boxes.
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, _params: &serde_json::Value) -> HostedParamDialog {
|
||||
let hf = app.session.active().map(|st| st.doc.header_footer.clone()).unwrap_or_default();
|
||||
let fmt_now = if hf.date_format.is_empty() { "datetime1".to_owned() } else { hf.date_format };
|
||||
let formats = super::date_time::date_rows("en-US").into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect();
|
||||
let rows = vec![
|
||||
Param::new("date", Word::plain("Date and time"), ParamKind::bool(hf.date)),
|
||||
Param::new("dateText", Word::plain("Fixed date (empty = update automatically):"), ParamKind::text(hf.date_text)).under_row("date"),
|
||||
Param::new("dateFormat", Word::plain("Format:"), ParamKind::choice(formats, Some(fmt_now.clone())))
|
||||
.under_row("date")
|
||||
.enabled_when("date", true)
|
||||
.enabled_when("dateText", ""),
|
||||
Param::new("num", Word::plain("Slide number"), ParamKind::bool(hf.slide_number)),
|
||||
Param::new("footer", Word::plain("Footer"), ParamKind::bool(hf.footer)),
|
||||
Param::new("footerText", Word::plain("Footer text:"), ParamKind::text(hf.footer_text)).under_row("footer"),
|
||||
Param::new("hide", Word::plain("Don't show on title slide"), ParamKind::bool(hf.hide_on_title)),
|
||||
Param::new("shownFormat", "", ParamKind::text(fmt_now)).shown(false),
|
||||
];
|
||||
HostedParamDialog::new(ctx, "headerFooter", DialogFields::new(), move |fields| {
|
||||
ParamDialog::new("headerFooter", Word::plain("Header and Footer"), rows.clone())
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.ok_label(Word::plain("Apply to All").into())
|
||||
.extra_buttons(vec![("apply".to_owned(), FooterButton::new(Word::plain("Apply"), DialogRole::Alternative))])
|
||||
.values(Bind::bound(fields))
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies an accepted form result.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w8): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
/// Applies the selected scope without rewriting imported date formats left untouched.
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, _host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
let fields = &result.fields;
|
||||
let mut params = json!({
|
||||
"date": fields.bool("date"), "dateText": fields.text("dateText"), "slideNumber": fields.bool("num"),
|
||||
"footer": fields.bool("footer"), "footerText": fields.text("footerText"), "hideOnTitle": fields.bool("hide"),
|
||||
"all": result.button.is_none(),
|
||||
});
|
||||
if fields.text("dateFormat") != fields.text("shownFormat") {
|
||||
params["dateFormat"] = json!(fields.text("dateFormat"));
|
||||
}
|
||||
app.run("design.headerFooter", params).map(|_| ())
|
||||
}
|
||||
@@ -1,47 +1,100 @@
|
||||
use super::{Dialog, exact_of, field_of};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::{LengthUnits, UnitKind, Word};
|
||||
use deckcraft_model::defaults::SLIDE_SIZES;
|
||||
use serde_json::json;
|
||||
|
||||
/// A Slide Size field set to `pt`: two decimals of the unit shown, the exact points kept beside.
|
||||
pub(super) fn put_slide_dim(d: &mut Dialog, key: &str, pt: f64, ppu: f64) {
|
||||
d.fields.insert(key.into(), format!("{:.2}", pt / ppu));
|
||||
d.fields.insert(format!("{key}Pt"), pt.to_string());
|
||||
// PLAN: assumed deckcraft_engine::cmd::design::SLIDE_SIZE_RANGE re-export (ribbon-w3)
|
||||
use deckcraft_engine::cmd::design::SLIDE_SIZE_RANGE;
|
||||
|
||||
fn oriented(w: f64, h: f64, portrait: bool) -> (f64, f64) {
|
||||
if portrait && w > h || !portrait && h > w { (h, w) } else { (w, h) }
|
||||
}
|
||||
|
||||
/// A Slide Size field in points: the exact value while the text is still its rendering, else
|
||||
/// the number typed (`default` when it is not one).
|
||||
pub(super) fn slide_dim_points(d: &Dialog, key: &str, ppu: f64, default: f64) -> f64 {
|
||||
let text = field_of(d, key);
|
||||
if let Some(pt) = exact_of(d, key)
|
||||
&& text == format!("{:.2}", pt / ppu)
|
||||
{
|
||||
return pt;
|
||||
}
|
||||
text.trim().trim_end_matches(['"', '%', ' ']).parse::<f64>().ok().filter(|v| v.is_finite()).map_or(default, |v| v * ppu)
|
||||
fn preset_size(label: &str, portrait: bool) -> Option<(f64, f64)> {
|
||||
SLIDE_SIZES.iter().find(|(name, _, _)| *name == label).map(|(_, w, h)| oriented(*w, *h, portrait))
|
||||
}
|
||||
|
||||
/// The unit's abbreviation in a field label, "Width (cm):".
|
||||
pub(super) fn unit_abbr(unit: deckcraft_geom::Unit) -> &'static str {
|
||||
match unit {
|
||||
deckcraft_geom::Unit::Inches => "in",
|
||||
deckcraft_geom::Unit::Centimeters => "cm",
|
||||
deckcraft_geom::Unit::Points => "pt",
|
||||
deckcraft_geom::Unit::Pixels => "px",
|
||||
fn follow_size(fields: &mut DialogFields) {
|
||||
let (Some(w), Some(h)) = (fields.number("w"), fields.number("h")) else { return };
|
||||
let portrait = h > w;
|
||||
let selected = fields.text("preset").unwrap_or("custom");
|
||||
// Labels can share dimensions; keeping a matching choice preserves the user's selection.
|
||||
let preset = if preset_size(selected, portrait) == Some((w, h)) {
|
||||
selected.to_owned()
|
||||
} else {
|
||||
SLIDE_SIZES.iter().find(|(_, pw, ph)| oriented(*pw, *ph, portrait) == (w, h)).map_or("custom", |(label, _, _)| *label).to_owned()
|
||||
};
|
||||
fields.set("preset", preset);
|
||||
fields.set("orient", if portrait { "portrait" } else { "landscape" });
|
||||
}
|
||||
|
||||
fn apply_preset(fields: &mut DialogFields) {
|
||||
if let Some(size) = preset_size(fields.text("preset").unwrap_or("custom"), fields.text("orient") == Some("portrait")) {
|
||||
fields.set("w", size.0);
|
||||
fields.set("h", size.1);
|
||||
follow_size(fields);
|
||||
}
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): dl.A9
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, params: &serde_json::Value) -> HostedParamDialog {
|
||||
let _ = (app, ctx, params);
|
||||
todo!("dl.A9")
|
||||
fn swap(fields: &mut DialogFields) {
|
||||
if let (Some(w), Some(h)) = (fields.number("w"), fields.number("h")) {
|
||||
let (w, h) = oriented(w, h, fields.text("orient") == Some("portrait"));
|
||||
fields.set("w", w);
|
||||
fields.set("h", h);
|
||||
follow_size(fields);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies an accepted form result.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w8): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
/// Opens Slide Size with exact point dimensions and the preferred display unit.
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, _params: &serde_json::Value) -> HostedParamDialog {
|
||||
let size = app.session.active().map_or(deckcraft_model::defaults::WIDE, |st| st.doc.slide_size);
|
||||
let (shown, width, height) = match app.session.prefs.units {
|
||||
deckcraft_geom::Unit::Inches => (UnitKind::Inches, "Width (in):", "Height (in):"),
|
||||
deckcraft_geom::Unit::Centimeters => (UnitKind::Centimetres, "Width (cm):", "Height (cm):"),
|
||||
deckcraft_geom::Unit::Points => (UnitKind::Points, "Width (pt):", "Height (pt):"),
|
||||
deckcraft_geom::Unit::Pixels => (UnitKind::Pixels, "Width (px):", "Height (px):"),
|
||||
};
|
||||
let mut fields = DialogFields::new();
|
||||
fields.set("w", size.width);
|
||||
fields.set("h", size.height);
|
||||
follow_size(&mut fields);
|
||||
let mut options: Vec<_> = SLIDE_SIZES.iter().map(|(label, _, _)| ((*label).to_owned(), Word::plain(label).into())).collect();
|
||||
options.push(("custom".into(), Word::plain("Custom").into()));
|
||||
let rows = vec![
|
||||
Param::new("preset", Word::plain("Slides sized for:"), ParamKind::choice(options, Some("custom".into()))).on_change(apply_preset),
|
||||
|
||||
Param::number("w", Word::plain(width), size.width, 0.01, 2)
|
||||
.length(LengthUnits::new(UnitKind::Points, shown, 72.0))
|
||||
.bounds(Some(*SLIDE_SIZE_RANGE.start()), Some(*SLIDE_SIZE_RANGE.end()))
|
||||
.on_change(follow_size),
|
||||
Param::number("h", Word::plain(height), size.height, 0.01, 2)
|
||||
.length(LengthUnits::new(UnitKind::Points, shown, 72.0))
|
||||
.bounds(Some(*SLIDE_SIZE_RANGE.start()), Some(*SLIDE_SIZE_RANGE.end()))
|
||||
.on_change(follow_size),
|
||||
Param::new(
|
||||
"orient",
|
||||
Word::plain("Orientation:"),
|
||||
ParamKind::radio(vec![("portrait".into(), Word::plain("Portrait").into()), ("landscape".into(), Word::plain("Landscape").into())], None),
|
||||
)
|
||||
.options_in_row()
|
||||
.on_change(swap),
|
||||
Param::new("max", Word::plain("Maximize content (else ensure fit)"), ParamKind::bool(false)),
|
||||
];
|
||||
HostedParamDialog::new(ctx, "slideSize", fields, move |fields| {
|
||||
ParamDialog::new("slideSize", Word::plain("Slide Size"), rows.clone())
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.values(Bind::bound(fields))
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies the accepted point dimensions with the chosen content scaling rule.
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, _host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
let fields = &result.fields;
|
||||
app.run(
|
||||
"design.slideSize",
|
||||
json!({"w": fields.number("w"), "h": fields.number("h"), "scale": if fields.bool("max") == Some(true) { "maximize" } else { "ensureFit" }}),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
@@ -1,52 +1,41 @@
|
||||
/// Seconds for a Trim Media field. Three decimal places, trailing zeros dropped, so the text
|
||||
/// round-trips the millisecond value the clip stores.
|
||||
pub(super) fn ms_as_seconds(ms: u32) -> String {
|
||||
let s = format!("{:.3}", f64::from(ms) / 1000.0);
|
||||
let trimmed = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if trimmed.is_empty() { "0".to_string() } else { trimmed.to_string() }
|
||||
}
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::Word;
|
||||
use serde_json::json;
|
||||
|
||||
/// Parse a seconds field back to milliseconds. Blank, junk and negatives become 0; the result is
|
||||
/// rounded so `0.333` is 333 ms, not 332.
|
||||
pub(super) fn seconds_text_to_ms(text: &str) -> u32 {
|
||||
let v = text.trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let ms = (v.max(0.0) * 1000.0).round();
|
||||
if ms >= f64::from(u32::MAX) { u32::MAX } else { ms as u32 }
|
||||
}
|
||||
|
||||
/// Start, end trim, fade in and fade out, as the Trim Media dialog shows them.
|
||||
pub(super) struct TrimSeed {
|
||||
pub(super) start: String,
|
||||
pub(super) end: String,
|
||||
pub(super) fade_in: String,
|
||||
pub(super) fade_out: String,
|
||||
}
|
||||
|
||||
impl TrimSeed {
|
||||
fn zeros() -> Self {
|
||||
TrimSeed { start: "0".into(), end: "0".into(), fade_in: "0".into(), fade_out: "0".into() }
|
||||
}
|
||||
fn from_clip(m: &deckcraft_model::MediaClip) -> Self {
|
||||
TrimSeed {
|
||||
start: ms_as_seconds(m.trim_start_ms),
|
||||
end: ms_as_seconds(m.trim_end_ms),
|
||||
fade_in: ms_as_seconds(m.fade_in_ms),
|
||||
fade_out: ms_as_seconds(m.fade_out_ms),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first selected audio or video. Other shapes in the selection are skipped. No media means
|
||||
/// the old zeros, which OK then stores.
|
||||
pub(super) fn trim_seed(st: Option<&deckcraft_engine::DocState>) -> TrimSeed {
|
||||
let Some(st) = st else { return TrimSeed::zeros() };
|
||||
st.selected_shapes()
|
||||
.into_iter()
|
||||
.find_map(|sh| match &sh.kind {
|
||||
deckcraft_model::ShapeKind::Media(m) => Some(TrimSeed::from_clip(m)),
|
||||
/// Seconds for start trim, end trim, fade in and fade out of the first selected media clip.
|
||||
pub(super) fn trim_seed(st: Option<&deckcraft_engine::DocState>) -> [f64; 4] {
|
||||
st.and_then(|st| {
|
||||
st.selected_shapes().into_iter().find_map(|sh| match &sh.kind {
|
||||
deckcraft_model::ShapeKind::Media(clip) => {
|
||||
Some([clip.trim_start_ms, clip.trim_end_ms, clip.fade_in_ms, clip.fade_out_ms].map(|ms| f64::from(ms) / 1000.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(TrimSeed::zeros)
|
||||
})
|
||||
.unwrap_or([0.0; 4])
|
||||
}
|
||||
|
||||
/// Opens Trim Media with seconds fields, without a unit selector.
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, _params: &serde_json::Value) -> HostedParamDialog {
|
||||
let seed = trim_seed(app.session.active());
|
||||
let rows = [("start", "Start time (s):"), ("end", "End trim (s):"), ("fin", "Fade in (s):"), ("fout", "Fade out (s):")]
|
||||
.into_iter()
|
||||
.zip(seed)
|
||||
.map(|((key, label), value)| Param::new(key, Word::plain(label), ParamKind::number(Some(0.0), None, value, 0.1, 3)))
|
||||
.collect::<Vec<_>>();
|
||||
HostedParamDialog::new(ctx, "trim", DialogFields::new(), move |fields| {
|
||||
ParamDialog::new("trim", Word::plain("Trim Media"), rows.clone())
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.values(Bind::bound(fields))
|
||||
})
|
||||
}
|
||||
|
||||
/// Stores accepted seconds as rounded milliseconds for the selected media.
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, _host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
let ms = |key| (result.fields.number(key).unwrap_or(0.0) * 1000.0).round() as u32;
|
||||
app.run("media.options", json!({"trimStart": ms("start"), "trimEnd": ms("end"), "fadeIn": ms("fin"), "fadeOut": ms("fout")})).map(|_| ())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -55,29 +44,17 @@ mod trim_media_tests {
|
||||
|
||||
use deckcraft_model::{MediaClip, Presentation, ShapeId, ShapeKind};
|
||||
|
||||
use super::{ms_as_seconds, seconds_text_to_ms, trim_seed};
|
||||
|
||||
#[test]
|
||||
fn trim_seconds_round_trip_the_stored_milliseconds() {
|
||||
for ms in [0, 1, 250, 333, 1000, 1500, 60_000] {
|
||||
let text = ms_as_seconds(ms);
|
||||
assert_eq!(seconds_text_to_ms(&text), ms, "{text}");
|
||||
}
|
||||
assert_eq!(seconds_text_to_ms(""), 0);
|
||||
assert_eq!(seconds_text_to_ms("nope"), 0);
|
||||
assert_eq!(seconds_text_to_ms("-2"), 0);
|
||||
assert_eq!(seconds_text_to_ms("1.5"), 1500);
|
||||
assert_eq!(seconds_text_to_ms("999999999"), u32::MAX);
|
||||
}
|
||||
use super::trim_seed;
|
||||
|
||||
#[test]
|
||||
fn trim_dialog_reads_the_selected_clip() {
|
||||
assert_eq!(trim_seed(None).start, "0");
|
||||
assert_eq!(trim_seed(None), [0.0; 4]);
|
||||
let mut doc = Presentation::default();
|
||||
let clip = MediaClip { trim_start_ms: 1500, trim_end_ms: 250, fade_in_ms: 333, fade_out_ms: 1000, ..Default::default() };
|
||||
let expected = [clip.trim_start_ms, clip.trim_end_ms, clip.fade_in_ms, clip.fade_out_ms].map(|ms| f64::from(ms) / 1000.0);
|
||||
let media_id = {
|
||||
let slide = Arc::make_mut(&mut doc.slides[0]);
|
||||
let title = slide.shapes[0].id;
|
||||
let clip = MediaClip { trim_start_ms: 1500, trim_end_ms: 250, fade_in_ms: 333, fade_out_ms: 1000, ..Default::default() };
|
||||
let mut media = slide.shapes[0].clone();
|
||||
media.id = ShapeId(900);
|
||||
media.kind = ShapeKind::Media(clip);
|
||||
@@ -86,30 +63,8 @@ mod trim_media_tests {
|
||||
};
|
||||
let mut st = deckcraft_engine::DocState::new(doc, None, "t".into());
|
||||
st.selection.shapes = vec![media_id.0];
|
||||
assert_eq!(trim_seed(Some(&st)).start, "0", "a title shape is not a clip");
|
||||
assert_eq!(trim_seed(Some(&st)), [0.0; 4], "a title shape is not a clip");
|
||||
st.selection.shapes = vec![media_id.0, media_id.1];
|
||||
let seed = trim_seed(Some(&st));
|
||||
assert_eq!(seed.start, "1.5");
|
||||
assert_eq!(seed.end, "0.25");
|
||||
assert_eq!(seed.fade_in, "0.333");
|
||||
assert_eq!(seed.fade_out, "1");
|
||||
assert_eq!(trim_seed(Some(&st)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w8): 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-w8): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w8): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
}
|
||||
@@ -18,13 +18,12 @@ fn open_with_size(w: f64, h: f64) -> egui_kittest::Harness<'static, SlideApp> {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SlideApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
// P3(dialogs-w8): sh.A2
|
||||
SlideApp::new_base(s, Services::default()),
|
||||
|
||||
crate::test_harness::harness_with(
|
||||
s,
|
||||
Services::default(),
|
||||
egui_kittest::Harness::<SlideApp>::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0),
|
||||
|_| {},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -52,9 +51,10 @@ fn extreme_loaded_slide_sizes_open_in_every_view() {
|
||||
fn the_canvas_fit_survives_a_zero_slide_size_in_memory() {
|
||||
let mut s = Session::with_new();
|
||||
std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).slide_size = deckcraft_model::Size::new(0.0, f64::NAN);
|
||||
// P3(dialogs-w8): sh.A2
|
||||
let app = SlideApp::new_base(s, Services::default());
|
||||
let (r, scale) = crate::canvas::layout(&app, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 700.0)));
|
||||
let mut h: egui_kittest::Harness<'static, SlideApp> = crate::test_harness::harness(s, Services::default());
|
||||
h.run_steps(3);
|
||||
let scale = h.state().canvas_scale();
|
||||
let r = h.state().slide_rect().unwrap();
|
||||
assert!(scale.is_finite() && scale > 0.0, "{scale}");
|
||||
assert!(r.min.x.is_finite() && r.max.y.is_finite(), "{r:?}");
|
||||
assert!(r.min.x.is_finite() && r.min.y.is_finite() && r.max.x.is_finite() && r.max.y.is_finite(), "{r:?}");
|
||||
}
|
||||
Reference in new issue
Block a user