dialogs-w13: net change of 4 commits

- dialogs-w13: written by an agent
- dialogs-w13: finished by an agent
- dialogs-w13: review fixes (review-1)
- dialogs-w13: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-27 14:51:32 +00:00
1 parent b635861586
commit a015ad8cce
6 files changed
+651 -652

No files matched your search

+4
View File
@@ -21,6 +21,10 @@ mod picture;
mod text_fields;
use album::{photo_album, photo_album_edit};
pub use album::{
ALBUM_MAX_BYTES, ALBUM_MAX_ITEMS, ALBUM_MAX_TEXT, ALBUM_MAX_TOTAL, album_check_item_count, album_check_picture_bytes, album_check_text,
album_check_total_bytes,
};
pub use chart::chart_type;
use chart::{chart, chart_data, chart_options, chart_type_cmd};
use links::{action_button, hyperlink, shape_action};
+62 -22
View File
@@ -1,13 +1,57 @@
use super::picture::{content_type, media_bytes};
use super::{NO_ID_SPACE, Result, Session, ShapeKind, Value, bad, base64_encode, json};
const ALBUM_MAX_ITEMS: usize = 48;
/// Maximum number of picture and text items a photo album can carry.
pub const ALBUM_MAX_ITEMS: usize = 48;
const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024;
/// Maximum decoded bytes in one album picture.
pub const ALBUM_MAX_BYTES: usize = 32 * 1024 * 1024;
const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024;
/// Maximum decoded picture bytes in an album.
pub const ALBUM_MAX_TOTAL: usize = 64 * 1024 * 1024;
const ALBUM_MAX_TEXT: usize = 400;
/// Maximum Unicode characters in an album text box.
pub const ALBUM_MAX_TEXT: usize = 400;
/// Checks the capacity of an album draft, which may still be empty.
pub fn album_check_item_count(count: usize) -> std::result::Result<(), String> {
if count > ALBUM_MAX_ITEMS {
return Err(format!("A photo album holds at most {ALBUM_MAX_ITEMS} pictures or text boxes"));
}
Ok(())
}
/// Returns the trimmed text of a valid album text box.
pub fn album_check_text(text: &str) -> std::result::Result<&str, String> {
let text = text.trim();
if text.is_empty() {
return Err("A text box needs some text".into());
}
if text.chars().count() > ALBUM_MAX_TEXT {
return Err(format!("Text is longer than {ALBUM_MAX_TEXT} characters"));
}
Ok(text)
}
/// Checks a picture's decoded byte count without decoding its media format.
pub fn album_check_picture_bytes(name: &str, bytes: usize) -> std::result::Result<(), String> {
if bytes == 0 {
return Err("That file is empty".into());
}
if bytes > ALBUM_MAX_BYTES {
return Err(format!("{name} is larger than 32 MB"));
}
Ok(())
}
/// Adds a picture's bytes to an album draft, refusing aggregate overflow.
pub fn album_check_total_bytes(total: usize, added: usize) -> std::result::Result<usize, String> {
let next = total.saturating_add(added);
if next > ALBUM_MAX_TOTAL {
return Err("The album is larger than 64 MB".into());
}
Ok(next)
}
#[derive(Clone, Copy)]
struct AlbumLayout {
@@ -258,9 +302,7 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
if arr.is_empty() {
return Err(bad("insert.photoAlbum", "add at least one picture or text box"));
}
if arr.len() > ALBUM_MAX_ITEMS {
return Err(bad("insert.photoAlbum", "a photo album holds at most 48 pictures or text boxes"));
}
album_check_item_count(arr.len()).map_err(|message| bad("insert.photoAlbum", message))?;
let mut items = Vec::with_capacity(arr.len());
let mut total = 0usize;
for item in arr {
@@ -272,25 +314,14 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
let Some(text) = obj.get("text").and_then(Value::as_str) else {
return Err(bad("insert.photoAlbum", "each album item needs `path`, `data` or `text`"));
};
let text = text.trim();
if text.is_empty() {
return Err(bad("insert.photoAlbum", "a text box needs some text"));
}
if text.chars().count() > ALBUM_MAX_TEXT {
return Err(bad("insert.photoAlbum", "text is longer than 400 characters"));
}
let text = album_check_text(text).map_err(|message| bad("insert.photoAlbum", message))?;
items.push(AlbumItem::Text(text.to_string()));
continue;
}
let (name, bytes) = media_bytes(item, "insert.photoAlbum")?;
if bytes.len() > ALBUM_MAX_BYTES {
return Err(bad("insert.photoAlbum", format!("{name} is larger than 32 MB")));
}
let next = total.saturating_add(bytes.len());
if next > ALBUM_MAX_TOTAL {
return Err(bad("insert.photoAlbum", "the album is larger than 64 MB"));
}
total = next;
album_check_picture_bytes(&name, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?;
total = album_check_total_bytes(total, bytes.len()).map_err(|message| bad("insert.photoAlbum", message))?;
let ct = content_type(&name, &bytes);
if !ct.starts_with("image/") {
return Err(bad("insert.photoAlbum", format!("{name} is not a picture")));
@@ -777,6 +808,15 @@ mod seed_tests {
use super::*;
#[test]
fn empty_svg_album_input_cannot_edit_the_document() {
let mut s = Session::with_new();
let before = s.active().unwrap().doc.clone();
assert!(s.execute("insert.photoAlbum", &json!({"pictures": [{"name": "empty.svg", "data": ""}]})).is_err());
assert!(Arc::ptr_eq(&s.active().unwrap().doc, &before));
assert!(s.active().unwrap().history.undo.is_empty());
}
#[test]
fn reopening_an_album_seeds_at_most_the_items_an_album_takes() {
// One picture named by 500 shapes: the dialog gets 48 items, not 500 encoded copies.
+332 -317
View File
@@ -1,13 +1,28 @@
use super::{Dialog, SlideApp, Tokens, Ui, Value, buttons, check, field, json};
use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange};
use craft::host::{Host, PickRequest, Picked};
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, clicked};
use craft::ui::dialog::DialogHost;
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft::ui::runtime::env::{Env, Label};
use craft::ui::text::TextField;
use deckcraft_engine::cmd::insert::{album_check_item_count, album_check_picture_bytes, album_check_text, album_check_total_bytes};
use serde_json::{Value, json};
fn album_items(d: &Dialog) -> Option<Vec<Value>> {
let raw = d.fields.get("items").map(String::as_str).unwrap_or("[]");
serde_json::from_str::<Value>(raw).ok().and_then(|v| v.as_array().cloned())
}
use crate::SlideApp;
fn store_album_items(d: &mut Dialog, items: &[Value]) {
let raw = serde_json::to_string(items).unwrap_or_else(|_| "[]".into());
d.fields.insert("items".into(), raw);
craft_ui::words! {
/// The sentences the album's custom rows write themselves; `{rot}`, `{brightness}` and `{contrast}` stand for the
/// selected picture's values.
struct AlbumWords {
picture_status: template "photoAlbum.pictureStatus" = "Rotation {rot}°, brightness {brightness}, contrast {contrast}";
text_box_status: "photoAlbum.textBoxStatus" = "Text boxes have no picture options";
nothing_selected: "photoAlbum.nothingSelected" = "Select a picture to rotate it or change brightness and contrast";
text_box_caption: "photoAlbum.textBoxCaption" = "Text box:";
}
}
fn album_item_label(v: &Value) -> String {
@@ -19,73 +34,6 @@ fn album_item_label(v: &Value) -> String {
}
}
fn pick_album_picture(app: &mut SlideApp) -> Option<Value> {
let path = if let Some(pick) = app.services.pick_open.as_mut() {
pick("picture")
} else {
app.set_status("Pass pictures to insert.photoAlbum");
None
};
let path = path?;
let loaded = if let Some(read) = app.services.read.as_ref() {
match read(&path) {
Ok(bytes) => bytes,
Err(e) => {
app.set_status(e);
return None;
}
}
} else {
#[cfg(not(target_arch = "wasm32"))]
{
match std::fs::read(&path) {
Ok(bytes) => bytes,
Err(e) => {
app.set_status(format!("{path}: {e}"));
return None;
}
}
}
#[cfg(target_arch = "wasm32")]
{
app.set_status("The web build inserts album pictures from data passed to insert.photoAlbum");
return None;
}
};
if loaded.is_empty() {
app.set_status("That file is empty");
return None;
}
if loaded.len() > 32 * 1024 * 1024 {
app.set_status("That picture is larger than 32 MB");
return None;
}
let name = std::path::Path::new(&path).file_name().and_then(std::ffi::OsStr::to_str).filter(|s| !s.is_empty()).unwrap_or("picture").to_string();
Some(json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(&loaded)}))
}
/// Draw an accessible album combo box, preserving its current/default selection and storing a
/// newly chosen key; the caller supplies the visible label.
fn album_choice(ui: &mut Ui, d: &mut Dialog, id: &str, name: &str, key: &str, default: &str, choices: &[(&str, &str)]) {
let cur = d.get(key, default);
let label = choices.iter().find(|(k, _)| *k == cur).map(|(_, l)| *l).unwrap_or(default);
// P3(dialogs-w13): earlier framework ComboBox removal (no contract id)
let opened = egui::ComboBox::from_id_salt(id).selected_text(label).width(220.0).show_ui(ui, |ui| {
for (k, l) in choices {
if ui.selectable_label(cur == *k, *l).clicked() {
d.fields.insert(key.into(), (*k).to_string());
}
}
});
let access = name.to_string();
let shown = label.to_string();
opened.response.widget_info(move || {
let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, true, access.clone());
info.current_text_value = Some(shown.clone());
info
});
}
const ALBUM_THEMES: &[&str] = &["DeckCraft", "Harbor", "Ember", "Meadow", "Nocturne", "Paper", "Coral Reef", "Slate"];
fn current_theme(app: &SlideApp) -> String {
@@ -101,265 +49,332 @@ fn album_json_id(v: &Value) -> Option<u64> {
v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))
}
/// Copy a command's dialog params into fields once. A fresh album has no `items`.
fn seed_photo_album(app: &SlideApp, d: &mut Dialog) {
if d.fields.contains_key("seeded") {
return;
fn items(fields: &DialogFields) -> Result<Vec<Value>, String> {
let value = fields.get("items").ok_or_else(|| "The picture list is invalid".to_string())?;
serde_json::to_value(value)
.ok()
.and_then(|value| value.as_array().cloned())
.ok_or_else(|| "The picture list is invalid".to_string())
}
fn selected(fields: &DialogFields, list: &[Value]) -> Option<usize> {
fields.int("sel").and_then(|n| usize::try_from(n).ok()).filter(|i| *i < list.len())
}
fn is_picture(item: &Value) -> bool {
item.get("data").is_some() || item.get("path").is_some()
}
struct AlbumRows<'a>(&'a [Value]);
impl DisplayOrder<usize> for AlbumRows<'_> {
fn len(&self) -> usize {
self.0.len()
}
d.fields.insert("seeded".into(), "1".into());
let p = d.params.clone();
if let Some(items) = p.get("items").and_then(Value::as_array) {
store_album_items(d, items);
d.fields.insert("editing".into(), "1".into());
fn key(&self, at: usize) -> usize {
at
}
for key in ["layout", "frame", "theme"] {
if let Some(v) = p.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()) {
d.fields.insert(key.into(), v.to_string());
}
fn index_of(&self, key: &usize) -> Option<usize> {
(*key < self.0.len()).then_some(*key)
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
self.0.get(at).map(|item| album_item_label(item).into())
}
}
impl ItemSource<usize> for AlbumRows<'_> {}
fn choice(key: &str, label: &str, default: &str, options: &[(&str, &str)]) -> Param {
let options = options.iter().map(|(id, name)| ((*id).into(), Label::from((*name).to_string()))).collect();
Param::new(key, Label::from(label.to_string()), ParamKind::choice(options, Some(default.into())))
}
/// Opens an album draft with caller data carried by hidden form rows.
pub(crate) fn open(app: &SlideApp, ctx: &egui::Context, params: &Value) -> HostedParamDialog {
let mut fields = DialogFields::new();
fields.set("items", FieldValue::Json(params.get("items").cloned().unwrap_or_else(|| json!([]))));
fields.set("sel", 0_i64);
fields.set("boxText", "Text Box");
let theme = params
.get("theme")
.and_then(Value::as_str)
.filter(|name| !name.is_empty())
.map(str::to_string)
.unwrap_or_else(|| current_theme(app));
fields.set("themeWas", theme.clone());
fields.set("theme", theme);
for (key, default) in [("layout", "1"), ("frame", "rect")] {
fields.set(key, params.get(key).and_then(Value::as_str).unwrap_or(default));
}
for key in ["captions", "grayscale"] {
if let Some(v) = p.get(key).and_then(Value::as_bool) {
d.fields.insert(key.into(), if v { "1".into() } else { "0".into() });
}
fields.set(key, params.get(key).and_then(Value::as_bool).unwrap_or(false));
}
if let Some(id) = p.get("album").and_then(album_json_id).filter(|n| *n != 0) {
d.fields.insert("album".into(), id.to_string());
}
let theme_was = d.fields.get("theme").cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| current_theme(app));
if !d.fields.contains_key("theme") {
d.fields.insert("theme".into(), theme_was.clone());
}
d.fields.entry("themeWas".into()).or_insert(theme_was);
}
fn selected_album_picture(d: &Dialog, items: &[Value]) -> bool {
let i = d.fields.get("sel").and_then(|s| s.parse::<usize>().ok()).unwrap_or(0);
items.get(i).is_some_and(|item| item.get("data").is_some() || item.get("path").is_some())
}
fn with_selected_picture(d: &mut Dialog, f: impl FnOnce(&mut serde_json::Map<String, Value>)) {
let Some(mut list) = album_items(d) else { return };
let i = d.fields.get("sel").and_then(|s| s.parse::<usize>().ok()).unwrap_or(0);
let Some(item) = list.get_mut(i) else { return };
if item.get("data").is_none() && item.get("path").is_none() {
return;
}
let Some(obj) = item.as_object_mut() else { return };
f(obj);
store_album_items(d, &list);
}
/// Photo Album. Returns true when the dialog should close.
pub(super) fn photo_album_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
seed_photo_album(app, d);
ui.set_min_width(440.0);
egui::ScrollArea::vertical().max_height(520.0).id_salt("album_body").show(ui, |ui| {
ui.set_min_width(420.0);
ui.label("Pictures in album");
let items = album_items(d).unwrap_or_default();
let mut sel = d.get("sel", "0").parse::<usize>().unwrap_or(0);
// Fixed height so adding pictures does not push Create past the window.
egui::ScrollArea::vertical().max_height(120.0).min_scrolled_height(120.0).auto_shrink([false, false]).id_salt("album_list").show(ui, |ui| {
if items.is_empty() {
ui.label(egui::RichText::new("No pictures yet").color(Tokens::get(ui.ctx()).text_dim));
}
for (i, item) in items.iter().enumerate() {
if ui.selectable_label(sel == i, album_item_label(item)).clicked() {
sel = i;
}
}
});
d.fields.insert("sel".into(), sel.to_string());
ui.horizontal(|ui| {
if ui.button("Add Pictures…").clicked()
&& let Some(item) = pick_album_picture(app)
{
match album_items(d) {
Some(mut list) if list.len() < 48 => {
list.push(item);
let next = list.len().saturating_sub(1);
store_album_items(d, &list);
d.fields.insert("sel".into(), next.to_string());
let album = params.get("album").and_then(album_json_id).and_then(|id| i64::try_from(id).ok()).unwrap_or(0);
fields.set("album", album);
let editing = params.get("items").is_some();
HostedParamDialog::new(ctx, "photoAlbum", fields, move |fields| {
let list = Param::custom("items", "Pictures in album", |ui, fields, context| {
Stack::new().show(ui, |ui, _| {
let Ok(mut list) = items(fields) else {
Text::new("The picture list is invalid").show(ui);
return;
};
let mut sel = selected(fields, &list);
let sel_was = sel;
let mut edited = false;
let mut selection = sel.map(Selection::single).unwrap_or_default();
Text::new("Pictures in album").show(ui);
let output = List::new("Pictures in album")
.select(SelectMode::Single)
.selection(Bind::bound(&mut selection))
.min_rows(5)
.max_rows(5)
.empty("No pictures yet")
.show_items(ui, &AlbumRows(&list), &mut |key, cx| ListRow::new(album_item_label(&list[*key])).state(cx.row.clone()));
for event in output.events {
if let CollectionEvent::Selection { change, .. } = event {
match change {
SelectionChange::Set(keys) => sel = keys.last().copied(),
SelectionChange::Toggle(key) => sel = (sel != Some(key)).then_some(key),
SelectionChange::Clear => sel = None,
_ => {}
}
}
Some(_) => app.set_status("A photo album holds at most 48 pictures or text boxes"),
None => app.set_status("The picture list is invalid"),
}
}
if ui.button("New Text Box").clicked() {
let text = d.get("boxText", "Text Box");
let text = text.trim();
if text.is_empty() {
app.set_status("Type the text for the new text box");
} else if text.chars().count() > 400 {
app.set_status("Text is longer than 400 characters");
} else if let Some(mut list) = album_items(d) {
if list.len() >= 48 {
app.set_status("A photo album holds at most 48 pictures or text boxes");
} else {
let mut text = fields.text("boxText").unwrap_or("Text Box").to_string();
Row::new().show(ui, |ui, _| {
let can_pick = Host::of(ui).files().can_pick();
if clicked(&Button::new("Add Pictures…").enabled(can_pick).tooltip("Pass pictures to insert.photoAlbum").show(ui)) {
context.request_action("addPictures");
}
let draft = album_check_item_count(list.len().saturating_add(1)).and_then(|()| album_check_text(&text).map(str::to_string));
let mut add = Button::new("New Text Box").enabled(draft.is_ok());
if let Err(reason) = &draft {
add = add.tooltip(reason.clone());
}
if clicked(&add.show(ui))
&& let Ok(text) = draft
{
edited = true;
list.push(json!({"text": text}));
let next = list.len().saturating_sub(1);
store_album_items(d, &list);
d.fields.insert("sel".into(), next.to_string());
sel = Some(list.len() - 1);
}
if clicked(&Button::new("Remove").enabled(sel.is_some()).show(ui))
&& let Some(at) = sel
{
edited = true;
list.remove(at);
sel = (!list.is_empty()).then(|| at.min(list.len() - 1));
}
});
Row::new().show(ui, |ui, _| {
Text::new(Env::of(ui).words::<AlbumWords>().text_box_caption.clone()).show(ui);
let edit = TextField::new("Text box", Bind::bound(&mut text)).show(ui);
if edit.value().is_some() {
fields.set("boxText", text.clone());
}
});
if sel != sel_was {
fields.set("sel", sel.and_then(|i| i64::try_from(i).ok()).unwrap_or(-1));
}
}
if ui.button("Remove").clicked()
&& let Some(mut list) = album_items(d)
&& let Some(i) = d.get("sel", "0").parse::<usize>().ok()
&& i < list.len()
{
list.remove(i);
store_album_items(d, &list);
let next = i.min(list.len().saturating_sub(1));
d.fields.insert("sel".into(), next.to_string());
}
});
field(ui, d, "Text box:", "boxText", "Text Box");
let picture = selected_album_picture(d, &items);
ui.label(album_picture_status(&items, sel));
ui.horizontal_wrapped(|ui| {
ui.add_enabled_ui(picture, |ui| {
if ui.button("Rotate Left").clicked() {
with_selected_picture(d, |obj| {
let cur = obj.get("rot").and_then(Value::as_f64).unwrap_or(0.0);
let next = ((cur - 90.0) % 360.0 + 360.0) % 360.0;
obj.insert("rot".into(), json!(next));
});
if edited {
fields.set("items", FieldValue::Json(json!(list)));
}
if ui.button("Rotate Right").clicked() {
with_selected_picture(d, |obj| {
let cur = obj.get("rot").and_then(Value::as_f64).unwrap_or(0.0);
let next = ((cur + 90.0) % 360.0 + 360.0) % 360.0;
obj.insert("rot".into(), json!(next));
});
})
.output
})
.companions(["sel", "boxText"])
.full_width();
let options = Param::custom("pictureOptions", "Picture options", |ui, fields, _| {
Stack::new().show(ui, |ui, _| {
let Ok(mut list) = items(fields) else { return };
let sel = selected(fields, &list);
let picture = sel.filter(|at| is_picture(&list[*at]));
let mut edited = false;
let words = Env::of(ui).words::<AlbumWords>();
let status: Label = match sel.map(|at| &list[at]) {
Some(item) if is_picture(item) => {
let rot = item.get("rot").and_then(Value::as_f64).unwrap_or(0.0);
let brightness = item.get("brightness").and_then(Value::as_f64).unwrap_or(0.0);
let contrast = item.get("contrast").and_then(Value::as_f64).unwrap_or(0.0);
Label::from(words.picture_status.fill(&[
("rot", &format!("{rot:.0}")),
("brightness", &format!("{brightness:.1}")),
("contrast", &format!("{contrast:.1}")),
]))
}
Some(_) => words.text_box_status.clone(),
None => words.nothing_selected.clone(),
};
Text::new(status).show(ui);
Row::new().wrap(true).show(ui, |ui, _| {
for (label, key, delta) in [
("Rotate Left", "rot", -90.0),
("Rotate Right", "rot", 90.0),
("More Brightness", "brightness", 0.1),
("Less Brightness", "brightness", -0.1),
("More Contrast", "contrast", 0.1),
("Less Contrast", "contrast", -0.1),
] {
if clicked(&Button::new(label).enabled(picture.is_some()).show(ui))
&& let Some(obj) = picture.and_then(|at| list[at].as_object_mut())
{
edited = true;
if key == "rot" {
let cur = obj.get(key).and_then(Value::as_f64).unwrap_or(0.0);
obj.insert(key.into(), json!((cur + delta).rem_euclid(360.0)));
} else {
nudge_picture(obj, key, delta);
}
}
}
});
if edited {
fields.set("items", FieldValue::Json(json!(list)));
}
if ui.button("More Brightness").clicked() {
nudge_picture(d, "brightness", 0.1);
}
if ui.button("Less Brightness").clicked() {
nudge_picture(d, "brightness", -0.1);
}
if ui.button("More Contrast").clicked() {
nudge_picture(d, "contrast", 0.1);
}
if ui.button("Less Contrast").clicked() {
nudge_picture(d, "contrast", -0.1);
}
});
});
ui.add_space(4.0);
ui.label("Picture layout");
album_choice(
ui,
d,
"album_layout",
"Picture layout",
"layout",
"1",
&[
("fit", "Fit to slide"),
("1", "1 picture"),
("2", "2 pictures"),
("4", "4 pictures"),
("1title", "1 picture with title"),
("2title", "2 pictures with title"),
("4title", "4 pictures with title"),
],
);
ui.label("Frame shape");
album_choice(
ui,
d,
"album_frame",
"Frame shape",
"frame",
"rect",
&[("none", "None"), ("rect", "Rectangle"), ("rounded", "Rounded"), ("simple", "Simple, white")],
);
check(ui, d, "Captions under pictures", "captions", false);
check(ui, d, "ALL pictures black and white", "grayscale", false);
ui.label("Album theme");
album_choice(ui, d, "album_theme", "Album theme", "theme", "DeckCraft", &ALBUM_THEMES.iter().map(|n| (*n, *n)).collect::<Vec<_>>());
});
let captions = d.fields.get("captions").is_some_and(|v| v == "1");
let grayscale = d.fields.get("grayscale").is_some_and(|v| v == "1");
let editing = d.fields.get("editing").is_some_and(|v| v == "1");
let (ok, cancel) = buttons(ui, if editing { "Update" } else { "Create" });
if ok {
let Some(list) = album_items(d) else {
app.set_status("The picture list is invalid");
return false;
};
if list.is_empty() {
app.set_status("Add a picture or a text box first");
return false;
}
let layout = d.get("layout", "1");
let frame = d.get("frame", "rect");
let theme = d.get("theme", "DeckCraft");
let theme_was = d.fields.get("themeWas").cloned().unwrap_or_default();
let mut payload = json!({"pictures": list, "layout": layout, "frame": frame, "captions": captions, "grayscale": grayscale});
if theme != theme_was
&& let Some(obj) = payload.as_object_mut()
{
obj.insert("theme".into(), json!(theme));
}
if editing {
if let Some(album) = d.fields.get("album").filter(|s| !s.is_empty() && s.as_str() != "0")
&& let Ok(id) = album.parse::<u64>()
&& let Some(obj) = payload.as_object_mut()
{
obj.insert("album".into(), json!(id));
}
return app.run("insert.photoAlbumEdit", payload).is_ok();
}
return app.run("insert.photoAlbum", payload).is_ok();
}
cancel
})
.output
})
.full_width();
let rows = vec![
list,
options,
choice(
"layout",
"Picture layout",
"1",
&[
("fit", "Fit to slide"),
("1", "1 picture"),
("2", "2 pictures"),
("4", "4 pictures"),
("1title", "1 picture with title"),
("2title", "2 pictures with title"),
("4title", "4 pictures with title"),
],
),
choice("frame", "Frame shape", "rect", &[("none", "None"), ("rect", "Rectangle"), ("rounded", "Rounded"), ("simple", "Simple, white")]),
Param::new("captions", "Captions under pictures", ParamKind::bool(false)),
Param::new("grayscale", "ALL pictures black and white", ParamKind::bool(false)),
choice("theme", "Album theme", "DeckCraft", &ALBUM_THEMES.iter().map(|name| (*name, *name)).collect::<Vec<_>>()),
Param::new("album", "Album", ParamKind::int(None, None, 0)).shown(false),
Param::new("themeWas", "Opening theme", ParamKind::text("")).shown(false),
];
ParamDialog::new("photoAlbum", "Photo Album", rows)
.values(Bind::bound(fields))
.layout(ParamLayout::Document)
.caption_column(true)
.ok_label(if editing { Label::from("Update") } else { Label::from("Create") })
})
.held_ok()
}
fn album_picture_status(items: &[Value], sel: usize) -> String {
let Some(item) = items.get(sel) else {
return "Select a picture to rotate it or change brightness and contrast".into();
fn nudge_picture(obj: &mut serde_json::Map<String, Value>, key: &str, delta: f64) {
let cur = obj.get(key).and_then(Value::as_f64).unwrap_or(0.0);
let next = (((cur + delta) * 10.0).round() / 10.0).clamp(-1.0, 1.0);
obj.insert(key.into(), json!(next));
}
fn picture_bytes(list: &[Value]) -> Result<usize, String> {
list.iter().try_fold(0, |total, item| {
let bytes = item
.get("data")
.and_then(Value::as_str)
.map(|data| deckcraft_engine::cmd::base64_decode(data).ok_or_else(|| "Invalid picture data".to_string()))
.transpose()?;
album_check_total_bytes(total, bytes.as_ref().map_or(0, Vec::len))
})
}
fn append_picture(dialog: &mut HostedParamDialog, name: &str, bytes: &[u8], total: &mut usize) -> Result<(), String> {
album_check_picture_bytes("That picture", bytes.len())?;
let mut list = items(dialog.fields())?;
album_check_item_count(list.len().saturating_add(1))?;
let next = album_check_total_bytes(*total, bytes.len())?;
let name = std::path::Path::new(name)
.file_name()
.and_then(std::ffi::OsStr::to_str)
.filter(|name| !name.is_empty())
.unwrap_or("picture");
list.push(json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(bytes)}));
dialog.set_field("sel", FieldValue::Int(i64::try_from(list.len() - 1).map_err(|error| error.to_string())?));
dialog.set_field("items", FieldValue::Json(json!(list)));
*total = next;
Ok(())
}
/// Consumes each action and file answer once, so a second pass has no input to replay.
pub(crate) fn each_pass(app: &mut SlideApp, _ctx: &egui::Context, dialog: &mut HostedParamDialog) {
let files = app.host.files();
for action in dialog.take_actions() {
if action == "addPictures" && app.dialogs.album_pick.is_none() {
if files.can_pick() {
app.dialogs.album_pick = Some(files.pick(PickRequest::open_many("picture")));
} else {
dialog.set_notes(vec![Label::from("Pass pictures to insert.photoAlbum")]);
}
}
}
let Some(answer) = app.dialogs.album_pick.and_then(|id| files.take_answer(id)) else { return };
app.dialogs.album_pick = None;
let mut total = match items(dialog.fields()).and_then(|list| picture_bytes(&list)) {
Ok(total) => total,
Err(message) => {
dialog.set_notes(vec![Label::from(message)]);
return;
}
};
if item.get("data").is_none() && item.get("path").is_none() {
return "Text boxes have no picture options".into();
let mut notes = Vec::new();
match answer {
Picked::Paths(paths) => {
for path in paths {
let result = files
.read(&path)
.map_err(|error| error.to_string())
.and_then(|bytes| append_picture(dialog, &path.to_string_lossy(), &bytes, &mut total));
if let Err(message) = result {
notes.push(Label::from(message));
}
}
}
Picked::Contents(contents) => {
for (name, bytes) in contents {
if let Err(message) = append_picture(dialog, &name, &bytes, &mut total) {
notes.push(Label::from(message));
}
}
}
Picked::Unavailable(message) | Picked::Failed(message) => notes.push(Label::from(message)),
Picked::Cancelled => {}
_ => notes.push(Label::from("Choose pictures to add to the album")),
}
let rot = item.get("rot").and_then(Value::as_f64).unwrap_or(0.0);
let brightness = item.get("brightness").and_then(Value::as_f64).unwrap_or(0.0);
let contrast = item.get("contrast").and_then(Value::as_f64).unwrap_or(0.0);
format!("Rotation {rot:.0}°, brightness {brightness:.1}, contrast {contrast:.1}")
dialog.set_notes(notes);
}
fn nudge_picture(d: &mut Dialog, key: &str, delta: f64) {
with_selected_picture(d, |obj| {
let cur = obj.get(key).and_then(Value::as_f64).unwrap_or(0.0);
let next = (((cur + delta) * 10.0).round() / 10.0).clamp(-1.0, 1.0);
obj.insert(key.into(), json!(next));
/// Inserts or reflows the complete album in one engine command.
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
let fields = &result.fields;
let list = items(fields)?;
if list.is_empty() {
return Err("Add a picture or a text box first".into());
}
let mut payload = json!({
"pictures": list,
"layout": fields.text("layout").unwrap_or("1"),
"frame": fields.text("frame").unwrap_or("rect"),
"captions": fields.bool("captions").unwrap_or(false),
"grayscale": fields.bool("grayscale").unwrap_or(false),
});
}
use craft::ui::patterns::form_dialogs::{HostedParamDialog, ParamResult};
/// Opens this hosted form with the supplied parameters.
#[allow(dead_code)] // P3(dialogs-w13): 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-w13): dl.A9
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
// P3(dialogs-w13): dl.A9
let _ = host;
let _ = (app, result);
todo!("dl.A9")
}
/// Advances the photo album file pick.
#[allow(dead_code)] // P3(dialogs-w13): dl.A9
pub(crate) fn each_pass(app: &mut crate::SlideApp, ctx: &egui::Context, dialog: &mut HostedParamDialog) {
let _ = (app, ctx, dialog);
todo!("dl.A9")
let theme = fields.text("theme").unwrap_or_default();
if Some(theme) != fields.text("themeWas") {
payload["theme"] = json!(theme);
}
let album = fields.int("album").filter(|id| *id > 0);
if let Some(album) = album {
payload["album"] = json!(album);
}
app.run(if album.is_some() { "insert.photoAlbumEdit" } else { "insert.photoAlbum" }, payload).map(|_| ())
}
+138 -106
View File
@@ -1,11 +1,15 @@
//! Photo Album dialog: the Insert ribbon opens it, and Create inserts the pictures in one step.
//! Album creation, reflow and cancellation use the hosted form and the installed file service.
use std::sync::Arc;
use craft::host::{PickRequest, Picked, ScriptedFiles};
use deckcraft_engine::Session;
use deckcraft_model::ShapeKind;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use serde_json::{Value, json};
use crate::test_harness::harness_with;
use crate::{Services, SlideApp};
/// 8×8 red PNG.
@@ -17,117 +21,145 @@ fn png() -> Vec<u8> {
]
}
fn harness(app: SlideApp) -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
fn slides(h: &Harness<'_, SlideApp>) -> usize {
h.state().session.active().map(|d| d.doc.slides.len()).unwrap_or(0)
}
#[test]
fn insert_ribbon_opens_the_dialog_without_editing() {
// P3(dialogs-w13): sh.A2
let mut app = SlideApp::new_base(Session::with_new(), Services::default());
app.ui.tab = "Insert".into();
let mut h = harness(app);
h.get_by_label("Photo Album…").click();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("photoAlbum"));
assert_eq!(slides(&h), 1);
assert!(h.state().session.active().unwrap().history.undo.is_empty());
}
#[test]
fn create_inserts_the_album_in_one_step() {
let bytes = png();
let services = Services {
pick_open: Some(Box::new(|_| Some("/tmp/cat.png".into()))),
read: Some(Box::new(move |_| Ok(bytes.clone()))),
..Default::default()
};
// P3(dialogs-w13): sh.A2
let mut app = SlideApp::new_base(Session::with_new(), services);
app.run("insert.photoAlbum", json!({})).expect("open");
let mut h = harness(app);
h.get_by_label("Add Pictures…").click();
h.run_steps(2);
assert!(h.query_by_label("cat.png").is_some(), "the chosen file is listed");
h.get_by_label("New Text Box").click();
h.run_steps(2);
assert!(h.query_by_label("Text: Text Box").is_some());
h.get_by_label("Create").click();
h.run_steps(4);
assert!(h.state().dialog.is_none(), "Create closes the dialog");
assert_eq!(slides(&h), 3);
let st = h.state().session.active().unwrap();
assert_eq!(st.history.undo.len(), 1);
assert_eq!(st.history.undo[0].label, "Photo Album…");
let pics: Vec<_> = st.doc.slides[1].shapes.iter().filter(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).collect();
assert_eq!(pics.len(), 1);
assert_eq!(pics[0].line.as_ref().and_then(|l| l.width), Some(1.5));
let text: Vec<_> = st.doc.slides[2].shapes.iter().filter(|sh| sh.text_box).filter_map(|sh| sh.text.as_ref().map(|t| t.text())).collect();
assert_eq!(text, ["Text Box"]);
}
/// Updating photo-album data reflows the already-open album without requiring it to be
/// reopened.
#[test]
fn update_reflows_the_open_album() {
let data = deckcraft_engine::cmd::base64_encode(&png());
// P3(dialogs-w13): sh.A2
let mut app = SlideApp::new_base(Session::with_new(), Services::default());
app.run("insert.photoAlbum", json!({"pictures": [{"name": "hill.png", "data": data}, {"name": "lake.png", "data": data}], "layout": "1"}))
.expect("create");
assert_eq!(slides_of(&app), 3);
app.run("insert.photoAlbumEdit", json!({})).expect("edit");
let mut h = harness(app);
assert!(h.query_by_label("hill.png").is_some(), "the album's pictures are listed");
assert!(h.query_by_label("Update").is_some());
h.get_by_label("ALL pictures black and white").click();
h.run_steps(2);
let layout = h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Picture layout");
assert_eq!(layout.value().as_deref(), Some("1 picture"));
layout.click();
h.run_steps(2);
h.get_by_label("2 pictures").click();
h.run_steps(2);
h.get_by_label("Update").click();
h.run_steps(4);
assert!(h.state().dialog.is_none(), "Update closes the dialog");
assert_eq!(slides(&h), 2);
let st = h.state().session.active().unwrap();
assert_eq!(st.history.undo.last().map(|u| u.label.as_str()), Some("Edit Photo Album…"));
let pics: Vec<_> = st.doc.slides[1].shapes.iter().filter(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).collect();
assert_eq!(pics.len(), 2);
match &pics[0].kind {
ShapeKind::Picture { fill } => assert!(fill.adjust.grayscale),
_ => panic!("picture"),
}
}
fn slides_of(app: &SlideApp) -> usize {
app.session.active().map(|d| d.doc.slides.len()).unwrap_or(0)
}
fn fields(h: &Harness<'_, SlideApp>) -> Value {
super::inspect(&h.ctx).as_array().unwrap().iter().find(|dialog| dialog["key"] == "photoAlbum").unwrap()["fields"].clone()
}
fn control(h: &mut Harness<'_, SlideApp>, method: &str, params: Value) {
let ctx = h.ctx.clone();
super::control(h.state_mut(), &ctx, method, &params).unwrap().unwrap();
}
#[test]
fn create_with_nothing_keeps_the_dialog() {
// P3(dialogs-w13): sh.A2
let mut app = SlideApp::new_base(Session::with_new(), Services::default());
app.run("insert.photoAlbum", json!({})).expect("open");
let mut h = harness(app);
h.get_by_label("Create").click();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("photoAlbum"));
assert_eq!(slides(&h), 1);
let status = h.state().status.as_ref().map(|s| s.0.as_str()).unwrap_or("");
assert!(status.contains("picture") || status.contains("text"), "{status}");
fn create_inserts_the_album_in_one_step() {
let path = "/tmp/cat.png";
let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![path.into()])]).with_file(path, png()));
let mut h = harness_with(
Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0),
|p| p.host = p.host.with_files(files.clone()),
);
// egui Context::run_ui reruns after request_discard and gives events only to the first pass.
h.ctx.on_end_pass(
"album second pass",
Arc::new(|ui| {
let ctx = ui.ctx();
if ctx.current_pass_index() == 0 {
ctx.request_discard("exercise the album action and answer pump twice in one frame");
}
}),
);
let before = slides(&h);
let undo_before = h.state().session.active().unwrap().history.undo.len();
h.state_mut().run("insert.photoAlbum", json!({})).expect("open");
h.run_steps(3);
h.get_by_label("Add Pictures…").click();
h.run_steps(3);
assert_eq!(files.requests(), [PickRequest::open_many("picture")]);
let mut items = fields(&h)["items"].as_array().unwrap().clone();
assert_eq!(items.len(), 1);
assert_eq!(items[0]["data"], deckcraft_engine::cmd::base64_encode(&png()));
let text = "Text Box";
items.push(json!({"text": text}));
control(&mut h, "ui.dialog.set", json!({"dialog": "top", "field": "items", "value": items}));
control(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
h.run_steps(4);
assert!(super::open_keys(&h.ctx).is_empty());
assert_eq!(slides(&h), before + items.len());
let st = h.state().session.active().unwrap();
assert_eq!(st.history.undo.len(), undo_before + 1);
let pics: Vec<_> = st.doc.slides[before].shapes.iter().filter(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).collect();
assert_eq!(pics.len(), 1);
assert_eq!(pics[0].line.as_ref().and_then(|l| l.width), Some(1.5));
let texts: Vec<_> = st.doc.slides[before + 1]
.shapes
.iter()
.filter(|sh| sh.text_box)
.filter_map(|sh| sh.text.as_ref().map(|t| t.text()))
.collect();
assert_eq!(texts, [text]);
}
#[test]
fn update_reflows_the_open_album() {
let data = deckcraft_engine::cmd::base64_encode(&png());
let pictures = json!([{"name": "hill.png", "data": data}, {"name": "lake.png", "data": data}]);
let mut h = harness_with(
Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0),
|_| {},
);
let before = slides_of(h.state());
h.state_mut().run("insert.photoAlbum", json!({"pictures": pictures, "layout": "1"})).expect("create");
let expanded = slides(&h);
let undo_before = h.state().session.active().unwrap().history.undo.len();
h.state_mut().run("insert.photoAlbumEdit", json!({})).expect("edit");
h.run_steps(3);
let seed = fields(&h);
assert_eq!(seed["items"].as_array().unwrap().len(), pictures.as_array().unwrap().len());
for (item, original) in seed["items"].as_array().unwrap().iter().zip(pictures.as_array().unwrap()) {
assert_eq!(item["name"], original["name"]);
assert_eq!(item["data"], original["data"]);
}
control(
&mut h,
"ui.dialog.set",
json!({"dialog": "top", "fields": [
{"field": "grayscale", "value": true}, {"field": "layout", "value": "2"},
]}),
);
control(&mut h, "ui.dialog.confirm", json!({"dialog": "top"}));
h.run_steps(4);
assert!(super::open_keys(&h.ctx).is_empty());
assert!(slides(&h) < expanded);
assert_eq!(slides(&h), before + 1);
let st = h.state().session.active().unwrap();
assert_eq!(st.history.undo.len(), undo_before + 1);
let pics: Vec<_> = st.doc.slides[before].shapes.iter().filter(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).collect();
assert_eq!(pics.len(), pictures.as_array().unwrap().len());
match &pics[0].kind {
ShapeKind::Picture { fill, .. } => assert!(fill.adjust.grayscale),
_ => panic!("picture"),
}
h.state_mut().run("edit.undo", json!({})).expect("undo the reflow");
assert_eq!(slides(&h), expanded, "the last undo restores the original album");
}
#[test]
fn a_pick_left_open_by_a_closed_album_does_not_reach_the_next_album() {
for queued_before_cancel in [false, true] {
let files = Arc::new(ScriptedFiles::held());
let mut h = harness_with(
Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_step_dt(1.0 / 60.0),
|p| p.host = p.host.with_files(files.clone()),
);
h.state_mut().open_dialog("photoAlbum", json!({}));
h.run_steps(3);
h.get_by_label("Add Pictures…").click();
h.run_steps(2);
let answer = Picked::Contents(vec![("stale.png".into(), png())]);
if queued_before_cancel {
files.answer(answer.clone());
}
control(&mut h, "ui.dialog.cancel", json!({"dialog": "top"}));
h.run_steps(3);
assert!(files.answer(answer).is_none(), "closing the album forgets its outstanding picker");
let requests = files.requests();
h.state_mut().open_dialog("photoAlbum", json!({}));
h.run_steps(3);
assert!(fields(&h)["items"].as_array().unwrap().is_empty());
assert_eq!(files.requests(), requests, "reopening an album does not ask for another file");
}
}
+78 -101
View File
@@ -1,113 +1,90 @@
use super::{Color32, CornerRadius, Dialog, SchemeSlot, Sense, SlideApp, Stroke, Tokens, Ui, Value, buttons, json, theme, vec2};
use craft::behavior::ColumnWidth;
use craft::theme::{Rgba, Srgba};
use craft::ui::choice::Swatch;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::DialogHost;
use craft::ui::display::Text;
use craft::ui::layout::GridFit;
use craft::ui::layout_components::{Grid, Row};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult};
use craft::ui::runtime::env::Label;
use craft::ui::text::TextField;
use deckcraft_color::SchemeSlot;
use serde_json::{Value, json};
fn seed_theme_colors(d: &mut Dialog) {
if d.fields.contains_key("seeded") {
return;
}
let name = d.params.get("name").and_then(Value::as_str).unwrap_or("Custom");
d.fields.insert("schemeName".into(), name.to_string());
let obj = d.params.get("colors").and_then(Value::as_object);
use crate::SlideApp;
const COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content];
const SLOT_ROWS: [[SchemeSlot; 2]; 6] = [
[SchemeSlot::Dk1, SchemeSlot::Accent1],
[SchemeSlot::Lt1, SchemeSlot::Accent2],
[SchemeSlot::Dk2, SchemeSlot::Accent3],
[SchemeSlot::Lt2, SchemeSlot::Accent4],
[SchemeSlot::Hlink, SchemeSlot::Accent5],
[SchemeSlot::FolHlink, SchemeSlot::Accent6],
];
fn hex(rgb: deckcraft_color::Rgba) -> String {
format!("#{}", rgb.hex())
}
/// Opens the presentation's twelve theme colours as a held form.
pub(crate) fn open(_app: &SlideApp, ctx: &egui::Context, params: &Value) -> HostedParamDialog {
let mut fields = DialogFields::new();
fields.set("schemeName", params.get("name").and_then(Value::as_str).unwrap_or("Custom"));
for slot in SchemeSlot::THEME {
let hex = obj.and_then(|o| o.get(slot.xml_name())).and_then(Value::as_str).unwrap_or("000000");
d.fields.insert(slot.xml_name().into(), hex.to_string());
let raw = params.get("colors").and_then(|colors| colors.get(slot.xml_name())).and_then(Value::as_str).unwrap_or("000000");
fields.set(slot.xml_name(), hex(deckcraft_color::Rgba::from_hex(raw).unwrap_or(deckcraft_color::Rgba::BLACK)));
}
d.fields.insert("seeded".into(), "1".into());
HostedParamDialog::new(ctx, "themeColors", fields, |fields| {
let colors = Param::custom("colors", "Colors", |ui, fields, context| {
Grid::new(&COLUMNS)
.fit(GridFit::Fixed)
.show(ui, |ui, _| {
for pair in SLOT_ROWS {
for slot in pair {
Row::new().id_salt(slot.xml_name()).show(ui, |ui, _| {
let label = slot.label();
let rgb = deckcraft_color::Rgba::from_hex(fields.text(slot.xml_name()).unwrap_or("000000"))
.unwrap_or(deckcraft_color::Rgba::BLACK);
let mut rgba = Rgba([rgb.r, rgb.g, rgb.b, 255]);
Text::new(label).show(ui);
Swatch::new(label, Srgba::from(rgba)).show(ui);
let edit = TextField::hex(format!("{label} hex"), Bind::bound(&mut rgba)).show(ui);
context.unparsed(edit.unparsed);
if edit.value().is_some() {
let [r, g, b, _] = rgba.0;
fields.set(slot.xml_name(), hex(deckcraft_color::Rgba::rgb(r, g, b)));
}
});
}
}
})
.output
})
.companions(SchemeSlot::THEME.map(|slot| slot.xml_name()))
.full_width();
ParamDialog::new("themeColors", "Create New Theme Colors", vec![colors, Param::new("schemeName", "Name", ParamKind::text("Custom"))])
.values(Bind::bound(fields))
.layout(ParamLayout::Document)
.caption_column(true)
.ok_label(Label::from("Save"))
.footer_note("Applies to this presentation's theme colours.")
})
.held_ok()
}
/// Draw one theme-colour row with its hex editor and store the value for the scheme slot.
fn theme_color_row(ui: &mut Ui, d: &mut Dialog, slot: SchemeSlot) {
let key = slot.xml_name();
let mut v = d.get(key, "000000");
ui.horizontal(|ui| {
ui.add_sized(vec2(188.0, 18.0), egui::Label::new(slot.label()));
let fill = deckcraft_color::Rgba::from_hex(&v).map(theme::to_color32).unwrap_or_else(|| Color32::from_gray(200));
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());
ui.painter().rect(rect, CornerRadius::same(2), fill, Stroke::new(1.0, Tokens::get(ui.ctx()).border), egui::StrokeKind::Inside);
let resp = ui.add(egui::TextEdit::singleline(&mut v).desired_width(84.0).id_salt(("theme-hex", key)));
let shown = v.clone();
resp.widget_info(move || {
let mut info = egui::WidgetInfo::labeled(egui::Role::TextInput, true, format!("{} hex", slot.label()));
info.current_text_value = Some(shown.clone());
info
});
});
d.fields.insert(key.into(), v);
}
fn theme_color_payload(d: &mut Dialog) -> Result<Value, String> {
let name = d.get("schemeName", "").trim().to_string();
/// Applies a named colour scheme in one engine command.
pub(crate) fn finish(app: &mut SlideApp, result: &ParamResult, _host: &mut DialogHost) -> Result<(), String> {
let name = result.fields.text("schemeName").unwrap_or_default().trim();
if name.is_empty() {
return Err("Enter a scheme name.".into());
}
let mut colors = serde_json::Map::new();
for slot in SchemeSlot::THEME {
let raw = d.get(slot.xml_name(), "");
let Some(rgb) = deckcraft_color::Rgba::from_hex(raw.trim()) else {
return Err(format!("{} needs a colour like #RRGGBB.", slot.label()));
};
colors.insert(slot.xml_name().into(), Value::String(format!("#{}", rgb.hex())));
let raw = result.fields.text(slot.xml_name()).unwrap_or_default();
let rgb = deckcraft_color::Rgba::from_hex(raw).ok_or_else(|| "Not a hex color".to_string())?;
colors.insert(slot.xml_name().into(), json!(hex(rgb)));
}
Ok(json!({"name": name, "colors": colors}))
}
/// Create New Theme Colors. Returns true when the dialog should close.
pub(super) fn theme_colors_dialog(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
seed_theme_colors(d);
// The window keeps the height of its contents and will not grow after the first frame, so the
// rows stay short enough that Save is inside that rect.
ui.style_mut().spacing.interact_size.y = 16.0;
ui.style_mut().spacing.item_spacing.y = 2.0;
ui.style_mut().spacing.button_padding.y = 2.0;
let left = [SchemeSlot::Dk1, SchemeSlot::Lt1, SchemeSlot::Dk2, SchemeSlot::Lt2, SchemeSlot::Hlink, SchemeSlot::FolHlink];
let right = [SchemeSlot::Accent1, SchemeSlot::Accent2, SchemeSlot::Accent3, SchemeSlot::Accent4, SchemeSlot::Accent5, SchemeSlot::Accent6];
egui::Grid::new("theme-colors").spacing(vec2(18.0, 4.0)).show(ui, |ui| {
for (a, b) in left.into_iter().zip(right) {
theme_color_row(ui, d, a);
theme_color_row(ui, d, b);
ui.end_row();
}
});
ui.add_space(6.0);
let mut name = d.get("schemeName", "");
ui.horizontal(|ui| {
ui.label("Name:");
let resp = ui.add(egui::TextEdit::singleline(&mut name).desired_width(280.0).id_salt("schemeName"));
let shown = name.clone();
resp.widget_info(move || {
let mut info = egui::WidgetInfo::labeled(egui::Role::TextInput, true, "Scheme name");
info.current_text_value = Some(shown.clone());
info
});
});
d.fields.insert("schemeName".into(), name);
ui.label(egui::RichText::new("Applies to this presentation's theme colours.").size(11.0).color(Tokens::get(ui.ctx()).text_dim));
let (ok, cancel) = buttons(ui, "Save");
if ok {
match theme_color_payload(d) {
Ok(payload) => return app.run("design.colors", payload).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-w13): 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-w13): dl.A9
pub(crate) fn finish(app: &mut crate::SlideApp, result: &ParamResult, host: &mut craft::ui::dialog::DialogHost) -> Result<(), String> {
// P3(dialogs-w13): dl.A9
let _ = host;
let _ = (app, result);
todo!("dl.A9")
app.run("design.colors", json!({"name": name, "colors": colors})).map(|_| ())
}
+37 -106
View File
@@ -1,27 +1,14 @@
//! Design › Colors › Customize Colors… opens Create New Theme Colors and saves in one step.
//! Saving from the Design ribbon preserves every unedited theme slot in one undo step.
use deckcraft_color::SchemeSlot;
use deckcraft_engine::Session;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use crate::test_harness::harness_with;
use crate::{Services, SlideApp};
fn harness() -> Harness<'static, SlideApp> {
// P3(dialogs-w13): sh.A2
let mut app = SlideApp::new_base(Session::with_new(), Services::default());
app.ui.tab = "Design".into();
let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
fn scheme(h: &Harness<'_, SlideApp>) -> deckcraft_color::ColorScheme {
h.state().session.active().unwrap().doc.masters[0].theme.colors.clone()
}
@@ -35,103 +22,47 @@ fn open_dialog(h: &mut Harness<'_, SlideApp>) {
h.run_steps(2);
h.get_by_label("Customize Colors…").click();
h.run_steps(3);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("themeColors"));
}
#[test]
fn customize_colors_opens_from_the_design_tab() {
let mut h = harness();
let before = scheme(&h);
let n = undo_len(&h);
open_dialog(&mut h);
assert_eq!(h.get_by_label("Scheme name").value().as_deref(), Some(before.name.as_str()));
let accent = format!("#{}", before.get(SchemeSlot::Accent1).hex());
assert_eq!(h.get_by_label("Accent 1 hex").value().as_deref(), Some(accent.as_str()));
let _ = h.get_by_label("Text/Background - Dark 1 hex");
let _ = h.get_by_label("Text/Background - Light 1 hex");
let _ = h.get_by_label("Followed Hyperlink hex");
let _ = h.get_by_label("Hyperlink hex");
let _ = h.get_by_label("Save");
let _ = h.get_by_label("Cancel");
let save = h.get_by_label("Save").rect();
let win = h.get_by_label("Create New Theme Colors").rect();
assert!(win.contains(save.center()), "Save {save:?} is outside the dialog window {win:?}");
h.get_by_label("Save").click();
h.run_steps(2);
assert!(h.state().dialog.is_none());
assert_eq!(scheme(&h), before);
assert_eq!(undo_len(&h), n, "saving the current colours is not an undo step");
assert!(super::open_keys(&h.ctx).iter().any(|key| key == "themeColors"));
}
#[test]
fn save_applies_the_name_and_one_colour() {
let mut h = harness();
// PLAN: plan error: writer note 9 removes the local harness helper retained by the Files table.
let mut h = harness_with(
Session::with_new(),
Services::default(),
Harness::builder().with_size(egui::vec2(1800.0, 1100.0)),
|_| {},
);
h.state_mut().ui.tab = "Design".into();
h.run_steps(3);
let before = scheme(&h);
let n = undo_len(&h);
open_dialog(&mut h);
{
let d = h.state_mut().dialog.as_mut().unwrap();
d.fields.insert("schemeName".into(), "Talk".into());
d.fields.insert("accent1".into(), "#ABCDEF".into());
}
h.get_by_label("Save").click();
h.run_steps(2);
assert!(h.state().dialog.is_none(), "status: {:?}", h.state().status);
let ctx = h.ctx.clone();
let name = format!("{} custom", before.name);
let color = deckcraft_color::Rgba::rgb(0xAB, 0xCD, 0xEF);
super::control(
h.state_mut(),
&ctx,
"ui.dialog.set",
&json!({"dialog": "top", "fields": [
{"field": "schemeName", "value": name},
{"field": "accent1", "value": format!("#{}", color.hex())},
]}),
)
.unwrap()
.unwrap();
super::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap();
h.run_steps(4);
assert!(super::open_keys(&ctx).is_empty());
let after = scheme(&h);
assert_eq!(after.name, "Talk");
assert_eq!(after.get(SchemeSlot::Accent1).hex(), "ABCDEF");
assert_eq!(after.get(SchemeSlot::Dk1), before.get(SchemeSlot::Dk1));
assert_eq!(undo_len(&h), n + 1);
assert_eq!(h.state().session.active().unwrap().history.undo.last().unwrap().label, "Colors");
}
#[test]
fn a_bad_hex_keeps_the_dialog_open() {
let mut h = harness();
let before = scheme(&h);
let n = undo_len(&h);
open_dialog(&mut h);
h.state_mut().dialog.as_mut().unwrap().fields.insert("accent1".into(), "zzzzzz".into());
h.get_by_label("Save").click();
h.run_steps(2);
assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("themeColors"));
assert_eq!(scheme(&h), before);
assert_eq!(undo_len(&h), n);
let status = h.state().status.as_ref().map(|(t, _)| t.clone()).unwrap_or_default();
assert!(status.contains("Accent 1"), "{status}");
}
#[test]
fn cancel_closes_without_editing() {
let mut h = harness();
let before = scheme(&h);
let n = undo_len(&h);
open_dialog(&mut h);
h.state_mut().dialog.as_mut().unwrap().fields.insert("accent1".into(), "#112233".into());
h.get_by_label("Cancel").click();
h.run_steps(2);
assert!(h.state().dialog.is_none());
assert_eq!(scheme(&h), before);
assert_eq!(undo_len(&h), n);
}
#[test]
fn typing_a_hex_replaces_accent_1() {
let mut h = harness();
let n = undo_len(&h);
open_dialog(&mut h);
h.get_by_label("Accent 1 hex").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
h.get_by_label("Accent 1 hex").type_text("#11AA22");
h.run_steps(1);
let shown = h.get_by_label("Accent 1 hex").value().unwrap_or_default();
assert_eq!(shown, "#11AA22", "the hex field should replace its text, got {shown}");
h.get_by_label("Save").click();
h.run_steps(2);
assert!(h.state().dialog.is_none(), "status: {:?}", h.state().status);
assert_eq!(scheme(&h).name, "DeckCraft");
assert_eq!(scheme(&h).get(SchemeSlot::Accent1).hex(), "11AA22");
assert_eq!(after.name, name);
assert_eq!(after.get(SchemeSlot::Accent1), color);
for slot in SchemeSlot::THEME {
if slot != SchemeSlot::Accent1 {
assert_eq!(after.get(slot), before.get(slot));
}
}
assert_eq!(undo_len(&h), n + 1);
}