mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 02:36:14 -06:00
dialogs-w12: net change of 2 commits
- dialogs-w12: written from its sheet - dialogs-w12: repair 1
This commit is contained in:
@@ -135,7 +135,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
quick_style
|
||||
),
|
||||
cmd!("shape.rename", "Rename", ["Selection Pane"], None, "{name, id?}", has_selection, rename),
|
||||
cmd!("shape.altText", "Alt Text", ["Shape Format", "Accessibility"], None, "{text, decorative?: bool, ids?}", has_selection, alt_text),
|
||||
cmd!(
|
||||
"shape.altText",
|
||||
"Alt Text",
|
||||
["Shape Format", "Accessibility"],
|
||||
None,
|
||||
"{text?: string, decorative?: bool, ids?}",
|
||||
has_selection,
|
||||
alt_text
|
||||
),
|
||||
cmd!("shape.visible", "Show/Hide", ["Selection Pane"], None, "{visible?: bool, ids?}", has_selection, visible),
|
||||
cmd!(
|
||||
"shape.lock",
|
||||
@@ -350,10 +358,12 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn alt_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").unwrap_or("").to_string();
|
||||
let text = str_param(p, "text");
|
||||
let deco = bool_param(p, "decorative");
|
||||
edit_shapes(s, p, "shape.altText", |sh| {
|
||||
sh.descr = text.clone();
|
||||
if let Some(text) = text {
|
||||
sh.descr = text.to_owned();
|
||||
}
|
||||
if let Some(d) = deco {
|
||||
sh.decorative = d;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,206 @@
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
use craft::behavior::{Selection, SelectionChange, keyed};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, ShowCollection as _, Sizing};
|
||||
use craft::ui::dialog::DialogHost;
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult, ParamTab,
|
||||
};
|
||||
use deckcraft_model::text::{Action, Hyperlink};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w12): dl.A9
|
||||
pub(crate) fn open(app: &crate::SlideApp, ctx: &egui::Context, params: &serde_json::Value) -> HostedParamDialog {
|
||||
let _ = (app, ctx, params);
|
||||
todo!("dl.A9")
|
||||
use crate::SlideApp;
|
||||
|
||||
/// Opens both action tabs over the first selected shape's settings.
|
||||
pub(crate) fn open(app: &SlideApp, ctx: &Context, _params: &Value) -> HostedParamDialog {
|
||||
let state = app.session.active();
|
||||
let shape = state.and_then(|s| s.selected_shapes().first().copied());
|
||||
let slides: Vec<_> = state
|
||||
.into_iter()
|
||||
.flat_map(|s| s.doc.slides.iter().enumerate())
|
||||
.map(|(i, slide)| (slide.id, format!("{}. {}", i + 1, slide.title())))
|
||||
.collect();
|
||||
let shows: Vec<_> = state.into_iter().flat_map(|s| s.doc.custom_shows.iter()).map(|show| show.name.clone()).collect();
|
||||
let mut fields = DialogFields::new();
|
||||
for (on, link) in [("click", shape.and_then(|s| s.click.as_ref())), ("hover", shape.and_then(|s| s.hover.as_ref()))] {
|
||||
seed(&mut fields, on, link, &slides, &shows);
|
||||
}
|
||||
fields.set("opening", FieldValue::Json(json!({"click": tab_values(&fields, "click"), "hover": tab_values(&fields, "hover")})));
|
||||
let tabs = vec![
|
||||
ParamTab::new("Mouse Click", rows("click", "Action on click", &slides, &shows)),
|
||||
ParamTab::new("Mouse Over", rows("hover", "Action on mouse over", &slides, &shows)),
|
||||
];
|
||||
let opening = Param::custom("opening", "", |ui, _, _| ui.allocate_response(egui::Vec2::ZERO, egui::Sense::hover())).shown(false);
|
||||
HostedParamDialog::new(ctx, "action", fields, move |fields| {
|
||||
ParamDialog::new("action", "Action Settings", vec![opening.clone()])
|
||||
.tabs(tabs.clone())
|
||||
.values(Bind::bound(fields))
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies an accepted form result.
|
||||
#[allow(dead_code)] // P3(dialogs-w12): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w12): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
fn seed(fields: &mut DialogFields, on: &str, link: Option<&Hyperlink>, slides: &[(deckcraft_model::SlideId, String)], shows: &[String]) {
|
||||
let mut kind = "link";
|
||||
let mut target = "next";
|
||||
let mut slide = 0;
|
||||
let mut url = "https://";
|
||||
let mut show = shows.first().map_or("", String::as_str);
|
||||
let mut path = "";
|
||||
match link.map(|link| &link.action) {
|
||||
None => kind = "none",
|
||||
Some(Action::NextSlide) => {}
|
||||
Some(Action::PreviousSlide) => target = "previous",
|
||||
Some(Action::FirstSlide) => target = "first",
|
||||
Some(Action::LastSlide) => target = "last",
|
||||
Some(Action::LastViewed) => target = "lastViewed",
|
||||
Some(Action::EndShow) => target = "endShow",
|
||||
Some(Action::PlayMedia) => kind = "playMedia",
|
||||
Some(Action::Url { url: value }) => {
|
||||
target = "url";
|
||||
url = value;
|
||||
}
|
||||
Some(Action::Slide { slide: id }) => {
|
||||
target = "slide";
|
||||
slide = slides.iter().position(|(slide, _)| slide == id).unwrap_or(0);
|
||||
}
|
||||
Some(Action::CustomShow { name, .. }) => {
|
||||
target = "customShow";
|
||||
show = name;
|
||||
}
|
||||
Some(Action::Program { path: value }) => {
|
||||
kind = "program";
|
||||
path = value;
|
||||
}
|
||||
}
|
||||
for (key, value) in [("kind", kind), ("target", target), ("url", url), ("show", show), ("path", path)] {
|
||||
fields.set(format!("{on}.{key}"), value);
|
||||
}
|
||||
fields.set(format!("{on}.slide"), slide as i64);
|
||||
fields.set(format!("{on}.highlight"), link.is_none_or(|link| link.highlight_click));
|
||||
}
|
||||
|
||||
fn options<const N: usize>(values: [(&str, &str); N]) -> Vec<(String, craft::ui::runtime::env::Label)> {
|
||||
values.into_iter().map(|(key, label)| (key.into(), label.into())).collect()
|
||||
}
|
||||
|
||||
fn rows(on: &str, caption: &str, slides: &[(deckcraft_model::SlideId, String)], shows: &[String]) -> Vec<Param> {
|
||||
let key = |name| format!("{on}.{name}");
|
||||
let linked = |row: Param, target: &str| row.visible_when(key("kind"), "link").visible_when(key("target"), target);
|
||||
vec![
|
||||
Param::new(
|
||||
key("kind"),
|
||||
caption,
|
||||
ParamKind::radio(
|
||||
options([("none", "None"), ("link", "Hyperlink to:"), ("program", "Run program:"), ("playMedia", "Play the shape's media")]),
|
||||
None,
|
||||
),
|
||||
),
|
||||
Param::new(
|
||||
key("target"),
|
||||
"",
|
||||
ParamKind::choice(
|
||||
options([
|
||||
("next", "Next Slide"),
|
||||
("previous", "Previous Slide"),
|
||||
("first", "First Slide"),
|
||||
("last", "Last Slide"),
|
||||
("lastViewed", "Last Slide Viewed"),
|
||||
("endShow", "End Show"),
|
||||
("customShow", "Custom Show…"),
|
||||
("slide", "Slide…"),
|
||||
("url", "URL…"),
|
||||
]),
|
||||
Some("next".into()),
|
||||
),
|
||||
)
|
||||
.under_option("link")
|
||||
.enabled_when(key("kind"), "link"),
|
||||
linked(pick_list(key("slide"), "Slide", slides.iter().map(|(_, label)| label.clone()).collect(), true), "slide"),
|
||||
linked(Param::new(key("url"), "Address:", ParamKind::text("https://")), "url"),
|
||||
linked(pick_list(key("show"), "Custom show", shows.to_vec(), false), "customShow"),
|
||||
linked(
|
||||
Param::read_only_text(key("noShows"), "", "This presentation has no custom shows.").full_width().shown(shows.is_empty()),
|
||||
"customShow",
|
||||
),
|
||||
Param::new(key("path"), "Program:", ParamKind::text("")).visible_when(key("kind"), "program"),
|
||||
Param::new(key("highlight"), "Highlight click", ParamKind::bool(true)),
|
||||
]
|
||||
}
|
||||
|
||||
fn pick_list(key: String, label: &'static str, names: Vec<String>, indexed: bool) -> Param {
|
||||
let draw_key = key.clone();
|
||||
let rows: Vec<_> = names.into_iter().enumerate().collect();
|
||||
Param::custom(key, label, move |ui, fields, _| {
|
||||
let mut picked = if indexed {
|
||||
fields.int(&draw_key).and_then(|i| usize::try_from(i).ok()).filter(|i| *i < rows.len())
|
||||
} else {
|
||||
rows.iter().position(|(_, name)| fields.text(&draw_key) == Some(name.as_str()))
|
||||
};
|
||||
let selection = picked.map(Selection::single).unwrap_or_default();
|
||||
// PLAN: plan error: the framework has no token for the action slide list's maximum height.
|
||||
let out = List::new(label).select(SelectMode::Single).sizing(Sizing::Content).selection(Bind::given(selection)).show_items(
|
||||
ui,
|
||||
&keyed(&rows, |(i, _)| *i).with_text(|(_, name)| std::borrow::Cow::Borrowed(name.as_str())),
|
||||
&mut |i, _| ListRow::new(rows[*i].1.clone()),
|
||||
);
|
||||
for event in out.events {
|
||||
if let CollectionEvent::Selection { change, .. } = event {
|
||||
picked = match change {
|
||||
SelectionChange::Set(keys) => keys.last().copied(),
|
||||
SelectionChange::Toggle(i) => (picked != Some(i)).then_some(i),
|
||||
SelectionChange::Clear => None,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(i) = picked.filter(|i| *i < rows.len()) {
|
||||
if indexed {
|
||||
fields.set(&draw_key, i as i64);
|
||||
} else {
|
||||
fields.set(&draw_key, rows[i].1.clone());
|
||||
}
|
||||
} else {
|
||||
fields.remove(&draw_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.response
|
||||
})
|
||||
}
|
||||
|
||||
fn tab_values(fields: &DialogFields, on: &str) -> Value {
|
||||
let key = |name| format!("{on}.{name}");
|
||||
json!({
|
||||
"kind": fields.text(&key("kind")).unwrap_or("none"),
|
||||
"target": fields.text(&key("target")).unwrap_or("next"),
|
||||
"slide": fields.int(&key("slide")).unwrap_or(0),
|
||||
"url": fields.text(&key("url")).unwrap_or("https://"),
|
||||
"show": fields.text(&key("show")).unwrap_or(""),
|
||||
"path": fields.text(&key("path")).unwrap_or(""),
|
||||
"highlight": fields.bool(&key("highlight")).unwrap_or(true),
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies every edited tab without replacing the other tab's action.
|
||||
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
|
||||
let Some(FieldValue::Json(opening)) = result.fields.get("opening") else {
|
||||
return Err("Action Settings: missing opening values".into());
|
||||
};
|
||||
for on in ["click", "hover"] {
|
||||
let values = tab_values(&result.fields, on);
|
||||
if opening.get(on) == Some(&values) {
|
||||
continue;
|
||||
}
|
||||
let kind = values["kind"].as_str().unwrap_or("none");
|
||||
let action = if kind == "link" { values["target"].as_str().unwrap_or("next") } else { kind };
|
||||
let mut params = json!({"on": on, "action": action, "highlight": values["highlight"]});
|
||||
match action {
|
||||
"url" => params["url"] = values["url"].clone(),
|
||||
"slide" => params["slide"] = values["slide"].clone(),
|
||||
"customShow" => params["show"] = values["show"].clone(),
|
||||
"program" => params["path"] = values["path"].clone(),
|
||||
_ => {}
|
||||
}
|
||||
app.run("shape.action", params)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,43 +1,134 @@
|
||||
/// "Mark as decorative" starts checked when every selected shape is already decorative.
|
||||
pub(super) fn alt_text_starts_decorative(decorative: impl IntoIterator<Item = bool>) -> bool {
|
||||
let mut any = false;
|
||||
for on in decorative {
|
||||
if !on {
|
||||
return false;
|
||||
}
|
||||
any = true;
|
||||
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, ParamLayout, ParamResult};
|
||||
use craft::ui::text::{AltText, AltTextField};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::SlideApp;
|
||||
|
||||
const PROMPT: &str = "How would you describe this object and its context to someone who is blind or has low vision?";
|
||||
|
||||
fn shared<T: Eq>(values: impl IntoIterator<Item = T>, empty: T) -> Mixed<T> {
|
||||
let mut values = values.into_iter();
|
||||
let first = values.next().unwrap_or(empty);
|
||||
if values.all(|value| value == first) { Mixed::Same(first) } else { Mixed::Mixed }
|
||||
}
|
||||
|
||||
/// Opens independently mixed description and decorative parts for the selection.
|
||||
pub(crate) fn open(app: &SlideApp, ctx: &Context, _params: &Value) -> HostedParamDialog {
|
||||
let shapes = app.session.active().map(|state| state.selected_shapes()).unwrap_or_default();
|
||||
let mut fields = DialogFields::new();
|
||||
match shared(shapes.iter().map(|shape| shape.descr.clone()), String::new()) {
|
||||
Mixed::Same(text) => fields.set("text", text),
|
||||
Mixed::Mixed => fields.set_mixed("text"),
|
||||
}
|
||||
any
|
||||
match shared(shapes.iter().map(|shape| shape.decorative), false) {
|
||||
Mixed::Same(decorative) => fields.set("decorative", decorative),
|
||||
Mixed::Mixed => fields.set_mixed("decorative"),
|
||||
}
|
||||
let row = Param::custom("text", PROMPT, |ui, fields, custom| {
|
||||
let mut alt = AltText::parts(
|
||||
fields.text("text").map_or(Mixed::Mixed, |text| Mixed::Same(text.to_owned())),
|
||||
fields.bool("decorative").map_or(Mixed::Mixed, Mixed::Same),
|
||||
);
|
||||
let before = alt.clone();
|
||||
let out = AltTextField::new(PROMPT, Bind::bound(&mut alt)).show(ui);
|
||||
if alt != before {
|
||||
if let Mixed::Same(text) = alt.text {
|
||||
fields.set("text", text);
|
||||
}
|
||||
if let Mixed::Same(decorative) = alt.decorative {
|
||||
fields.set("decorative", decorative);
|
||||
}
|
||||
}
|
||||
custom.gesture(&out.events);
|
||||
out.response
|
||||
})
|
||||
.companions(["decorative"])
|
||||
.full_width();
|
||||
HostedParamDialog::new(ctx, "altText", fields, move |fields| {
|
||||
ParamDialog::new("altText", "Alt Text", vec![row.clone()]).values(Bind::bound(fields)).layout(ParamLayout::Document).caption_column(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies only the shared or edited parts, preserving each untouched mixed part.
|
||||
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
|
||||
let mut params = json!({});
|
||||
if let Some(text) = result.fields.text("text") {
|
||||
params["text"] = json!(text);
|
||||
}
|
||||
if let Some(decorative) = result.fields.bool("decorative") {
|
||||
params["decorative"] = json!(decorative);
|
||||
}
|
||||
app.run("shape.altText", params).map(|_| ())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod alt_text_tests {
|
||||
use super::alt_text_starts_decorative;
|
||||
use deckcraft_engine::Session;
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{Services, SlideApp};
|
||||
|
||||
#[test]
|
||||
fn decorative_starts_checked_only_when_every_shape_is() {
|
||||
assert!(!alt_text_starts_decorative([]));
|
||||
assert!(!alt_text_starts_decorative([false]));
|
||||
assert!(alt_text_starts_decorative([true]));
|
||||
assert!(alt_text_starts_decorative([true, true]));
|
||||
assert!(!alt_text_starts_decorative([true, false]));
|
||||
fn ok_leaves_a_mixed_description_alone_and_applies_the_decorative_flag() {
|
||||
let descriptions = ["A circle above the title", "A line joining the two panels"];
|
||||
let mut session = Session::with_new();
|
||||
let mut ids = Vec::new();
|
||||
for (i, description) in descriptions.iter().enumerate() {
|
||||
let inserted = session.execute("shape.insert", &json!({"preset": "rect", "rect": [0, 0, 50, 50]})).unwrap();
|
||||
ids.push(deckcraft_model::ShapeId(u32::try_from(inserted["id"].as_u64().unwrap()).unwrap()));
|
||||
session.execute("shape.altText", &json!({"text": description, "decorative": i == 0})).unwrap();
|
||||
}
|
||||
session.execute("edit.select", &json!({"ids": ids})).unwrap();
|
||||
let mut h = crate::test_harness::harness_with(
|
||||
session,
|
||||
Services::default(),
|
||||
Harness::<SlideApp>::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0),
|
||||
|_| {},
|
||||
);
|
||||
h.run_steps(2);
|
||||
let ctx = h.ctx.clone();
|
||||
h.state_mut().open_dialog("altText", json!({}));
|
||||
h.run_steps(2);
|
||||
let opening = crate::dialogs::inspect(&ctx);
|
||||
let fields = &opening.as_array().unwrap().iter().find(|dialog| dialog["key"] == "altText").unwrap()["fields"];
|
||||
assert!(fields.get("text").is_none());
|
||||
assert!(fields.get("decorative").is_none());
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "decorative", "value": true}))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!crate::dialogs::modal_open(&ctx));
|
||||
for (id, description) in ids.iter().zip(descriptions) {
|
||||
let shape = h.state().session.doc().unwrap().shape(*id).unwrap();
|
||||
assert_eq!(shape.descr, description);
|
||||
assert!(shape.decorative);
|
||||
}
|
||||
|
||||
let shared = "The same description";
|
||||
let replacement = "A description for both objects";
|
||||
h.state_mut().run("shape.altText", json!({"text": shared, "decorative": false})).unwrap();
|
||||
h.state_mut().open_dialog("altText", json!({}));
|
||||
h.run_steps(2);
|
||||
let opening = crate::dialogs::inspect(&ctx);
|
||||
let fields = &opening.as_array().unwrap().iter().find(|dialog| dialog["key"] == "altText").unwrap()["fields"];
|
||||
assert_eq!(fields["text"], json!(shared));
|
||||
assert_eq!(fields["decorative"], json!(false));
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "text", "value": replacement}))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!crate::dialogs::modal_open(&ctx));
|
||||
for id in ids {
|
||||
let shape = h.state().session.doc().unwrap().shape(id).unwrap();
|
||||
assert_eq!(shape.descr, replacement);
|
||||
assert!(!shape.decorative);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w12): 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-w12): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w12): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
}
|
||||
|
||||
@@ -1,79 +1,137 @@
|
||||
use super::{Dialog, SlideApp, Ui, Value, check, field, json, num, vec2};
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::dialog::DialogHost;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use deckcraft_engine::gif_export::{DEFAULT_SECONDS, DEFAULT_WIDTH, MAX_SECONDS, MAX_WIDTH, MIN_SECONDS, MIN_WIDTH, SIZE_PRESETS, check_seconds};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The export dialog's Animated GIF options (size, seconds per slide, loop, slide range, hidden
|
||||
/// slides) as `file.export` params; a slide range that doesn't fit the deck is an error message.
|
||||
pub(super) fn gif_options(app: &SlideApp, ui: &mut Ui, d: &mut Dialog) -> Result<Value, String> {
|
||||
use deckcraft_engine::gif_export::{MAX_SECONDS, MAX_WIDTH, MIN_SECONDS, MIN_WIDTH, SIZE_PRESETS};
|
||||
let n = app.session.active().map_or(0, |s| s.doc.slides.len());
|
||||
let size = d.get("gifSize", "medium");
|
||||
let size_label = |k: &str| match k {
|
||||
"small" => "Small (640 px wide)",
|
||||
"large" => "Large (1280 px wide)",
|
||||
"extraLarge" => "Extra Large (1920 px wide)",
|
||||
"custom" => "Custom width",
|
||||
_ => "Medium (960 px wide)",
|
||||
};
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
let field = ui.add_sized(vec2(120.0, 20.0), egui::Label::new("Size:"));
|
||||
// P3(dialogs-w12): earlier framework ComboBox removal (no contract id)
|
||||
let combo = egui::ComboBox::from_id_salt("gif_size").selected_text(size_label(&size)).show_ui(ui, |ui| {
|
||||
for k in SIZE_PRESETS.iter().map(|(k, _)| *k).chain(["custom"]) {
|
||||
if ui.selectable_label(size == k, size_label(k)).clicked() {
|
||||
d.fields.insert("gifSize".into(), k.into());
|
||||
}
|
||||
}
|
||||
});
|
||||
let _ = combo.response.labelled_by(field.id);
|
||||
});
|
||||
if size == "custom" {
|
||||
field(ui, d, "Width (pixels):", "gifWidth", "960");
|
||||
}
|
||||
field(ui, d, "Seconds per slide:", "gifSeconds", "5");
|
||||
let n_text = n.max(1).to_string();
|
||||
field(ui, d, "From slide:", "gifFrom", "1");
|
||||
field(ui, d, "To slide:", "gifTo", &n_text);
|
||||
let forever = check(ui, d, "Loop forever", "gifLoop", true);
|
||||
let hidden = check(ui, d, "Include hidden slides", "gifHidden", false);
|
||||
use crate::SlideApp;
|
||||
|
||||
let width = if size == "custom" {
|
||||
let w = num(d, "gifWidth", 960.0).round();
|
||||
if !(f64::from(MIN_WIDTH)..=f64::from(MAX_WIDTH)).contains(&w) {
|
||||
return Err(format!("Width: enter {MIN_WIDTH} to {MAX_WIDTH} pixels"));
|
||||
fn options<const N: usize>(values: [(&str, &str); N]) -> Vec<(String, Label)> {
|
||||
values.into_iter().map(|(key, label)| (key.into(), label.into())).collect()
|
||||
}
|
||||
|
||||
/// Opens export format and format-specific options on the document form.
|
||||
pub(crate) fn open(app: &SlideApp, ctx: &Context, _params: &Value) -> HostedParamDialog {
|
||||
let n = app.session.active().map_or(0, |state| state.doc.slides.len()) as i64;
|
||||
let mut sizes: Vec<_> = SIZE_PRESETS
|
||||
.into_iter()
|
||||
.map(|(key, _)| {
|
||||
let label = match key {
|
||||
"small" => "Small (640 px wide)",
|
||||
"large" => "Large (1280 px wide)",
|
||||
"extraLarge" => "Extra Large (1920 px wide)",
|
||||
_ => "Medium (960 px wide)",
|
||||
};
|
||||
(key.to_owned(), Label::from(label))
|
||||
})
|
||||
.collect();
|
||||
sizes.push(("custom".into(), "Custom width".into()));
|
||||
let rows = vec![
|
||||
Param::new(
|
||||
"fmt",
|
||||
"Export the presentation as:",
|
||||
ParamKind::radio(
|
||||
options([
|
||||
("pdf", "PDF document (.pdf)"),
|
||||
("png", "PNG images (current slide)"),
|
||||
("pngAll", "PNG images (all slides)"),
|
||||
("jpeg", "JPEG image (current slide)"),
|
||||
("jpegAll", "JPEG images (all slides)"),
|
||||
("pptx", "PowerPoint Presentation (.pptx)"),
|
||||
("outline", "Outline (.txt)"),
|
||||
("gif", "Animated GIF (.gif)"),
|
||||
("rtf", "Outline/RTF (.rtf)"),
|
||||
]),
|
||||
Some("pdf".into()),
|
||||
),
|
||||
),
|
||||
Param::new(
|
||||
"layout",
|
||||
"Print layout:",
|
||||
ParamKind::choice(
|
||||
options([
|
||||
("slides", "Full Page Slides"),
|
||||
("notes", "Notes Pages"),
|
||||
("h1", "Handouts (1 slide per page)"),
|
||||
("h2", "Handouts (2 slides per page)"),
|
||||
("h3", "Handouts (3 slides per page)"),
|
||||
("h4", "Handouts (4 slides per page)"),
|
||||
("h6", "Handouts (6 slides per page)"),
|
||||
("h9", "Handouts (9 slides per page)"),
|
||||
]),
|
||||
Some("slides".into()),
|
||||
),
|
||||
)
|
||||
.visible_when("fmt", "pdf"),
|
||||
Param::new("hidden", "Include hidden slides", ParamKind::bool(false)).visible_when("fmt", "pdf"),
|
||||
Param::new("pngTransparent", "Transparent background", ParamKind::bool(false))
|
||||
.visible_when_in("fmt", ["png", "pngAll"])
|
||||
.tooltip("Leave the slide background out: only what is on the slide is drawn"),
|
||||
Param::new("gifSize", "Size:", ParamKind::choice(sizes, Some("medium".into()))).visible_when("fmt", "gif"),
|
||||
Param::new("gifWidth", "Width (pixels):", ParamKind::int(Some(i64::from(MIN_WIDTH)), Some(i64::from(MAX_WIDTH)), i64::from(DEFAULT_WIDTH)))
|
||||
.visible_when("fmt", "gif")
|
||||
.visible_when("gifSize", "custom"),
|
||||
Param::number("gifSeconds", "Seconds per slide:", DEFAULT_SECONDS, 0.1, 1)
|
||||
.bounds(Some(MIN_SECONDS), Some(MAX_SECONDS))
|
||||
.visible_when("fmt", "gif"),
|
||||
Param::new("gifFrom", "From slide:", ParamKind::int(Some(1), Some(n), 1)).visible_when("fmt", "gif"),
|
||||
Param::new("gifTo", "To slide:", ParamKind::int(Some(1), Some(n), n)).visible_when("fmt", "gif"),
|
||||
Param::new("gifLoop", "Loop forever", ParamKind::bool(true)).visible_when("fmt", "gif"),
|
||||
Param::new("gifHidden", "Include hidden slides", ParamKind::bool(false)).visible_when("fmt", "gif"),
|
||||
];
|
||||
HostedParamDialog::new(ctx, "export", DialogFields::new(), move |fields| {
|
||||
ParamDialog::new("export", "Export", rows.clone())
|
||||
.values(Bind::bound(fields))
|
||||
.layout(ParamLayout::Document)
|
||||
.caption_column(true)
|
||||
.ok_label(Label::from("Export"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Validates the slide range and exports with the accepted format's options.
|
||||
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
|
||||
let fields = &result.fields;
|
||||
let fmt = fields.text("fmt").unwrap_or("pdf");
|
||||
let extra = match fmt {
|
||||
"pdf" => {
|
||||
let (layout, per_page) = match fields.text("layout").unwrap_or("slides") {
|
||||
"notes" => ("notes", 0),
|
||||
"h1" => ("handouts", 1),
|
||||
"h2" => ("handouts", 2),
|
||||
"h3" => ("handouts", 3),
|
||||
"h4" => ("handouts", 4),
|
||||
"h6" => ("handouts", 6),
|
||||
"h9" => ("handouts", 9),
|
||||
_ => ("slides", 0),
|
||||
};
|
||||
json!({"layout": layout, "perPage": per_page, "includeHidden": fields.bool("hidden").unwrap_or(false)})
|
||||
}
|
||||
json!(w as u32)
|
||||
} else {
|
||||
json!(size)
|
||||
"png" | "pngAll" => {
|
||||
json!({"transparentBackground": fields.bool("pngTransparent").unwrap_or(false)})
|
||||
}
|
||||
"gif" => {
|
||||
let n = app.session.active().map_or(0, |state| state.doc.slides.len()) as i64;
|
||||
let (from, to) = (fields.int("gifFrom").unwrap_or(1), fields.int("gifTo").unwrap_or(n));
|
||||
if !(1 <= from && from <= to && to <= n) {
|
||||
return Err(format!("Slides: choose a range from 1 to {n}"));
|
||||
}
|
||||
let size = fields.text("gifSize").unwrap_or("medium");
|
||||
let width = if size == "custom" { json!(fields.int("gifWidth").unwrap_or(i64::from(DEFAULT_WIDTH))) } else { json!(size) };
|
||||
let seconds = check_seconds(fields.number("gifSeconds").unwrap_or(DEFAULT_SECONDS)).map_err(|error| error.to_string())?;
|
||||
let mut params = json!({
|
||||
"width": width, "secondsPerSlide": seconds,
|
||||
"loop": fields.bool("gifLoop").unwrap_or(true), "includeHidden": fields.bool("gifHidden").unwrap_or(false),
|
||||
});
|
||||
// The UI's inclusive 1..2 is the engine's indices [0, 1]; a full range uses its all-slides default.
|
||||
if from != 1 || to != n {
|
||||
params["slides"] = json!(((from - 1)..to).collect::<Vec<_>>());
|
||||
}
|
||||
params
|
||||
}
|
||||
_ => json!({}),
|
||||
};
|
||||
let seconds = num(d, "gifSeconds", f64::NAN);
|
||||
if deckcraft_engine::gif_export::check_seconds(seconds).is_err() {
|
||||
return Err(format!("Seconds per slide: enter {MIN_SECONDS} to {MAX_SECONDS}"));
|
||||
}
|
||||
let mut p = json!({"width": width, "secondsPerSlide": seconds, "loop": forever, "includeHidden": hidden});
|
||||
let (from, to) = (num(d, "gifFrom", 1.0).round(), num(d, "gifTo", n as f64).round());
|
||||
if !(from >= 1.0 && from <= to && to <= n as f64) {
|
||||
return Err(format!("Slides: choose a range from 1 to {n}"));
|
||||
}
|
||||
if from > 1.0 || to < n as f64 {
|
||||
p["slides"] = json!(((from as usize - 1)..(to as usize)).collect::<Vec<_>>());
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
|
||||
|
||||
/// Opens this hosted form with the supplied parameters.
|
||||
#[allow(dead_code)] // P3(dialogs-w12): 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-w12): dl.A9
|
||||
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
|
||||
// P3(dialogs-w12): dl.A9
|
||||
let _ = host;
|
||||
let _ = (app, result);
|
||||
todo!("dl.A9")
|
||||
app.export_as(fmt, extra);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user