mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-10 12:29:58 -06:00
* UI: RefEdit reference boxes in dialogs; Goal Seek picks its cells on the grid A reference box (RefEdit) is a text field that takes a range by selection on the grid. While a box is the one being picked into (it was clicked into or collapsed), clicking or dragging on the sheet writes the absolute reference into it, with the sheet name when the selection is on another sheet; typing still edits it, and the box takes the keyboard back after a pick. Focusing another text field of the dialog ends picking. The collapse button beside each box shrinks the dialog to that box, at the dialog's top-left corner, so the sheet is free for selecting. Escape, Enter or the expand button restore the dialog. The sheet and selection from before picking are restored before the dialog runs its command (references without a sheet name mean the sheet the dialog was opened on) and when it closes. The button is focusable, works with Space and Enter, and is named for screen readers; the icons are drawn in code. Goal Seek's Set cell and By changing cell are reference boxes. The snapshot example's --refedit key=range collapses the open dialog to a box and selects a range, to render the collapsed state. * UI: Solver and Data Analysis take their ranges with RefEdit boxes Form dialogs gain a Ref field, drawn as a reference box with its collapse button. Data Analysis uses it for the input, variable, X and Y and bin ranges, and for Output Range, where picking or typing a reference also chooses that output option. Solver Parameters uses reference boxes for the objective, the variable cells and both sides of a new constraint. * UI: Data Analysis keeps New Worksheet Ply when chosen after picking an Output Range The Output Range box chose its option on every frame while it was the box being picked into, so clicking New Worksheet Ply after using the box reverted to Output Range on the next frame. The box now chooses Output Range only when it is clicked into or its text changes (typed or picked), and choosing another output option ends picking into it, so a later selection on the grid doesn't fill it either. * UI: RefEdit boxes remember the dialog's sheet by name The sheet a dialog was opened on was kept by index, so a sheet inserted or moved while picking (the ribbon stays usable) made a range on the new sheet lose its sheet name, and closing the dialog went back to whichever sheet now had that index. The sheet is now kept by name, as New Formatting Rule's formula box does. * UI: switching sheets while picking into a RefEdit box doesn't fill it A reference on another sheet carries the sheet name, so after a click on another sheet tab the selection never matched the one last seen, and the switch alone wrote that sheet's remembered selection into the box, replacing a typed reference. The box now notes which sheet its last seen selection was on: showing another sheet only refreshes it, and a selection made on that sheet still fills the box. * UI: a RefEdit box for one reference takes only the area being selected A selection of several areas (Ctrl+click) was written into every box as a comma-joined union, which Goal Seek, Solver's objective and constraints, and Data Analysis then refused as an invalid reference. Solver's variable cells still take every area; the other boxes take the area being selected. * UI: RefEdit boxes follow the dialog's sheet when it is renamed The dialog's own sheet was kept by name only, so renaming it while a reference box picked made references on it carry the new name as if it were another sheet, and running or closing the dialog could not put the selection back. The sheet's index and the sheet count are now kept with the name: when the name disappears while the count stays the same, the sheet at that index was renamed and its new name is taken. Inserting, moving or deleting other sheets still follows the name. * UI: a deleted dialog sheet is never taken for another sheet The dialog's own sheet was taken as renamed whenever its name was gone and the sheet count matched the last frame's, so deleting it was read as a rename a frame later (or after a sheet was inserted), and the surviving sheet at that index became the dialog's sheet: unqualified references ran against it and Cancel put the old selection on it. The sheet names of the last frame are now kept in order. A rename is taken only when the list keeps its length and only the home sheet's entry changed; any other loss of the name marks the sheet as deleted for good. Once it is deleted, picks carry their sheet's name, closing leaves the selection where it is, and OK is refused with a message, since references without a sheet name would otherwise run against whichever sheet is shown. * UI: RefEdit dialogs keep their sheet until they close OK put the saved selection back and dropped the dialog's sheet with it. When the command then failed, the dialog stayed open without its sheet: a later deletion of that sheet went unnoticed and a second OK ran references without a sheet name against the sheet shown, as it also did when the person had only moved to another sheet after the failed OK. The sheet is now kept, and followed through renames and deletion, until the dialog closes; only the saved selection is put back once. A later OK or Cancel shows the dialog's sheet again (or is refused once it is deleted), and picking again on that sheet saves its selection anew. * UI: Solver's Model Range is a RefEdit box * UI: a collapsed RefEdit box keeps picking when something else is clicked * UI: a dialog opened over a picking RefEdit dialog puts the selection back * UI: arrow keys select on the grid while a dialog is collapsed to a RefEdit box * UI: F4 cycles the anchors of the reference in a RefEdit box * UI: tests for Enter while collapsed and OK after a cross-sheet pick * Docs: RefEdit boxes' keyboard route, Model Range and click-elsewhere behaviour * UI: a confirmed RefEdit dialog stays on the sheet its command showed * UI: scripted dialog cancel and confirm end a RefEdit pick like the buttons * UI: RefEdit boxes run their selection and sheet commands through the app * Docs: RefEdit dialogs after OK, scripted cancel and confirm * UI: a RefEdit dialog's OK stops when the picked sheet's draft cannot be saved * Docs: ui.dialog.confirm applies to command-backed dialogs; a draft that cannot be saved stops OK * UI: Cancel of a RefEdit dialog is never a confirmation, and says when it cannot go home * Docs: cancelling a RefEdit dialog when its sheet cannot be shown again * UI: a RefEdit dialog follows its sheet's rename only through the engine's recorded steps * UI: F4 in a RefEdit box splits areas only at commas outside quoted sheet names * Docs: how a RefEdit dialog follows its sheet's rename * UI: a RefEdit dialog's sheet is told from a new sheet given its name The dialog followed its sheet by name and read the recorded steps only once the name was gone, so a sheet deleted and recreated under its own name between two frames was taken for the dialog's sheet, and OK resolved unqualified references against the replacement. The home sheet is now followed through every recorded step since the dialog last looked: a sheet with its name is the same sheet only while its file id is unchanged (a sheet inserted in the session has none), a rename keeps the file id and the cells, and a deleted sheet is remembered as it was, so only an undo that brings that very sheet back revives it. When the steps are not accounted for, a sheet with the name is taken for it, as before. A sheet never saved to a file and replaced inside one undo group is the one case nothing in the model tells apart; the code comment says so. * Docs: how a RefEdit dialog tells its sheet from a new sheet given its name * UI: a RefEdit dialog follows a sheet that came from a file by its file id A sheet read from a file keeps the file's sheetId, which no step changes and which a sheet inserted in the session lacks, so the dialog's sheet is found by it wherever a recorded step puts it and whatever the step renames it to: a group that renames the sheet and inserts a new one under its old name follows the rename instead of refusing OK. When the step also copied the sheet (a copy keeps the id), the one keeping the name is taken. A sheet never saved to a file is still followed by name, with the rename rule as before. * Docs: a RefEdit dialog follows a sheet that came from a file by its file id * UI: a RefEdit box the dialog stops showing is no longer picked into A reference box compares the grid selection with the one it last saw only while it is drawn, so a box hidden while it was the one being picked into (Solver's Options view, the constraint value once the operator is int or bin) took a selection made meanwhile when it came back. After the dialog's window is drawn, a target box that was not drawn in the frame ends the pick, whatever hid it; Model Range no longer needs its own rule when the Load/Save area is hidden. * UI: the Name Box keeps its keys while a dialog is collapsed to a RefEdit box The collapsed picker took Escape, Enter and the arrow keys out of the frame's input whoever had the keyboard. The Name Box, drawn before the dialogs, had already read an arrow when the picker removed the same event and moved the grid selection, and the box then took that selection and the keyboard; its Escape expanded the dialog instead of only leaving the box. The picker now acts on those keys only when no other text field owns the keyboard, judged by the focus at the end of the frame before as well as now, since egui drops the focus for Escape before anything is drawn. The other field's Escape and Enter are still used up, so the dialog neither closes nor confirms on them. * Docs: a sentence break in the ui.dialog row of the control protocol * UI: a RefEdit dialog keeps its sheet by the sheet's identity, not by file id or history The dialog's sheet was followed by name through the recorded undo steps, with the file's sheet id telling a saved sheet from a new one; a copy made with sheet.move keeps that id, so once the original was deleted the copy, as the only sheet of the id, was taken for the dialog's sheet and OK ran against it. The model now gives every sheet an identity while the app runs (SheetUid: fresh for every sheet added, inserted, copied or read, kept through renames, moves, undo and redo), so Home keeps the sheet's uid and finds the sheet by it each time it is needed. The history walk, the rename rule and the file-id and Arc comparisons are gone, with the undetectable single-step case they left: a sheet given the name, a replacement inside one undo group and a copy are all other sheets, and an undo that brings the original back makes it the dialog's again. Nothing of the unaccounted-steps fallback is kept, since the identity always answers. Regression test: copy the dialog's sheet, delete the original, OK is refused; undo, OK runs on the original. The identity tests no longer need a workbook that came through a file. * UI: Solver's Reset All, Load, Save and Replace act on the dialog's sheet, as Solve does Only Solve went through the dialog's home-sheet checks before running (dialogs::show): Reset All, Load Model, Save Model and Replace ran their commands straight from the form, on whichever sheet was active. After a reference box picked on another sheet and the dialog expanded, that sheet was still shown, so Reset All removed its model instead of the dialog's sheet's, and Load and Save read and wrote the model range on it. The four buttons now run only after the same checks as Solve: the dialog's sheet must still exist (else the command is refused with the deleted-sheet message) and is shown again with the selection from before picking put back (a failure to show it, a text-box draft that could not be saved, is shown as the dialog's error and the command does not run). Goal Seek has no other buttons, and Data Analysis's Replace goes through the confirm path that Solve uses, so neither needed a change. Regression tests: after a cross-sheet pick, Reset All clears the dialog's sheet's model and leaves the other sheet's; Save and Replace write the dialog's sheet; Load reads it. * UI: Protect Sheet opened while a reference box picks on another sheet acts on the dialog's sheet * Docs: a scripted Goal Seek after a cross-sheet pick cancels the dialog before data.goalSeek * UI: the Protect Sheet labels follow the dialog's sheet while a reference box picks on another * Docs: a scripted Goal Seek checks that the dialog's sheet still exists after cancel * Control: ui.dialog.cancel replies sheetDeleted when the dialog's own sheet is gone, even if its name was reused * M2: allow shared-runner variance in the pathological math timing gate * M2: refuse sheet protection actions after a reference dialog home is deleted --------- Co-authored-by: FredApps <FredApps@users.noreply.github.com>
697 lines
35 KiB
Rust
697 lines
35 KiB
Rust
use super::about::about;
|
||
use super::analysis::{analysis_toolpak, cancel_solver_options, goal_seek, in_solver_options, solver, solver_results};
|
||
use super::charts::{recommended_charts, select_data};
|
||
use super::command_search::command_search;
|
||
use super::cond_format_rules::manage_rules;
|
||
use super::data::{advanced_filter_form, data_validation_form, sort};
|
||
use super::find::{find, go_to};
|
||
use super::format_cells::format_cells;
|
||
use super::insert_function::insert_function;
|
||
use super::names::{name_manager, paste_name};
|
||
use super::paste::{paste_special, paste_special_shortcuts};
|
||
use super::ref_edit::{RefLabel, SHEET_DELETED, end_pick, home_sheet_deleted, place_window, ref_edit, window_shown};
|
||
use super::spelling::spelling;
|
||
use super::zoom::zoom;
|
||
use super::{Dialog, Field, Json, Key, Map, RefPick, SheetApp, json, vec2};
|
||
use gridcraft_engine::model::PageOrder;
|
||
|
||
/// Builds the command params from form values for dialogs that need translation.
|
||
/// The parameters OK sends to the dialog's command: its field values, reshaped per dialog.
|
||
/// Unchanged hyperlink display text is omitted so its number or formula stays intact.
|
||
pub(crate) fn build_params(d: &Dialog) -> Json {
|
||
let mut v = Json::Object(d.values.clone());
|
||
match d.name.as_str() {
|
||
"insertLink" => {
|
||
if d.original_link_text.as_deref().is_some_and(|text| d.values.get("text").and_then(Json::as_str) == Some(text))
|
||
&& let Some(m) = v.as_object_mut()
|
||
{
|
||
m.remove("text");
|
||
}
|
||
}
|
||
"advancedFilter" => {
|
||
if let Some(m) = v.as_object_mut() {
|
||
m.remove("action");
|
||
if d.values.get("action").and_then(Json::as_str) != Some("copy") {
|
||
m.remove("copyTo");
|
||
}
|
||
if m.get("criteria").and_then(Json::as_str).is_some_and(|s| s.trim().is_empty()) {
|
||
m.remove("criteria");
|
||
}
|
||
}
|
||
}
|
||
"dataValidation" => {
|
||
let kind = d.values.get("type").and_then(Json::as_str).unwrap_or("any");
|
||
let operator = d.values.get("operator").and_then(Json::as_str).unwrap_or("between");
|
||
if let Some(m) = v.as_object_mut() {
|
||
if !matches!(operator, "between" | "notBetween") || matches!(kind, "any" | "list" | "custom") {
|
||
m.remove("formula2");
|
||
}
|
||
if matches!(kind, "any" | "list" | "custom") {
|
||
m.remove("operator");
|
||
}
|
||
if kind == "any" {
|
||
m.remove("formula1");
|
||
}
|
||
if kind != "list" {
|
||
m.remove("dropdown");
|
||
}
|
||
}
|
||
}
|
||
"textToColumns" => {
|
||
let mut delims = Vec::new();
|
||
for (k, c) in [("tab", "\t"), ("semicolon", ";"), ("comma", ","), ("space", " ")] {
|
||
if d.values.get(k).and_then(Json::as_bool) == Some(true) {
|
||
delims.push(json!(c));
|
||
}
|
||
}
|
||
v["delimiters"] = Json::Array(delims);
|
||
}
|
||
"removeDuplicates" | "subtotal" => {
|
||
if let Some(t) = d.values.get("columnsText").and_then(Json::as_str).filter(|t| !t.trim().is_empty()) {
|
||
v["columns"] = Json::Array(t.split(',').map(|c| json!(c.trim().to_ascii_uppercase())).collect());
|
||
}
|
||
}
|
||
"allowEditRanges" => {
|
||
if let Some(m) = v.as_object_mut() {
|
||
// Blank fields mean "unchanged"; the check box clears a password.
|
||
m.retain(|_, x| x.as_str().is_none_or(|s| !s.trim().is_empty()));
|
||
if m.remove("removePassword").and_then(|x| x.as_bool()) == Some(true) {
|
||
m.insert("password".into(), json!(""));
|
||
}
|
||
}
|
||
}
|
||
"cfQuick" => {
|
||
let mut rule = Map::new();
|
||
for (k, val) in &d.values {
|
||
rule.insert(k.clone(), val.clone());
|
||
}
|
||
v = json!({"rule": Json::Object(rule)});
|
||
if let Some(pick) = d.pick.as_ref().filter(|pick| !pick.applies_to.is_empty() && !pick.sheet.is_empty()) {
|
||
v["sheet"] = json!(pick.sheet.as_str());
|
||
v["range"] = json!(pick.applies_to);
|
||
}
|
||
}
|
||
"series" => {
|
||
if let Some(s) = d.values.get("stop").and_then(Json::as_str).and_then(|s| s.parse::<f64>().ok()) {
|
||
v["stop"] = json!(s);
|
||
} else if let Some(m) = v.as_object_mut() {
|
||
m.remove("stop");
|
||
}
|
||
}
|
||
"defineName" => {
|
||
if let Some(m) = v.as_object_mut() {
|
||
for key in ["scope", "oldScope"] {
|
||
if m.get(key).and_then(Json::as_str) == Some("Workbook") {
|
||
m.remove(key);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
"pageSetup" => {
|
||
// A margin dragged below zero is zero, as the Margins command makes it (Page Setup
|
||
// refuses negative margins from other callers).
|
||
for key in ["left", "right", "top", "bottom", "header", "footer"] {
|
||
if let Some(inches) = d.values.get(key).and_then(Json::as_f64) {
|
||
v[key] = json!(inches.max(0.0));
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
v
|
||
}
|
||
|
||
/// Takes and draws the active dialog, dispatches its body by name, consumes picture-inbox results, runs OK/confirm commands, handles Esc/close and restores the back-dialog stack.
|
||
pub fn show(app: &mut SheetApp, ctx: &egui::Context) {
|
||
let Some(mut d) = app.dialog.take() else { return };
|
||
let home = app.ui_window();
|
||
// The macro step editor is a large resizable window of its own.
|
||
if d.name == "macroEditor" {
|
||
let mut open = true;
|
||
crate::macro_editor::window(app, ctx, &mut d, &mut open);
|
||
if !open {
|
||
app.macros.editor = None;
|
||
app.grid.macro_overlay = None;
|
||
} else if app.ui_window() != home {
|
||
// Something run from the editor switched windows: the editor stays in its own.
|
||
app.return_dialog(home, d);
|
||
} else {
|
||
app.dialog = Some(d);
|
||
}
|
||
return;
|
||
}
|
||
if d.name == "pasteSpecial" {
|
||
paste_special_shortcuts(&mut d, ctx);
|
||
}
|
||
let mut open = true;
|
||
let mut win_open = true;
|
||
let mut confirm = false;
|
||
let width = match d.name.as_str() {
|
||
"formatCells" => 560.0,
|
||
"about" => 660.0,
|
||
"insertFunction" | "commandSearch" | "nameManager" | "manageRules" | "journal" | "agents" | "equation" => 520.0,
|
||
"macros" => 480.0,
|
||
"recommendedCharts" => 600.0,
|
||
"analysisToolPak" => 420.0,
|
||
"solver" => 460.0,
|
||
"zoom" => 220.0,
|
||
"pasteSpecial" => 480.0,
|
||
_ => 380.0,
|
||
};
|
||
let window_id = egui::Id::unique("dialog").with(&d.name);
|
||
let window = egui::Window::new(app.ui.language.tr(&d.title))
|
||
.id(window_id)
|
||
.collapsible(false)
|
||
.resizable(false)
|
||
.default_width(width)
|
||
// A default position, not an anchor: egui anchors can't be dragged, and dialogs move by their title bar.
|
||
.pivot(egui::Align2::CENTER_CENTER)
|
||
.default_pos(ctx.content_rect().center() + vec2(0.0, -40.0))
|
||
.open(&mut win_open);
|
||
let window = match d.name.as_str() {
|
||
"insertPicture" => window.default_height(240.0),
|
||
"advancedFilter" => window.default_height(0.0),
|
||
_ => window,
|
||
};
|
||
let (window, collapsed) = place_window(app, ctx, &mut d, window, window_id);
|
||
let shown = window.show(ctx, |ui| {
|
||
if let Some(key) = &collapsed {
|
||
let title = d.title.clone();
|
||
ref_edit(app, ui, &mut d, key, RefLabel::Named(&title), (width - 40.0).min(380.0));
|
||
return;
|
||
}
|
||
ui.set_min_width(width - 20.0);
|
||
match d.name.as_str() {
|
||
"formatCells" => format_cells(app, ui, &mut d, &mut confirm),
|
||
"dataValidation" => data_validation_form(app, ui, &mut d, &mut confirm, &mut open),
|
||
"advancedFilter" => advanced_filter_form(app, ui, &mut d, &mut confirm, &mut open),
|
||
"insertFunction" => insert_function(app, ui, &mut d, &mut confirm),
|
||
"find" => find(app, ui, &mut d),
|
||
"goTo" => go_to(app, ui, &mut d, &mut confirm),
|
||
"zoom" => zoom(ui, &mut d, &mut confirm, &mut open),
|
||
"sort" => sort(app, ui, &mut d, &mut confirm),
|
||
"nameManager" => name_manager(app, ui, &mut d, &mut open),
|
||
"pasteName" => paste_name(app, ui, &mut d, &mut confirm, &mut open),
|
||
"manageRules" => manage_rules(app, ui),
|
||
"recommendedCharts" => recommended_charts(app, ui, &mut d, &mut confirm, &mut open),
|
||
"selectData" => select_data(app, ui, &mut d, &mut confirm, &mut open),
|
||
"commandSearch" => command_search(app, ui, &mut d, &mut confirm),
|
||
"goalSeek" => goal_seek(app, ui, &mut d, &mut confirm, &mut open),
|
||
"equation" => crate::equation::editor(app, ui, &mut d, &mut confirm, &mut open),
|
||
"pasteSpecial" => paste_special(app, ui, &mut d, &mut confirm, &mut open),
|
||
"analysisToolPak" => analysis_toolpak(app, ui, &mut d, &mut confirm, &mut open),
|
||
"solver" => solver(app, ui, &mut d, &mut confirm, &mut open),
|
||
"solverResults" => solver_results(app, ui, &mut d, &mut open),
|
||
"spelling" => spelling(app, ui, &mut d, &mut open),
|
||
"agents" => {
|
||
ui.label("GridCraft is fully drivable by agents. Every menu item, button and gesture is a command:");
|
||
ui.add_space(4.0);
|
||
ui.monospace("gridcraft --control 7979 # JSON-lines control channel\ngridcraft-cli mcp --connect 7979 # MCP bridged to this window\ngridcraft-cli mcp # headless MCP server");
|
||
ui.add_space(4.0);
|
||
ui.label(format!("{} engine commands are available. See docs/mcp.md and docs/control-protocol.md.", gridcraft_engine::command_specs().len()));
|
||
}
|
||
"about" => about(ui, &mut d),
|
||
"journal" => {
|
||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||
for (id, p) in app.session.journal.iter().rev().take(500) {
|
||
ui.monospace(format!("{id} {p}"));
|
||
}
|
||
});
|
||
}
|
||
"macros" => crate::macro_ui::macros_dialog(app, ui, &mut d, &mut open),
|
||
"recordMacro" => crate::macro_ui::record_dialog(app, ui, &mut d, &mut open),
|
||
"statistics" | "accessibility" | "errorChecking" | "evaluateFormula" | "comments" => {
|
||
let r = if d.name == "comments" {
|
||
app.session.active().and_then(|doc| doc.wb.active().map(|s| json!(s.comments.iter().map(|(c, m)| json!({"cell": c.a1(), "author": m.author, "text": m.text})).collect::<Vec<_>>())))
|
||
} else {
|
||
d.result.clone()
|
||
};
|
||
egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
|
||
ui.monospace(serde_json::to_string_pretty(&r.unwrap_or(Json::Null)).unwrap_or_default());
|
||
});
|
||
}
|
||
"insertPicture" => {
|
||
// A private inbox dies with this dialog; late browser results
|
||
// cannot affect a later picture choice or another workbook.
|
||
let arrived = d.picture_inbox.as_ref().and_then(|inbox| {
|
||
inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner).pop()
|
||
});
|
||
if let Some((name, bytes)) = arrived {
|
||
d.picture_inbox = None;
|
||
if bytes.len() > 16 * 1024 * 1024 {
|
||
app.message = Some((d.title.clone(), "Choose a PNG or JPEG no larger than 16 MB.".into()));
|
||
} else {
|
||
d.values.remove("path");
|
||
d.values.insert("alt".into(), json!(name));
|
||
d.values.insert("base64".into(), json!(gridcraft_engine::io::base64_encode(&bytes)));
|
||
}
|
||
}
|
||
if app.services.pick_picture_async.is_some() {
|
||
let name = d.values.get("alt").and_then(Json::as_str).unwrap_or("No picture selected");
|
||
ui.label(name);
|
||
} else {
|
||
ui.label("Picture file path (PNG or JPEG):");
|
||
let mut path = d.values.get("path").and_then(Json::as_str).unwrap_or("").to_string();
|
||
if ui.text_edit_singleline(&mut path).changed() {
|
||
d.values.remove("base64");
|
||
d.values.insert("path".into(), json!(path));
|
||
}
|
||
}
|
||
if (app.services.pick_picture.is_some() || app.services.pick_picture_async.is_some()) && ui.button("Browse…").clicked() {
|
||
if let Some(start) = &app.services.pick_picture_async {
|
||
let inbox = crate::Inbox::default();
|
||
start(inbox.clone());
|
||
d.picture_inbox = Some(inbox);
|
||
} else if let Some(pick) = &app.services.pick_picture
|
||
&& let Some(path) = pick()
|
||
{
|
||
d.values.remove("base64");
|
||
let alt = std::path::Path::new(&path).file_name().and_then(std::ffi::OsStr::to_str).unwrap_or("");
|
||
d.values.insert("alt".into(), json!(alt));
|
||
d.values.insert("path".into(), json!(path));
|
||
}
|
||
}
|
||
ui.label("Description (optional):");
|
||
let mut alt = d.values.get("alt").and_then(Json::as_str).unwrap_or("").to_string();
|
||
if ui.text_edit_singleline(&mut alt).changed() {
|
||
d.values.insert("alt".into(), json!(alt));
|
||
}
|
||
if d.values.get("placement").and_then(Json::as_str) == Some("cell") {
|
||
ui.label(egui::RichText::new("Fits inside the selected cell and moves with its content.").small());
|
||
}
|
||
ok_cancel(ui, &mut confirm, &mut open);
|
||
}
|
||
"pickList" => {
|
||
let items: Vec<String> = app
|
||
.session
|
||
.active()
|
||
.and_then(|doc| {
|
||
let sh = doc.wb.active()?;
|
||
let a = doc.selection.active;
|
||
let mut seen = std::collections::BTreeSet::new();
|
||
let mut r = a.row;
|
||
while r > 0 && !sh.value(gridcraft_engine::core::CellRef::new(r - 1, a.col)).is_empty() {
|
||
r -= 1;
|
||
seen.insert(sh.value(gridcraft_engine::core::CellRef::new(r, a.col)).display());
|
||
}
|
||
Some(seen.into_iter().collect())
|
||
})
|
||
.unwrap_or_default();
|
||
for it in items {
|
||
if ui.button(&it).clicked() {
|
||
app.run_or_alert("cell.set", json!({"input": it}));
|
||
open = false;
|
||
}
|
||
}
|
||
}
|
||
"saveCopy" => {
|
||
let fmt = d.values.get("format").and_then(Json::as_str).unwrap_or("xlsx").to_string();
|
||
ui.label(format!("Save a copy as .{fmt}"));
|
||
let mut path = d.values.get("path").and_then(Json::as_str).unwrap_or("").to_string();
|
||
ui.text_edit_singleline(&mut path);
|
||
d.values.insert("path".into(), json!(path.clone()));
|
||
ok_cancel(ui, &mut confirm, &mut open);
|
||
if confirm {
|
||
// A bare name has no folder: written as typed it would land in the
|
||
// process's working directory (`/` from the Finder, the install folder on
|
||
// Windows), never where the user looks. The picker chooses the folder.
|
||
let pick = app.services.pick_save.as_ref();
|
||
let target = if path.is_empty() {
|
||
pick.and_then(|f| f(&format!("Copy.{fmt}")))
|
||
} else if let Some(f) = pick.filter(|_| std::path::Path::new(&path).is_relative()) {
|
||
f(&if path.ends_with(&format!(".{fmt}")) { path } else { format!("{path}.{fmt}") })
|
||
} else {
|
||
Some(path)
|
||
};
|
||
if let Some(t) = target {
|
||
let id = match fmt.as_str() {
|
||
"csv" => "file.exportCsv",
|
||
"html" => "file.exportHtml",
|
||
_ => "file.saveAs",
|
||
};
|
||
app.run_or_alert(id, json!({"path": t}));
|
||
}
|
||
}
|
||
}
|
||
"saveChanges" => {
|
||
ui.label(format!("Do you want to save the changes you made to {}?", d.values.get("title").and_then(Json::as_str).unwrap_or("this workbook")));
|
||
let quitting = d.values.get("quit").and_then(Json::as_bool) == Some(true);
|
||
ui.horizontal(|ui| {
|
||
for (label, answer) in
|
||
[("Don't Save", crate::SaveAnswer::DontSave), ("Cancel", crate::SaveAnswer::Cancel), ("Save", crate::SaveAnswer::Save)]
|
||
{
|
||
if ui.button(label).clicked() && app.answer_save_changes(answer, quitting, ui.ctx()) {
|
||
open = false;
|
||
}
|
||
}
|
||
});
|
||
}
|
||
"start" => {
|
||
ui.heading("Start a new workbook");
|
||
ui.horizontal_wrapped(|ui| {
|
||
if ui.button("Blank workbook").clicked() {
|
||
app.run_or_alert("file.new", json!({}));
|
||
open = false;
|
||
}
|
||
for (n, t) in gridcraft_engine::sample::SAMPLES {
|
||
if ui.button(*t).clicked() {
|
||
app.run_or_alert("file.new", json!({"sample": n}));
|
||
open = false;
|
||
}
|
||
}
|
||
});
|
||
ui.separator();
|
||
ui.label(egui::RichText::new("Recent").strong());
|
||
for path in app.ui.recent.clone() {
|
||
if ui.link(&path).clicked() {
|
||
app.open_path(&path);
|
||
open = false;
|
||
}
|
||
}
|
||
if ui.button("Open…").clicked() {
|
||
app.open_dialog("open", json!({}));
|
||
open = false;
|
||
}
|
||
}
|
||
_ => form(app, ui, &mut d, &mut confirm, &mut open),
|
||
}
|
||
});
|
||
window_shown(ctx, &mut d, collapsed.is_some(), shown.map(|r| r.response.rect));
|
||
// Hyperlinks inside dialogs (About ▸ Contributors) open through the host's `open_url`, since
|
||
// the native shell has no browser integration of its own.
|
||
if let Some(open_url) = &app.services.open_url {
|
||
let urls: Vec<String> = ctx.output_mut(|o| {
|
||
let mut urls = vec![];
|
||
o.commands.retain(|c| match c {
|
||
egui::OutputCommand::OpenUrl(u) => {
|
||
urls.push(u.url.clone());
|
||
false
|
||
}
|
||
_ => true,
|
||
});
|
||
urls
|
||
});
|
||
for u in urls {
|
||
open_url(&u);
|
||
}
|
||
}
|
||
if ctx.input(|i| i.key_pressed(Key::Escape)) || !win_open {
|
||
// In Solver Options, Escape (or closing the window) cancels the options only.
|
||
if in_solver_options(&d) {
|
||
cancel_solver_options(&mut d);
|
||
} else {
|
||
open = false;
|
||
}
|
||
}
|
||
if confirm && d.name == "insertPicture" && d.picture_target != app.view_key() {
|
||
app.message = Some((d.title.clone(), "Return to the original worksheet to insert this picture, or cancel and choose another cell.".into()));
|
||
confirm = false;
|
||
}
|
||
if confirm && d.command.is_some() && home_sheet_deleted(app, &mut d) {
|
||
// References without a sheet name would land on whichever sheet is shown now.
|
||
app.message = Some((d.title.clone(), SHEET_DELETED.into()));
|
||
confirm = false;
|
||
}
|
||
if confirm && let Err(e) = end_pick(app, &mut d) {
|
||
// References without a sheet name mean the sheet the dialog was opened on: when it can't
|
||
// be shown again (a text-box draft on the picked sheet could not be saved), the command
|
||
// would read them against the wrong sheet, so it doesn't run and the dialog stays.
|
||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||
confirm = false;
|
||
}
|
||
if confirm && let Some(cmd) = d.command {
|
||
let params = build_params(&d);
|
||
match app.run(cmd, params) {
|
||
Ok(r) => {
|
||
open = false;
|
||
if d.name == "solver" {
|
||
app.open_dialog("solverResults", r);
|
||
} else if d.name == "openPassword" {
|
||
let path = d.values.get("path").and_then(Json::as_str).map(str::to_string);
|
||
app.after_open(path.as_deref(), &r);
|
||
}
|
||
}
|
||
// Data Analysis asks before replacing data in its output range.
|
||
Err(e) if d.name == "analysisToolPak" && e.contains(gridcraft_engine::cmd::analysis::OVERWRITE_ERROR) => {
|
||
d.values.insert("askOverwrite".into(), json!(true));
|
||
}
|
||
// A wrong password: say so, clear the field and stay open for another try.
|
||
Err(e) if d.name == "openPassword" => {
|
||
d.values.insert("password".into(), json!(""));
|
||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||
}
|
||
Err(e) => app.message = Some((d.title.clone(), crate::clean_error(&e))),
|
||
}
|
||
} else if confirm {
|
||
open = false;
|
||
}
|
||
if !open
|
||
&& !confirm
|
||
&& let Err(e) = end_pick(app, &mut d)
|
||
{
|
||
// Cancelled or closed: back to the sheet and selection from before picking. A confirmed
|
||
// OK went back before its command ran, and stays where the command left things (Data
|
||
// Analysis shows the report sheet it added). When the dialog's sheet can't be shown
|
||
// again (a text-box draft on the picked sheet could not be saved), Cancel still closes
|
||
// the dialog, since there is no command left to protect: the reason is shown, and the
|
||
// draft and the selection stay where they are for the person to deal with. A script's
|
||
// `ui.dialog.cancel` gets the error instead and keeps the dialog, so it can act on it.
|
||
app.message = Some((d.title.clone(), crate::clean_error(&e)));
|
||
}
|
||
if app.ui_window() != home {
|
||
// A command run from the dialog switched windows: whatever it opened shows in the new
|
||
// window, and this dialog (or the one it returns to) stays in its own.
|
||
let keep = if open { Some(d) } else { d.back.take().map(|b| *b) };
|
||
if let Some(keep) = keep {
|
||
app.return_dialog(home, keep);
|
||
}
|
||
return;
|
||
}
|
||
if let Some(child) = app.dialog.as_mut() {
|
||
// The body opened another dialog (Name Manager › New…). It takes over; this one waits
|
||
// behind it and comes back when it closes, as Excel returns to the Name Manager. Go To
|
||
// hands over to Go To Special for good, as in Excel.
|
||
if open && d.name != "goTo" {
|
||
child.back = Some(Box::new(d));
|
||
} else if child.back.is_none() {
|
||
child.back = d.back.take();
|
||
}
|
||
return;
|
||
}
|
||
if open {
|
||
app.dialog = Some(d);
|
||
} else if let Some(back) = d.back.take() {
|
||
app.dialog = Some(*back);
|
||
}
|
||
}
|
||
|
||
pub(super) fn ok_cancel(ui: &mut egui::Ui, confirm: &mut bool, open: &mut bool) {
|
||
ui.add_space(8.0);
|
||
// A row as tall as the buttons: a right-to-left layout straight in the window takes all the
|
||
// height it is offered, which stretched every form dialog to the screen's height.
|
||
ui.horizontal(|ui| {
|
||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||
let lang = crate::i18n::current(ui.ctx());
|
||
let t = crate::theme::Tokens::get(ui.ctx());
|
||
let ok = ui.add(egui::Button::new(egui::RichText::new(format!(" {} ", lang.tr("OK"))).color(t.on_accent)).fill(t.accent));
|
||
if ok.clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
|
||
*confirm = true;
|
||
}
|
||
if ui.button(format!(" {} ", lang.tr("Cancel"))).clicked() {
|
||
*open = false;
|
||
}
|
||
})
|
||
});
|
||
}
|
||
|
||
fn form(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) {
|
||
form_fields(app, ui, d);
|
||
ok_cancel(ui, confirm, open);
|
||
}
|
||
|
||
/// Gives keyboard focus to the first text or number field the first time a form is drawn. A
|
||
/// focused number field is in typing mode with its value selected, so Alt+H, O, W then 12 and
|
||
/// Enter sets the width, as in Excel.
|
||
/// Keeps asking until the field really has focus: a new window's first frame is an invisible
|
||
/// sizing pass where a focus request is ignored.
|
||
pub(super) fn take_first_focus(d: &mut Dialog, r: &egui::Response) {
|
||
if !d.focus_first_field {
|
||
return;
|
||
}
|
||
if !r.has_focus() {
|
||
r.request_focus();
|
||
return;
|
||
}
|
||
// Focus has landed, and the field is now a text box: select its whole value so typing
|
||
// replaces it (the field's own select-on-focus fired before it was a text box).
|
||
let mut state = egui::text_edit::TextEditState::load(&r.ctx, r.id).unwrap_or_default();
|
||
let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(usize::MAX / 2));
|
||
state.cursor.set_char_range(Some(all));
|
||
state.store(&r.ctx, r.id);
|
||
d.focus_first_field = false;
|
||
}
|
||
|
||
/// Keeps a picking formula box's caret, and gives it the keyboard back after a grid click put a
|
||
/// reference in it (the click took the focus), its caret after the reference.
|
||
fn track_pick(pick: &mut RefPick, r: &egui::Response, typed: bool) {
|
||
if typed {
|
||
pick.point = None;
|
||
}
|
||
if pick.refocus {
|
||
let mut state = egui::text_edit::TextEditState::load(&r.ctx, r.id).unwrap_or_default();
|
||
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(egui::text::CCursor::new(pick.caret))));
|
||
state.store(&r.ctx, r.id);
|
||
r.request_focus();
|
||
pick.refocus = false;
|
||
} else if r.has_focus()
|
||
&& let Some(range) = egui::text_edit::TextEditState::load(&r.ctx, r.id).and_then(|state| state.cursor.char_range())
|
||
{
|
||
pick.caret = range.primary.index.into();
|
||
}
|
||
}
|
||
|
||
/// Draws a dialog's `fields`, editing its values.
|
||
pub(super) fn form_fields(app: &SheetApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||
// Field labels, choices and notes are English source strings, translated as they are drawn.
|
||
let lang = crate::i18n::current(ui.ctx());
|
||
egui::Grid::new("form").num_columns(1).spacing(vec2(8.0, 6.0)).show(ui, |ui| {
|
||
for f in d.fields.clone() {
|
||
match f {
|
||
Field::Text { key, label } => {
|
||
ui.vertical(|ui| {
|
||
let label = ui.label(lang.tr(label));
|
||
let mut s = d
|
||
.values
|
||
.get(key)
|
||
.map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| if v.is_null() { String::new() } else { v.to_string() }))
|
||
.unwrap_or_default();
|
||
let multiline = key == "text";
|
||
let r = if multiline {
|
||
ui.add(egui::TextEdit::multiline(&mut s).desired_rows(4).desired_width(320.0)).labelled_by(label.id)
|
||
} else {
|
||
ui.add(egui::TextEdit::singleline(&mut s).desired_width(320.0)).labelled_by(label.id)
|
||
};
|
||
take_first_focus(d, &r);
|
||
if r.changed() {
|
||
d.values.insert(key.into(), json!(s));
|
||
}
|
||
if let Some(pick) = d.pick.as_mut().filter(|pick| pick.key == key) {
|
||
track_pick(pick, &r, r.changed());
|
||
}
|
||
});
|
||
}
|
||
Field::Ref { key, label } => {
|
||
ui.vertical(|ui| {
|
||
let l = ui.label(lang.tr(label));
|
||
ref_edit(app, ui, d, key, RefLabel::By(l.id), 320.0);
|
||
});
|
||
}
|
||
Field::Password { key, label } => {
|
||
// Masked as typed (Excel shows dots); "Show password" reveals it on purpose.
|
||
ui.vertical(|ui| {
|
||
let label = ui.label(lang.tr(label));
|
||
let mut s = d.values.get(key).and_then(Json::as_str).unwrap_or_default().to_string();
|
||
if ui.add(egui::TextEdit::singleline(&mut s).password(!d.show_password).desired_width(320.0)).labelled_by(label.id).changed()
|
||
{
|
||
d.values.insert(key.into(), json!(s));
|
||
}
|
||
ui.checkbox(&mut d.show_password, lang.tr("Show password"));
|
||
});
|
||
}
|
||
Field::Number { key, label } => {
|
||
ui.horizontal(|ui| {
|
||
let label = ui.label(lang.tr(label));
|
||
let mut n = d.values.get(key).and_then(Json::as_f64).unwrap_or(0.0);
|
||
// Typed values count straight away: otherwise Enter or OK in the same frame
|
||
// confirms the old value, because a number field only commits when it loses focus.
|
||
let r = ui.add(egui::DragValue::new(&mut n).speed(0.5).update_while_editing(true)).labelled_by(label.id);
|
||
take_first_focus(d, &r);
|
||
if r.changed() {
|
||
d.values.insert(key.into(), json!(n));
|
||
}
|
||
});
|
||
}
|
||
Field::Choice { key, label, options } => {
|
||
ui.vertical(|ui| {
|
||
let field_label = ui.label(egui::RichText::new(lang.tr(label)).strong());
|
||
let cur = d.values.get(key).and_then(Json::as_str).unwrap_or("").to_string();
|
||
if d.name == "dataValidation" {
|
||
let selected = options.iter().find(|(val, _)| *val == cur).map(|(_, text)| lang.tr(text)).unwrap_or("");
|
||
craft_ui::ComboBox::from_id_salt(("dataValidation", key))
|
||
.selected_text(selected)
|
||
.width(300.0)
|
||
.show_ui(ui, |ui| {
|
||
for (val, text) in options {
|
||
if ui.selectable_label(cur == val, lang.tr(text)).clicked() {
|
||
d.set_value(key, json!(val));
|
||
}
|
||
}
|
||
})
|
||
.response
|
||
.labelled_by(field_label.id);
|
||
} else {
|
||
let radios = |ui: &mut egui::Ui, d: &mut Dialog| {
|
||
for (val, text) in &options {
|
||
if ui.radio(cur == *val, lang.tr(text)).clicked() {
|
||
d.set_value(key, json!(val));
|
||
}
|
||
}
|
||
};
|
||
if key == "pageOrder" {
|
||
// Page Setup pictures the order beside its choices.
|
||
ui.horizontal(|ui| {
|
||
ui.vertical(|ui| radios(ui, d));
|
||
ui.add_space(24.0);
|
||
page_order_preview(ui, PageOrder::parse(&cur).unwrap_or_default());
|
||
});
|
||
} else {
|
||
radios(ui, d);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
Field::Check { key, label } => {
|
||
let mut b = d.values.get(key).and_then(Json::as_bool).unwrap_or(false);
|
||
if ui.checkbox(&mut b, lang.tr(label)).changed() {
|
||
d.values.insert(key.into(), json!(b));
|
||
}
|
||
}
|
||
Field::Note(t) => {
|
||
// A note can carry user data (a URL, a file or sheet name); `tr` reads a `|` as a
|
||
// context separator, so such a note is shown as it is.
|
||
let text = if t.contains('|') { t.as_str() } else { lang.tr(&t) };
|
||
ui.label(egui::RichText::new(text).small());
|
||
}
|
||
}
|
||
ui.end_row();
|
||
}
|
||
});
|
||
}
|
||
|
||
/// Page Setup's picture of a page order: four pages, two tall and two wide, numbered in the
|
||
/// order they print, with a line through them from the first to the last.
|
||
fn page_order_preview(ui: &mut egui::Ui, order: PageOrder) {
|
||
let t = crate::theme::Tokens::get(ui.ctx());
|
||
let (page, gap) = (vec2(22.0, 28.0), 8.0);
|
||
let (rect, _) = ui.allocate_exact_size(vec2(page.x * 2.0 + gap, page.y * 2.0 + gap), egui::Sense::hover());
|
||
let p = ui.painter();
|
||
let mut path = [egui::Pos2::ZERO; 4];
|
||
for (row, col) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||
let r = egui::Rect::from_min_size(rect.min + vec2(col as f32 * (page.x + gap), row as f32 * (page.y + gap)), page);
|
||
p.rect_filled(r, 1.0, t.paper);
|
||
p.rect_stroke(r, 1.0, egui::Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
|
||
let n = order.index(row, col, 2, 2);
|
||
p.text(r.left_top() + vec2(4.0, 2.0), egui::Align2::LEFT_TOP, (n + 1).to_string(), crate::theme::ui_font(9.0), t.text);
|
||
if let Some(at) = path.get_mut(n) {
|
||
*at = r.center() + vec2(2.0, 3.0);
|
||
}
|
||
}
|
||
let stroke = egui::Stroke::new(1.5, t.accent);
|
||
p.add(egui::Shape::line(path.to_vec(), stroke));
|
||
// An arrowhead on the last page.
|
||
let (from, to) = (path[2], path[3]);
|
||
let d = (to - from).normalized();
|
||
let n = vec2(-d.y, d.x);
|
||
p.add(egui::Shape::convex_polygon(vec![to, to - d * 6.0 + n * 3.5, to - d * 6.0 - n * 3.5], t.accent, egui::Stroke::NONE));
|
||
}
|