From 8b5bbcb7e8017402d7a17a6c69e3e65623bc1914 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Sat, 7 Nov 2026 02:31:07 +0800 Subject: [PATCH] Read a modal dialog's controls and values into its MCP message --- docs/HLSD/mcp-server.md | 191 ++++-- src/slic3r/GUI/BindDialog.cpp | 2 + src/slic3r/GUI/ConnectPrinter.cpp | 2 + src/slic3r/GUI/Mcp/McpToolsApp.cpp | 5 +- src/slic3r/GUI/Mcp/McpToolsUi.cpp | 46 +- src/slic3r/GUI/Mcp/McpTypes.hpp | 5 + src/slic3r/GUI/Mcp/ModalTracker.cpp | 680 +++++++++++++++++--- src/slic3r/GUI/Mcp/ModalTracker.hpp | 77 ++- src/slic3r/GUI/Mcp/UiInspector.cpp | 274 +++++++- src/slic3r/GUI/Mcp/UiInspector.hpp | 55 +- src/slic3r/GUI/Mcp/UiRefs.cpp | 2 +- src/slic3r/GUI/Mcp/UiRefs.hpp | 2 +- src/slic3r/GUI/Mcp/WebPages.cpp | 14 +- src/slic3r/GUI/ReleaseNote.cpp | 3 + src/slic3r/GUI/Widgets/SwitchButton.hpp | 4 + src/slic3r/GUI/Widgets/TabCtrl.hpp | 2 + tests/slic3rutils/test_mcp_results.cpp | 805 ++++++++++++++++++++++++ tests/slic3rutils/test_mcp_web.cpp | 68 +- 18 files changed, 2053 insertions(+), 184 deletions(-) diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index a567079cc3..7f8ea3b0ad 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -1430,7 +1430,11 @@ never reused and carry the UI generation and a liveness check, so a ref to a destroyed or rebuilt widget is reported stale. A field is named by the setting it edits: its option key is read from the "parameter name" line of its tooltip, and its label comes from the option's definition. Failing that, the label to its left on the same row names it, then its -tooltip. +tooltip. A control's state reads `[checked]` or `[unchecked]`, or `[mixed]` for a checkbox that shows +neither (a three-state one undetermined, Orca's `CheckBox` half-checked for an unset nullable +setting). An option of a selector Orca builds of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`) +is a button that reads checked while it is the selected one (`selector_option()`), so `ui_input true` +selects it, and a `SwitchButton` with a label at each end has the one it is on as its value. Input tools take a `target`: a ref (also read written as `{ref: "w12"}`), or a locator, which is stable across runs and is what the journal stores. A locator is one of: @@ -1560,11 +1564,15 @@ on the main frame, but under ids `wxNewId()` never hands out again, so they neve ### Rows and popups The rows of `wxDataViewCtrl`s (the object list, Compare presets, the upload queue and other data -views), of `wxListBox` and `wxCheckListBox` (the Add Settings checklist), of Orca's `DropDown` lists, -of `wxGrid` tables (the object settings table) and of the Design tab's `DesignRowList`s are listed -under their list as `row` nodes (`list_rows()`): the first text cell is the label, the other text -cells the value joined with ` | `, a checkbox cell its checked state. A data view is walked through -its model from the root, collapsed branches included. An object list row also says what it stands +views), of `wxListBox` and `wxCheckListBox` (the Add Settings checklist), of `wxListCtrl`s (the +printers a Bonjour or Creality scan finds), of Orca's `DropDown` lists, of `wxGrid` tables (the object +settings table) and of the Design tab's `DesignRowList`s are listed under their list as `row` nodes +(`list_rows()`): the first text cell is the label, the other text cells the value joined with ` | `, a +checkbox cell its checked state. A data view is walked through its model from the root, collapsed +branches included; a modal dialog's message reads its lists through a bounded `list_rows()`, which reads +only shown rows, up to its limit. A click on a list control's row selects it with `SetItemState()`, for +which the control sends `wxEVT_LIST_ITEM_SELECTED`, natively on Windows and from the generic control's +highlighting elsewhere; a double click sends `wxEVT_LIST_ITEM_ACTIVATED`. An object list row also says what it stands for by the indices `list_objects` uses (`plate 1`, `object 0 part 1, modifier`, `object 0 layer range 0-2`). A table's rows are named by their `Name` cell (the object settings table's part rows by the part), else by their row label; a sort indicator after a column title is left out, and a @@ -1749,38 +1757,149 @@ point picking and the painters to their Shift and Alt modes. ### Dialogs and web views `ModalTracker`, a `wxModalDialogHook`, sees every `ShowModal()`, native dialogs included, and -publishes the snapshot `[{title, message, class, native, buttons}]`. Message boxes and file and folder -pickers are native; a picker's message is its prompt, such as "Choose Download Directory", since its -title is often empty. Colour and font choosers are not classified as native, because on GTK they are -wx dialogs that `dialog_respond` ends; on macOS and Windows they are OS choosers, best answered ahead -with a `dialog_auto_answer` rule. `dialog_respond` presses the -topmost wx dialog's button, so the dialog's own handler runs, or ends the dialog with that id when -no such button exists. On Windows and Linux it also presses an open native message box: the tracker -lists the buttons wx gives the box for its style (Yes and No or OK, and Cancel; not Help, which on -Windows shows help without closing the box), and a press goes to the OS's box by message -(`press_dialog_button()`). On Windows that is a `WM_COMMAND` to a message box, or a `TDM_CLICK_BUTTON` -to the task dialog wx shows where Windows has one, found among the UI thread's windows by class and -caption, the active one first; on GTK, `gtk_dialog_response()` on the dialog's widget. The box closes once its own loop runs -again, which `dialog_respond` waits up to 1 s for, so its reply says `closed`. This is how a plugin's -permission prompt is answered. On macOS a message box lists no -buttons, since no call reaches one (above). A picker, and on macOS any native dialog, can only be -answered ahead with a `dialog_auto_answer` rule: a regex searched in the title and message joined by a newline, and also in the title alone for a -dialog with no message (so `^Title$` matches a web dialog), and a button. `Enter()` then returns that button's id without -showing the dialog, and logs it; a file or folder picker can only be cancelled, since any other -answer would return without a path. A wx dialog that matches a rule opens, and the tracker presses -the button once the dialog's modal loop runs (`press_dialog_button()`, queued on the dialog), as -`dialog_respond` does: its buttons do the dialog's work in their handlers (`UnsavedChangesDialog`'s -Transfer and Discard, `CloneDialog`'s Fill), which a returned id would skip. A modal opened above it -before then leaves it to `dialog_respond`. A new rule also answers a -matching dialog that is already open, as `dialog_respond` would, a message box included where it can -be pressed. A prompt posted around the same time, such as the restore -prompt after startup, is handled whether it opens before or after the rule. A script's rules end -with the script, a client's call replaces its earlier rules, and `get_state` lists the rules in -force. +publishes the snapshot `[{title, message, class, native, buttons}]`, which other threads read. Read on +the UI thread, as `get_state`, the `blocked_by_dialog` probe, the guards' refusals and the input tools' +`dialogs` read it, the snapshot describes the open dialogs again first. So it shows a dialog as it is +now: text the dialog filled in once it showed (a printer's name, a list from a scan), a field typed in, +a page switched. Should describing fail, the last description stands. Only a native dialog that holds +the UI thread (macOS) leaves readers with the description published before it; its content does not +change. A dialog that can't be described is listed by its title, class, `native` and `web` flags, with no +message or buttons, so the guards still see it and a rule matches it by its title. Message boxes and file and folder pickers are native; a box's message is its text, and a +picker's is its prompt, such as "Choose Download Directory", since its title is often empty. Colour and +font choosers are not classified as native, because on GTK they are wx dialogs that `dialog_respond` +ends; on macOS and Windows they are OS choosers, best answered ahead with a `dialog_auto_answer` rule. + +A wx dialog's message reads it as a person does, so an agent can tell what the dialog asks and what +each button will do without a screenshot (`DialogReader`). Each shown child becomes a cell. Nested +dialogs, popups, web views and canvases are left out; a nested dialog is described on its own. +Controls are read through the readers `ui_snapshot` uses (`kind_of`, `value_of`, `checked_of`, +`selector_choices`, `list_rows`), so the two say the same about each one: + +- Static text, html and custom widgets that show a label (`StaticLine` titles) read as their text, and + a static box as its title, then its contents. A label that is the window's own name, when that is a + name wx gives every window of a class, is no label: Windows shows the name a window was created with + as its text, so a bare panel reads "panel". +- An editable field, spin or slider reads `[value]`. A read-only field reads as its text. +- A choice reads `[value ▾]`. Orca's `ComboBox` shows its placeholder, such as "Select Vendor", until + something is picked. +- A checkbox or switch reads `[x] label`, `[ ] label`, or `[-] label` when it shows neither state (an + unset nullable setting). A radio button reads `(*) label` or `( ) label`. +- A selector Orca builds of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`), a `SwitchButton` + with a label at each end, and a notebook's tabs read as one line, `(*) A | ( ) B`; an icon option + reads as its tooltip. A notebook's tabs are followed by the page shown. +- A list reads one line per shown row, up to 25, then a line saying `ui_snapshot` lists the rest. +- A gauge reads `[45%]`. +- A disabled control adds ` (disabled)`. Disabled is judged between the control and its dialog, so a + dialog under another modal does not read as all disabled. + +Of the cells a toggle could take as its label, a control with its own mark (a labelled checkbox, a +selector) is never one. + +A secret never shows: a field with password style, a setting field for a password, API key or token +(by the `parameter name` of its tooltip, as `printhost_password` and `printhost_apikey`), or one its +dialog names `kSecretField` (a printer's access code and pin, which those dialogs show in plain text) +reads `[******]`. A URL in a field loses its credentials (`redact_url()`), each word of the value on +its own, as does a print host's value without a scheme, `user:password@host`, which the hosts prefix +with `http://`. + +A parent's cells are put in reading order by their rectangles: rows top to bottom, then left to right. +Two cells are on one row when either one's vertical centre lies within the other's span. A cell over +twice as tall as the other, such as a wrapped label or a column of text, shares its row only with a +cell beside its first line (its centre within the shorter cell's height of the taller one's top) or +centred on it. So a checkbox or a field at a wrapped label's first line shares its row, while a column +of text never pulls the label and field rows below that line into one. So the order the dialog made its widgets in does not +matter: a field made before the label above it reads after it, and PrintHostSend's radio boxes, made +before their labels, each meet their own label. In a row: + +- A toggle with no label of its own (Orca's `CheckBox` and `RadioBox`) takes the cell to its right as + its label: `[x] Remember my choice.`. With nothing there, it takes the topmost single-line cell to + its left, as Preferences and CloneDialog lay their switches out: `Show splash screen | [x]`. Of a + title and its hint stacked beside a switch (RecordingDialog), that is the title. +- Single-line cells side by side join with ` | `. A container whose children make one line counts as + one cell, so `UnsavedChangesDialog`'s rows, each cell in a panel of its own, read + `Sparse infill density | 15% | 20%`. +- A toggle nothing completes is named by what is its own: the setting it edits, its tooltip, else its + window name in parentheses. The text beside it is not used, since the layout gave that to what it + labels. + +Widgets that overlap, as in a dialog not laid out yet, join nothing and keep their order. + +The message is at most 2000 bytes; a longer one is cut there, where a character starts, and ends in +`...`. Once the +cells read pass that, only buttons are looked for: lists are read through a bounded `list_rows()`, which +reads only shown rows and stops at the cap. So describing a dialog costs its window count, plus each +bounded list's own enumeration of the level it reads (a flat data view's model lists all its children, +a pointer each), not the size of the text, values or rows it holds. The dialog's own text, which only +rule matching reads, is walked only for that. Text no wx control holds is not read: what custom widgets paint themselves (`SwitchBoard`, the +AMS mapping items, `RecenterDialog`'s explanation, Preferences' row labels) and icon buttons with no +label. Web dialogs are read through their page (below). + +`buttons` lists the wx buttons a dialog shows, with `enabled: false` for a disabled one. The options of +a selector made of buttons (`RadioGroup`, `TabCtrl`, `MultiSwitchButton`) are not listed, since pressing +one only selects it. `dialog_respond`, and a rule, still find such an option by its label (its tooltip +for an icon option, in full even where a message cut at its cap shows only its start) and select it, and +`ui_snapshot` shows the selected option checked, under the same full label. `ui_input false` on the +selected one, or on a selected radio button or radio box, is refused, since an option is unselected by +selecting another. Other radio buttons and switches are set +with `ui_click` or `ui_input true`, and notebook tabs with `ui_click` on the tab. + +`dialog_respond` presses the topmost wx dialog's button, so the dialog's own handler runs. +`press_dialog_button()` tells what it did: + +- **Pressed:** the button was pressed. +- **Ended:** the dialog has no button with that id, so it ended with it, and `cancel` closes a dialog + without a Cancel button. One whose Cancel or Close is on a page it does not show ends the same way. +- **Disabled:** the button is shown but disabled, so nothing is pressed or stood in for. The dialog + disabled it on purpose: OK while a name is invalid, Send until a box is ticked, Cancel while a + cancel is under way. `dialog_respond` refuses a disabled button, its message showing what the dialog + still needs. +- **Hidden:** the button is only on a page the dialog does not show, such as a wizard's Finish, so + nothing is pressed or stood in for, and `dialog_respond` refuses it. Buttons are looked up among the + dialog's own windows, not a popup's or a nested dialog's. +- **Failed:** a native message box could not be pressed. + +On Windows and Linux `dialog_respond` also presses an open native message box. The tracker lists the +buttons wx gives the box for its style (Yes and No or OK, and Cancel; not Help, which on Windows shows +help without closing the box), and a press goes to the OS's box by message. On Windows that is a +`WM_COMMAND` to a message box, or a `TDM_CLICK_BUTTON` to the task dialog wx shows where Windows has +one, found among the UI thread's windows by class and caption, the active one first. On GTK it is +`gtk_dialog_response()` on the dialog's widget. The box closes once its own loop runs again, which +`dialog_respond` waits up to 1 s for, so its reply says `closed`. A box that is no longer shown is +refused. This is how a plugin's permission prompt is answered. On macOS a message box lists no buttons, +since no call reaches one (above). + +A picker, and on macOS any native dialog, can only be answered ahead with a `dialog_auto_answer` rule: +a regex and a button. The regex is searched in three places: + +- the title and message joined by a newline +- the title and the dialog's own text joined the same way. The own text is its static text and html, + one per line in child order, cut and trimmed as the message is. It leaves the controls out, and + `describe_dialog()` reads it in a walk of its own that the message's budget does not stop. +- the title alone, for a dialog with no own text (so `^Title$` matches a web dialog) + +A rule written against a dialog's wording therefore matches however its controls read, and long values +or lists before that wording do not push it out. `Enter()` then returns that button's id without +showing the dialog, and logs it; a file or folder picker can only be cancelled, since any other answer +would return without a path. + +A wx dialog that matches a rule opens, and the tracker presses the button once the dialog's modal loop +runs (`press_dialog_button()`, queued on the dialog), as `dialog_respond` does. Its buttons do the +dialog's work in their handlers (`UnsavedChangesDialog`'s Transfer and Discard, `CloneDialog`'s Fill), +which a returned id would skip. The rule counts as used once the press pressed the button or ended the +dialog. A button disabled by then leaves the dialog open, logged, and a modal opened above it before +then leaves it to `dialog_respond`. + +A new rule also answers a matching dialog that is already open, as `dialog_respond` would, a message +box included where it can be pressed. The first rule that names one of its buttons decides: if that +button is disabled or hidden, the dialog stays open and the reply says `disabled: true` or +`hidden: true` (a hidden Cancel or Close ends the dialog, as above). A prompt posted around +the same time, such as the restore prompt after startup, is handled whether it opens before or after +the rule. A script's rules end with the script, a client's call replaces its earlier rules, and +`get_state` lists the rules in force. A dialog that hosts a web view is described with `web: true`; its controls are on its page, which -`ui_snapshot root=dialog` lists and the input tools drive like any widget (see Web pages below). Its -message is empty, so a rule matches it by title. Its page is the one its shown web view holds; a web +`ui_snapshot root=dialog` lists and the input tools drive like any widget (see Web pages below). It +has no text of its own, so a rule matches it by title. Its page is the one its shown web view holds; a web view the dialog keeps hidden has no page to press on. `dialog_respond` looks a name or label up as a wx button label first, then among the page's buttons and links, waiting up to 3 s for one to show (each ask expires with those 3 s, so the page never presses one later), and clicks it there, hit diff --git a/src/slic3r/GUI/BindDialog.cpp b/src/slic3r/GUI/BindDialog.cpp index 90b2c937dc..61a333e8e0 100644 --- a/src/slic3r/GUI/BindDialog.cpp +++ b/src/slic3r/GUI/BindDialog.cpp @@ -10,6 +10,7 @@ #include "slic3r/GUI/Widgets/Label.hpp" #include "slic3r/GUI/Widgets/HyperLink.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" #include #include #include @@ -153,6 +154,7 @@ PingCodeBindDialog::PingCodeBindDialog(Plater* plater /*= nullptr*/) m_text_input_single_code[i]->GetTextCtrl()->SetDefaultStyle(textAttr); m_text_input_single_code[i]->SetFont(Label::Body_16); m_text_input_single_code[i]->GetTextCtrl()->SetMaxLength(1); + m_text_input_single_code[i]->SetName(Mcp::kSecretField); m_text_input_single_code[i]->GetTextCtrl()->Bind(wxEVT_TEXT, &PingCodeBindDialog::on_text_changed, this); m_text_input_single_code[i]->GetTextCtrl()->Bind(wxEVT_KEY_DOWN, &PingCodeBindDialog::on_key_backspace, this); m_text_input_single_code[i]->GetTextCtrl()->Bind(wxEVT_CHAR, &PingCodeBindDialog::on_key_input, this); diff --git a/src/slic3r/GUI/ConnectPrinter.cpp b/src/slic3r/GUI/ConnectPrinter.cpp index 4a1d8c7da9..7d587277f1 100644 --- a/src/slic3r/GUI/ConnectPrinter.cpp +++ b/src/slic3r/GUI/ConnectPrinter.cpp @@ -11,6 +11,7 @@ #include #include #include "slic3r/GUI/Widgets/TextInput.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" #include #include #include "slic3r/GUI/wxExtensions.hpp" @@ -50,6 +51,7 @@ ConnectPrinterDialog::ConnectPrinterDialog(wxWindow *parent, wxWindowID id, cons // OrcaSonar uses a 12-character base32 access code. Keep this field long // enough for it while retaining the existing validation for LAN codes. m_textCtrl_code->GetTextCtrl()->SetMaxLength(12); + m_textCtrl_code->SetName(Mcp::kSecretField); m_textCtrl_code->SetFont(Label::Body_14); m_textCtrl_code->SetCornerRadius(FromDIP(5)); m_textCtrl_code->SetSize(wxSize(FromDIP(330), FromDIP(40))); diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 5b91985606..d3a92c4831 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -232,7 +232,10 @@ void register_app_tools(McpService& service) "volumes [[object, part]], in the indices select takes; wipe_tower when a prime tower is selected; canvas is the 3D " "view it belongs to), slicing state, and " "the Preview's view type, time mode and layer range (1-based, with their Z). What is going on: open modal " - "dialogs, menus closed unseen (a menu a call opened that no reply listed), dialog_auto_answer rules in force, " + "dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its " + "text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and " + "selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled " + "control; menus closed unseen (a menu a call opened that no reply listed), dialog_auto_answer rules in force, " "notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running " "recording.", object_schema({}), [&service](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&service] { return app_state(service); })); })); diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index 98c1acb7e7..8c9f55e267 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -610,6 +610,14 @@ json web_locator(McpService& service, ToolContext& ctx, const WebTarget& t, cons return loc; } +// Why dialog_respond does not press a button refused_press() refuses. +std::string refused_button(const std::string& button, DialogPress refused) +{ + if (refused == DialogPress::Hidden) + return "The dialog's \"" + button + "\" button is on a page it does not show; its message shows what it shows now"; + return "The dialog's \"" + button + "\" button is disabled; its message shows what the dialog still needs"; +} + // `closed: true`, with the dialogs still open under the one that closed (the filament picker under the // colour picker it opened), whose answer is still to give. Any thread. json closed_reply(McpService& service) @@ -1235,7 +1243,10 @@ void register_ui_tools(McpService& service) "ui_input", L("Set a control's value"), "Set a control's value and send the events a person's edit would. Widgets: text fields (submit, the default, also " "presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, sliders, choice, " - "combo and list boxes (by option text or index), and checkboxes, toggles and a row's checkbox (true or false). " + "combo and list boxes (by option text or index), checkboxes, toggles and a row's checkbox (true or false), and a " + "radio button (an Orca radio box too) or a selector's option, as the dialog message shows them (*) / ( ) (true " + "selects it; false on the " + "selected one is refused, as only selecting another unselects it). " "ImGui items, by their kind, with the value read back: a field is typed into (a slider through the number field " "beside it, multiline text with \\n), a combo's option is picked by its text or 0-based index, and a checkbox, radio " "or toggle is clicked when it differs. A web page's fields, as typing would leave them: text, number, range, colour " @@ -1475,6 +1486,11 @@ void register_ui_tools(McpService& service) reg.add(recover_input_tool( "dialog_respond", L("Answer a dialog"), "Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's label, or a numeric id. " + "A disabled button (enabled: false) is refused, the dialog's message showing what it still needs, and so is one on " + "a page the dialog does not show, except a hidden cancel or close, which ends the dialog. The label of an option of a " + "selector made of buttons (Orca's radio groups, tab bars and multi-switches, shown as (*) / ( ) in the message) " + "selects that option and leaves the dialog open; set other radio buttons and switches with ui_click or ui_input " + "true, and notebook tabs with ui_click. " "dialog.title, text the dialog's title contains, makes sure which dialog that is; it must be the topmost. Reply: " "closed: true when it closed, and dialogs, those still open. A native message box (native: true) is pressed through " "the OS, by one of the buttons get_state.dialogs lists for it; a file or folder picker can't be answered here, nor " @@ -1542,11 +1558,13 @@ void register_ui_tools(McpService& service) native = is_native_dialog(dialog); if (id == wxID_NONE || (native && !has_dialog_button(dialog, id))) throw ToolFailure("The dialog has no button \"" + button + "\"", {{"dialog", describe_dialog(dialog)}}); - const bool pressed = press_dialog_button(dialog, id); - if (native && !pressed) + if (const std::optional refused = refused_press(dialog, id)) + throw ToolFailure(refused_button(button, *refused), {{"dialog", describe_dialog(dialog)}}); + const DialogPress press = press_dialog_button(dialog, id); + if (press == DialogPress::Failed) throw ToolFailure("The message box is not shown, so its button could not be pressed; take a new ui_snapshot", {{"dialog", describe_dialog(dialog)}}); - return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", pressed}}; + return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", press == DialogPress::Pressed}}; }); if (!out.is_null()) { settle(ctx); @@ -1618,8 +1636,13 @@ void register_ui_tools(McpService& service) out = ctx.run_ui([&]() -> json { wxDialog* dialog = find_dialog(); const int id = standard; + if (const std::optional refused = id != wxID_NONE ? refused_press(dialog, id) : std::nullopt) + throw ToolFailure(refused_button(button, *refused), {{"dialog", describe_dialog(dialog)}}); if (id != wxID_NONE && (ends_dialog || has_dialog_button(dialog, id))) - return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", press_dialog_button(dialog, id)}}; + return {{"dialog", dialog_title}, + {"button", button}, + {"id", id}, + {"pressed", press_dialog_button(dialog, id) == DialogPress::Pressed}}; throw ToolFailure("The dialog's page has no button \"" + button + "\"", {{"dialog", describe_dialog(dialog)}, {"page_buttons", page_buttons}}); }); @@ -1646,7 +1669,7 @@ void register_ui_tools(McpService& service) "label, standard name or id) is pressed as for a wx dialog, any other on its page once it shows there, for up to " "10 s after the page loads; past that, cancel and close end the dialog and any other button gives up.", object_schema({{"rules", array_prop({{"type", "object"}, - {"properties", {{"match", prop("string", "Regex searched in \"title\\nmessage\", and also in the title alone for a dialog with no message (a web dialog), so ^Title$ matches it.")}, + {"properties", {{"match", prop("string", "Regex searched in \"title\\nmessage\", in \"title\\ntext\" (the dialog's own static text, one line each, without its controls), and in the title alone for a dialog with no text (a web dialog), so ^Title$ matches it.")}, {"button", prop("string", "yes | no | ok | cancel | close | apply | label | id")}}}, {"required", {"match", "button"}}, {"additionalProperties", false}}, @@ -1665,9 +1688,10 @@ void register_ui_tools(McpService& service) const bool native = top != nullptr && is_native_dialog(top); if (top == nullptr || (native && message_box_buttons(top).empty())) return json(); - const json info = describe_dialog(top); + std::string text; + const json info = describe_dialog(top, &text); for (const AutoAnswerRule& rule : registered) - if (rule_matches(rule, info["title"].get(), info["message"].get())) { + if (rule_matches(rule, info["title"].get(), info["message"].get(), text)) { // A web dialog is answered on its page, as ModalTracker::Enter() does. if (info.value("web", false) && native_dialog_button(top, rule.button) == wxID_NONE) { const int standard = standard_dialog_button(rule.button); @@ -1678,9 +1702,13 @@ void register_ui_tools(McpService& service) const int id = resolve_dialog_button(top, rule.button); if (id == wxID_NONE || (native && !has_dialog_button(top, id))) continue; + // The first rule that names a button decides; a disabled or hidden one leaves the + // dialog open. + if (const std::optional refused = refused_press(top, id)) + return {{"dialog", info["title"]}, {"button", rule.button}, {*refused == DialogPress::Hidden ? "hidden" : "disabled", true}}; // As before any other press, the presses ui_mouse downs left on pages end first. service.modals().before_press(); - if (press_dialog_button(top, id) || !native) { + if (press_dialog_button(top, id) != DialogPress::Failed) { service.modals().count_use(0, rule.pattern, rule.button); return {{"dialog", info["title"]}, {"button", rule.button}}; } diff --git a/src/slic3r/GUI/Mcp/McpTypes.hpp b/src/slic3r/GUI/Mcp/McpTypes.hpp index 260872644f..47eff89cbe 100644 --- a/src/slic3r/GUI/Mcp/McpTypes.hpp +++ b/src/slic3r/GUI/Mcp/McpTypes.hpp @@ -23,6 +23,11 @@ namespace Slic3r { namespace GUI { namespace Mcp { // window that changes the Python scripts setting, so no agent or script can turn it on. inline constexpr char kHiddenFromAutomation[] = "OrcaHiddenFromMcp"; +// The name of a text field that holds a secret its dialog shows in plain text, such as a printer's +// access code: a modal dialog's description writes its value as [******] (describe_dialog()). A field +// with password style, or a setting field for a password or key, needs no name. +inline constexpr char kSecretField[] = "OrcaSecretForMcp"; + // What a tool may do while the app is inside another call's nested event loop or behind a modal // dialog. Inspect tools only read; Recover tools act on the topmost modal dialog to unblock the // app; everything else is Mutate and is refused in both situations. diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 795a005fb5..1e9a082386 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -1,22 +1,34 @@ #include "ModalTracker.hpp" #include "McpTypes.hpp" +#include "UiInspector.hpp" #include "WebPages.hpp" #include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Widgets/Button.hpp" +#include "slic3r/GUI/Widgets/ComboBox.hpp" +#include "slic3r/GUI/Widgets/RadioBox.hpp" +#include "slic3r/GUI/Widgets/TextInput.hpp" #include +#include #include #include #include #include #include +#include +#include #include #include +#include +#include #include #include #include +#include +#include #include #include #include @@ -62,6 +74,8 @@ using nlohmann::json; namespace { constexpr std::size_t kMaxMessage = 2000; +// Rows of one list a message shows; ui_snapshot lists them all. +constexpr std::size_t kMaxListRows = 25; std::string lower(std::string s) { @@ -77,32 +91,420 @@ std::string normalize_label(const wxString& label) return lower(into_u8(l)); } -void collect(wxWindow* w, std::string& message, json& buttons) +bool is_button(const wxWindow* w) { return dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr; } + +// At most kMaxMessage bytes, cut where a character starts, without trailing blank lines. +void fit_message(std::string& s) +{ + if (s.size() > kMaxMessage) { + std::size_t cut = kMaxMessage; + while (cut > 0 && (static_cast(s[cut]) & 0xC0) == 0x80) + --cut; + s = s.substr(0, cut) + "..."; + } + while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) + s.pop_back(); +} + +// The dialog's own text, which rules search (rule_matches()): its static text and html, one per line, +// in child order, through every shown child but its buttons. Its controls' values are left out, so a +// rule written against the dialog's wording matches however the controls read. +void own_text(wxWindow* w, std::string& text) { for (wxWindow* child : w->GetChildren()) { if (!child->IsShown()) continue; if (auto* html = dynamic_cast(child)) { - message += into_u8(html->ToText()) + "\n"; + text += into_u8(html->ToText()) + "\n"; continue; } - if (dynamic_cast(child) != nullptr || dynamic_cast<::Button*>(child) != nullptr) { - const wxString label = wxStripMenuCodes(child->GetLabel()); - if (!label.empty()) - buttons.push_back({{"id", child->GetId()}, {"label", into_u8(label)}}); + if (is_button(child)) continue; - } - if (auto* text = dynamic_cast(child)) { - const wxString t = text->GetLabel(); + if (auto* label = dynamic_cast(child)) { + const wxString t = label->GetLabel(); if (!t.empty()) - message += into_u8(t) + "\n"; + text += into_u8(t) + "\n"; } - collect(child, message, buttons); + own_text(child, text); } } +// Whether `w` and the windows between it and its dialog are enabled. The dialog itself is left out: +// one under another modal is disabled as a whole, which says nothing about its controls. +bool enabled_in_dialog(const wxWindow* w) +{ + for (; w != nullptr && dynamic_cast(w) == nullptr; w = w->GetParent()) + if (!w->IsThisEnabled()) + return false; + return true; +} + +// The text a field edits: a TextInput's own text control, or the field itself. +wxTextEntry* field_entry(wxWindow* w) +{ + if (auto* input = dynamic_cast<::TextInput*>(w)) + return input->GetTextCtrl(); + return dynamic_cast(w); +} + +// A field whose value is a secret: password style, a setting for a password or key, or a field its +// dialog names kSecretField (a printer's access code, which it shows in plain text). +bool is_secret_field(wxWindow* w) +{ + auto* inner = dynamic_cast(field_entry(w)); + if (w->GetName() == kSecretField || (inner != nullptr && inner->GetName() == kSecretField)) + return true; + if (inner != nullptr && inner->HasFlag(wxTE_PASSWORD)) + return true; + return is_secret_key(option_key_of(w)); +} + +// A field's value without the credentials the URLs in it carry, each word of it on its own. A host +// setting's value without a scheme counts as a URL too: the print hosts put http:// before it and sign +// in with its user:password@. +std::string redacted_value(wxWindow* w, const std::string& value) +{ + const bool host = value.find('@') != std::string::npos && lower(option_key_of(w)).find("host") != std::string::npos; + std::string out; + for (std::size_t i = 0; i < value.size();) { + const bool space = std::isspace(static_cast(value[i])) != 0; + std::size_t end = i; + while (end < value.size() && (std::isspace(static_cast(value[end])) != 0) == space) + ++end; + const std::string word = value.substr(i, end - i); + if (!space && word.find("://") != std::string::npos) + out += redact_url(word); + else if (!space && host && word.find('@') != std::string::npos) + out += redact_url("http://" + word).substr(std::char_traits::length("http://")); + else + out += word; + i = end; + } + return out; +} + +// A toggle's mark: [x] / [ ] / [-] for a checkbox or switch, (*) / ( ) for a radio button. +std::string toggle_mark(wxWindow* w, const std::string& kind) +{ + const int checked = checked_of(w); + if (kind == "radio" || dynamic_cast(w) != nullptr) + return checked == 1 ? "(*)" : "( )"; + return checked == 1 ? "[x]" : checked == 2 ? "[-]" : "[ ]"; +} + +// A toggle nothing completed, named by what is its own: the setting it edits, its tooltip, else its +// window name. Not by the text beside it, which the layout gave whatever it labels. +void complete_toggle(MessageCell& cell) +{ + if (!cell.toggle) + return; + std::string name; + if (cell.window != nullptr) { + // A setting field's tooltip ends in its "parameter name" line, which names nothing. + wxString tip = cell.window->GetToolTipText().BeforeFirst('\n'); + if (tip.StartsWith(_L("parameter name") + ": ")) + tip.clear(); + if (const std::string key = option_key_of(cell.window); !key.empty()) + name = option_label(key); + if (name.empty() && !tip.Trim().Trim(false).empty()) + name = into_u8(tip); + if (name.empty()) + if (const std::string window_name = meaningful_name(cell.window); !window_name.empty()) + name = "(" + window_name + ")"; + } + cell.text += (name.empty() ? "" : " " + name) + cell.suffix; + cell.toggle = false; + cell.suffix.clear(); +} + +std::string as_lines(std::vector cells) +{ + std::string out; + for (MessageCell& cell : cells) { + complete_toggle(cell); + out += (out.empty() ? "" : "\n") + cell.text; + } + return out; +} + +// Reads a wx dialog's message (describe_dialog()): each shown child becomes a cell, a container's +// cells are laid out in rows (layout_cells()), and its buttons are listed apart. Once the cells read +// so far fill the message, only buttons are looked for: a dialog costs its window count, whatever the +// text, values and rows it holds. +class DialogReader +{ +public: + explicit DialogReader(json& buttons) : m_buttons(buttons) {} + + std::string message(wxWindow* dialog) { return as_lines(read(dialog)); } + +private: + std::vector read(wxWindow* parent) + { + std::vector cells; + for (wxWindow* child : parent->GetChildren()) + if (std::optional cell = read_child(child); cell && !cell->text.empty()) + cells.push_back(std::move(*cell)); + return layout_cells(std::move(cells)); + } + + // A container's cells, as one cell at the container: a single one keeps what it is, so a row's + // cells in panels of their own (UnsavedChangesDialog's name, old and new value) still join. + std::optional container(wxWindow* w, const std::string& head = {}) + { + std::vector inner = read(w); + MessageCell cell; + if (head.empty() && inner.size() == 1) + cell = std::move(inner.front()); + else { + cell.text = head; + if (!inner.empty()) + cell.text += (head.empty() ? "" : "\n") + as_lines(std::move(inner)); + } + cell.rect = w->GetRect(); + if (cell.text.empty()) + return std::nullopt; + return cell; + } + + std::optional content(wxWindow* w, std::string text, const std::string& suffix = {}) + { + if (text.empty()) + return std::nullopt; + MessageCell cell; + cell.rect = w->GetRect(); + cell.text = std::move(text) + suffix; + m_chars += cell.text.size(); + return cell; + } + + bool full() const { return m_chars > kMaxMessage; } + + std::optional read_child(wxWindow* w) + { + // A nested dialog is described on its own, and a popup belongs to no dialog. + if (!w->IsShown() || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + return std::nullopt; + if (is_button(w)) { + // A selector's option only selects it, so it is read with its selector. + const wxString label = wxStripMenuCodes(w->GetLabel()); + if (!label.empty() && selector_option(w).selector == nullptr) { + json button{{"id", w->GetId()}, {"label", into_u8(label)}}; + if (!enabled_in_dialog(w)) + button["enabled"] = false; + m_buttons.push_back(std::move(button)); + } + return std::nullopt; + } + const std::string kind = kind_of(w); + const std::string disabled = enabled_in_dialog(w) ? "" : " (disabled)"; + if (kind == "canvas" || kind == "webview") + return std::nullopt; + if (auto* box = dynamic_cast(w)) { + const std::string label = full() ? std::string() : into_u8(box->GetLabelText().Trim().Trim(false)); + m_chars += label.size(); + std::optional cell = container(box, label); + // Boxed controls that are its siblings read after its title, not beside it. + if (cell && box->GetChildren().empty()) + cell->rect.height = box->GetCharHeight(); + return cell; + } + if (std::optional choices = selector_choices(w)) { + auto* book = dynamic_cast(w); + wxWindow* page = book != nullptr ? book->GetCurrentPage() : nullptr; + const std::string line = full() ? std::string() : selector_line(choices->options, choices->selected); + std::optional cell; + if (page == nullptr) + cell = content(w, line, disabled); + else { + // A notebook's tabs, then the page shown. + m_chars += line.size(); + cell = container(page, line); + if (cell) + cell->rect = w->GetRect(); + } + if (cell) + cell->marked = true; + return cell; + } + const bool leaf = !kind.empty() && kind != "tabs" && kind != "window" && kind != "dialog" && kind != "popup"; + if (!leaf && dynamic_cast(w) == nullptr && dynamic_cast(w) == nullptr) + return container(w); + if (full()) + return std::nullopt; + if (auto* html = dynamic_cast(w)) + return content(w, into_u8(html->ToText())); + if (auto* gauge = dynamic_cast(w)) + return content(w, "[" + std::to_string(gauge->GetRange() > 0 ? gauge->GetValue() * 100 / gauge->GetRange() : 0) + "%]"); + if (kind == "checkbox" || kind == "toggle" || kind == "radio") { + const std::string mark = toggle_mark(w, kind); + const std::string label = into_u8(wxStripMenuCodes(w->GetLabel()).Trim().Trim(false)); + if (!label.empty()) { + std::optional cell = content(w, mark + " " + label, disabled); + cell->marked = true; + return cell; + } + std::optional cell = content(w, mark); + cell->toggle = true; + cell->suffix = disabled; + cell->window = w; + return cell; + } + if (kind == "combo" || kind == "choice") { + // Orca's ComboBox shows its placeholder ("Select Vendor") until something is picked. + auto* combo = dynamic_cast<::ComboBox*>(w); + return content(w, "[" + (combo != nullptr ? into_u8(combo->GetValue()) : value_of(w)) + " ▾]", disabled); + } + if (kind == "spin" || kind == "slider") + return content(w, "[" + value_of(w) + "]", disabled); + if (kind == "text") { + const std::string value = value_of(w); + if (is_secret_field(w)) + return content(w, value.empty() ? "[]" : "[******]", disabled); + wxTextEntry* entry = field_entry(w); + if (entry != nullptr && !entry->IsEditable()) + return content(w, redacted_value(w, value)); + return content(w, "[" + redacted_value(w, value) + "]", disabled); + } + if (kind == "list") + return list(w); + if (kind == "label" || kind == "control") + return content(w, into_u8(w->GetLabel())); + return std::nullopt; + } + + // One line per shown row, up to kMaxListRows: its label and cells, its check, whether it is + // selected; a tree's rows indented by depth. + std::optional list(wxWindow* w) + { + const std::vector rows = list_rows(w, kMaxListRows + 1); + std::string text; + for (std::size_t i = 0; i < rows.size() && i < kMaxListRows; ++i) { + const ListRow& row = rows[i]; + const std::string label = row.path.empty() ? std::string() : row.path.back(); + std::string line = std::string(std::size_t(2 * row.depth), ' ') + "- "; + if (row.checked >= 0) + line += row.checked == 1 ? "[x] " : row.checked == 2 ? "[-] " : "[ ] "; + line += label; + if (!row.value.empty()) + line += (label.empty() ? "" : " | ") + row.value; + if (row.selected) + line += " (selected)"; + if (!row.enabled) + line += " (disabled)"; + text += (text.empty() ? "" : "\n") + line; + } + if (rows.size() > kMaxListRows) + text += "\n- … more rows (ui_snapshot lists them)"; + return content(w, text); + } + + json& m_buttons; + std::size_t m_chars = 0; +}; + } // namespace +std::vector layout_cells(std::vector cells) +{ + auto centre = [](const wxRect& r) { return r.y + r.height / 2; }; + auto same_row = [&](const MessageCell& a, const MessageCell& b) { + const bool a_in_b = b.rect.y <= centre(a.rect) && centre(a.rect) <= b.rect.GetBottom(); + const bool b_in_a = a.rect.y <= centre(b.rect) && centre(b.rect) <= a.rect.GetBottom(); + const MessageCell& taller = a.rect.height >= b.rect.height ? a : b; + const MessageCell& shorter = a.rect.height >= b.rect.height ? b : a; + if (taller.rect.height <= 2 * std::max(1, shorter.rect.height)) + return a_in_b || b_in_a; + // A cell over twice as tall as the other (a wrapped label, a column of text) shares its row with + // a cell beside its first line or centred on it; the rows of a column beside it below that line + // keep rows of their own. The first line is as tall as the shorter cell, or as one of the taller + // cell's lines where those are shorter. + const int lines = int(std::count(taller.text.begin(), taller.text.end(), '\n')) + 1; + const int line = std::min(shorter.rect.height, std::max(1, taller.rect.height / lines)); + const int c = centre(shorter.rect); + return (taller.rect.y <= c && c <= taller.rect.y + line) || (a_in_b && b_in_a); + }; + std::stable_sort(cells.begin(), cells.end(), [](const MessageCell& a, const MessageCell& b) { return a.rect.y < b.rect.y; }); + std::vector> rows; + for (MessageCell& cell : cells) { + const bool joins_row = !rows.empty() && std::any_of(rows.back().begin(), rows.back().end(), + [&](const MessageCell& other) { return same_row(other, cell); }); + if (!joins_row) + rows.emplace_back(); + rows.back().push_back(std::move(cell)); + } + // Joined cells meet at one separator, whatever spaces their labels end in ("Start PA: "). + auto join = [](MessageCell& left, const std::string& separator, const std::string& right) { + while (!left.text.empty() && left.text.back() == ' ') + left.text.pop_back(); + left.text += separator + right.substr(std::min(right.find_first_not_of(' '), right.size())); + }; + std::vector out; + for (std::vector& row : rows) { + std::stable_sort(row.begin(), row.end(), [](const MessageCell& a, const MessageCell& b) { return a.rect.x < b.rect.x; }); + const std::size_t first = out.size(); + for (MessageCell& cell : row) { + if (out.size() > first) { + MessageCell& prev = out.back(); + // Cells that overlap were not laid out side by side (a dialog not laid out yet). + const bool apart = prev.rect.GetRight() < cell.rect.x; + if (apart && prev.toggle && !cell.toggle && !cell.marked) { + join(prev, " ", cell.text + prev.suffix); + prev.toggle = false; + prev.marked = true; + prev.suffix.clear(); + prev.window = nullptr; + prev.rect.Union(cell.rect); + continue; + } + const bool single = prev.text.find('\n') == std::string::npos && cell.text.find('\n') == std::string::npos; + if (apart && !prev.toggle && !cell.toggle && single) { + join(prev, " | ", cell.text); + prev.marked = prev.marked || cell.marked; + prev.rect.Union(cell.rect); + continue; + } + } + out.push_back(std::move(cell)); + } + // A toggle with nothing to its right takes a label to its left: "Show splash screen | [x]", as + // Preferences lays its switches out. Of a title and its hint stacked there, the title. + for (std::size_t i = first; i < out.size();) { + std::size_t label = out.size(); + for (std::size_t j = first; out[i].toggle && j < i; ++j) + if (!out[j].toggle && !out[j].marked && out[j].text.find('\n') == std::string::npos && out[j].rect.GetRight() < out[i].rect.x && + (label == out.size() || out[j].rect.y < out[label].rect.y)) + label = j; + if (label == out.size()) { + ++i; + continue; + } + join(out[label], " | ", out[i].text + out[i].suffix); + out[label].marked = true; + out[label].rect.Union(out[i].rect); + out.erase(out.begin() + std::ptrdiff_t(i)); + } + } + return out; +} + +std::string selector_line(const std::vector& options, int selected) +{ + std::string out; + for (std::size_t i = 0; i < options.size(); ++i) + out += (i == 0 ? "" : " | ") + std::string(int(i) == selected ? "(*) " : "( ) ") + options[i]; + return out; +} + +bool is_secret_key(const std::string& key) +{ + const std::string k = lower(key); + for (const char* word : {"password", "apikey", "api_key", "token", "secret"}) + if (k.find(word) != std::string::npos) + return true; + return false; +} + std::string class_name(const wxWindow* window) { if (window == nullptr) @@ -162,6 +564,27 @@ wxString shown_label(int id, const wxString& label) } // namespace +namespace { + +// Whether `dialog` can return `id`: a message box only the ids of the buttons its style gives it, on +// every platform (on macOS too, where no call presses them, but ShowModal() still returns one); any +// other dialog any id. +bool box_answers(wxDialog* dialog, int id) +{ + const auto* box = dynamic_cast(dialog); + if (box == nullptr) + return true; + const long style = box->GetMessageDialogStyle(); + if (style & wxYES_NO) { + if (id == wxID_YES || id == wxID_NO) + return true; + } else if (id == wxID_OK) + return true; + return id == wxID_CANCEL && (style & wxCANCEL) != 0; +} + +} // namespace + json message_box_buttons(wxDialog* dialog) { json out = json::array(); @@ -271,31 +694,36 @@ bool press_message_box(wxDialog* dialog, int id) } // namespace -json describe_dialog(wxDialog* dialog) +json describe_dialog(wxDialog* dialog, std::string* text) { json out{{"title", into_u8(dialog->GetTitle())}, {"class", class_name(dialog)}, {"native", is_native_dialog(dialog)}}; std::string message; + std::string own; json buttons = json::array(); if (auto* md = dynamic_cast(dialog)) { message = into_u8(md->GetMessage()); if (!md->GetExtendedMessage().empty()) message += "\n" + into_u8(md->GetExtendedMessage()); buttons = message_box_buttons(dialog); + own = message; } else if (auto* fd = dynamic_cast(dialog)) { - message = into_u8(fd->GetMessage()); + message = own = into_u8(fd->GetMessage()); } else if (auto* dd = dynamic_cast(dialog)) { - message = into_u8(dd->GetMessage()); + message = own = into_u8(dd->GetMessage()); } else { - collect(dialog, message, buttons); + message = DialogReader(buttons).message(dialog); + if (text != nullptr) + own_text(dialog, own); } - if (message.size() > kMaxMessage) - message = message.substr(0, kMaxMessage) + "..."; - while (!message.empty() && (message.back() == '\n' || message.back() == ' ')) - message.pop_back(); + fit_message(message); out["message"] = message; out["buttons"] = std::move(buttons); if (!is_native_dialog(dialog) && web_view_in(dialog, false) != nullptr) out["web"] = true; + if (text != nullptr) { + fit_message(own); + *text = std::move(own); + } return out; } @@ -303,18 +731,37 @@ int dialog_button_by_label(wxDialog* dialog, const std::string& label) { if (dialog == nullptr) return wxID_NONE; - const std::string name = lower(label); - json buttons = json::array(); - if (dynamic_cast(dialog) != nullptr) - buttons = message_box_buttons(dialog); - else if (!is_native_dialog(dialog)) { - std::string message; - collect(dialog, message, buttons); + const std::string name = lower(label); + if (dynamic_cast(dialog) != nullptr) { + for (const json& b : message_box_buttons(dialog)) + if (normalize_label(from_u8(b["label"].get())) == name) + return b["id"].get(); + return wxID_NONE; } - for (const json& b : buttons) - if (normalize_label(from_u8(b["label"].get())) == name) - return b["id"].get(); - return wxID_NONE; + if (is_native_dialog(dialog)) + return wxID_NONE; + // The buttons a person sees, a selector's options among them: pressing one of those selects it. + int found = wxID_NONE; + std::function find = [&](wxWindow* w) { + for (wxWindow* child : w->GetChildren()) { + if (found != wxID_NONE || !child->IsShown() || dynamic_cast(child) != nullptr || + dynamic_cast(child) != nullptr) + continue; + if (is_button(child)) { + // The label the dialog's description shows for it: a selector option's (an icon one's + // tooltip), or the button's without its mnemonic, so "A&&B" is found as "A&B". + wxString shown = selector_option(child).selector != nullptr ? from_u8(selector_option_label(child)) : + wxStripMenuCodes(child->GetLabel()); + if (!shown.Trim().Trim(false).empty() && lower(into_u8(shown)) == name) + found = child->GetId(); + continue; + } + if (dynamic_cast(child) == nullptr) + find(child); + } + }; + find(dialog); + return found; } int standard_dialog_button(const std::string& button) @@ -340,21 +787,30 @@ int resolve_dialog_button(wxDialog* dialog, const std::string& button) namespace { -wxWindow* dialog_button(wxDialog* dialog, int id) +// The button with `id` among `dialog`'s windows, outside nested dialogs and popups, and whether it +// shows: it and every window above it are shown. A shown one wins over one on a hidden page. +struct FoundButton { - wxWindow* found = nullptr; - std::function find = [&](wxWindow* w) { + wxWindow* button = nullptr; + bool shown = false; +}; + +FoundButton find_button(wxDialog* dialog, int id) +{ + FoundButton found; + std::function find = [&](wxWindow* w, bool shown) { for (wxWindow* child : w->GetChildren()) { - if (found != nullptr || dynamic_cast(child) != nullptr) + if (found.shown || dynamic_cast(child) != nullptr || dynamic_cast(child) != nullptr) continue; - if (child->GetId() == id && child->IsShown() && child->IsEnabled() && - (dynamic_cast(child) != nullptr || class_name(child).find("Button") != std::string::npos)) - found = child; - else - find(child); + const bool here = shown && child->IsShown(); + if (child->GetId() == id && (dynamic_cast(child) != nullptr || class_name(child).find("Button") != std::string::npos)) { + if (here || found.button == nullptr) + found = {child, here}; + } else + find(child, here); } }; - find(dialog); + find(dialog, true); return found; } @@ -364,22 +820,40 @@ bool has_dialog_button(wxDialog* dialog, int id) { if (dynamic_cast(dialog) != nullptr) return has_box_button(dialog, id); - return dialog != nullptr && dialog_button(dialog, id) != nullptr; + if (dialog == nullptr) + return false; + const FoundButton found = find_button(dialog, id); + return found.shown && enabled_in_dialog(found.button); } -bool press_dialog_button(wxDialog* dialog, int id) +std::optional refused_press(wxDialog* dialog, int id) +{ + if (dialog == nullptr || is_native_dialog(dialog)) + return std::nullopt; + const FoundButton found = find_button(dialog, id); + if (found.button == nullptr) + return std::nullopt; + if (found.shown) + return enabled_in_dialog(found.button) ? std::nullopt : std::optional(DialogPress::Disabled); + // Cancel and Close end a dialog that shows neither, as they end one without them. + return id == wxID_CANCEL || id == wxID_CLOSE ? std::nullopt : std::optional(DialogPress::Hidden); +} + +DialogPress press_dialog_button(wxDialog* dialog, int id) { if (dynamic_cast(dialog) != nullptr) - return press_message_box(dialog, id); - wxWindow* pressed = dialog_button(dialog, id); - if (pressed == nullptr) { + return press_message_box(dialog, id) ? DialogPress::Pressed : DialogPress::Failed; + if (const std::optional refused = refused_press(dialog, id)) + return *refused; + const FoundButton found = find_button(dialog, id); + if (!found.shown) { dialog->EndModal(id); - return false; + return DialogPress::Ended; } wxCommandEvent evt(wxEVT_BUTTON, id); - evt.SetEventObject(pressed); - pressed->GetEventHandler()->ProcessEvent(evt); - return true; + evt.SetEventObject(found.button); + found.button->GetEventHandler()->ProcessEvent(evt); + return DialogPress::Pressed; } AutoAnswerRule make_rule(const std::string& pattern, const std::string& button) @@ -395,9 +869,10 @@ AutoAnswerRule make_rule(const std::string& pattern, const std::string& button) return rule; } -bool rule_matches(const AutoAnswerRule& rule, const std::string& title, const std::string& message) +bool rule_matches(const AutoAnswerRule& rule, const std::string& title, const std::string& message, const std::string& text) { - return std::regex_search(title + "\n" + message, rule.compiled) || (message.empty() && std::regex_search(title, rule.compiled)); + return std::regex_search(title + "\n" + message, rule.compiled) || std::regex_search(title + "\n" + text, rule.compiled) || + (text.empty() && std::regex_search(title, rule.compiled)); } int native_dialog_button(wxDialog* dialog, const std::string& button) @@ -483,8 +958,16 @@ void ModalTracker::count_use(int layer, const std::string& pattern, const std::s } } -json ModalTracker::snapshot() const +json ModalTracker::snapshot() { + // On the UI thread the dialogs are described as they are now: text a dialog filled in once it + // showed, a field typed in, a page switched. Should describing fail, the last description stands. + if (wxIsMainThread()) { + try { + publish(); + } catch (...) { + } + } std::lock_guard lock(m_mutex); return m_snapshot; } @@ -495,11 +978,35 @@ bool ModalTracker::any_open() const return !m_snapshot.empty(); } +namespace { + +// A dialog that can't be described, listed by its title and kind so the guards and the tools still see +// it and rules match it by its title: a web one too, as describe_dialog() would have flagged it. +json undescribed(wxDialog* dialog) +{ + json entry{{"title", into_u8(dialog->GetTitle())}, {"class", class_name(dialog)}, {"native", is_native_dialog(dialog)}, + {"message", ""}, + {"buttons", json::array()}}; + try { + if (!is_native_dialog(dialog) && web_view_in(dialog, false) != nullptr) + entry["web"] = true; + } catch (...) { + } + return entry; +} + +} // namespace + void ModalTracker::publish() { json snap = json::array(); - for (wxDialog* d : m_stack) - snap.push_back(describe_dialog(d)); + for (wxDialog* d : m_stack) { + try { + snap.push_back(describe_dialog(d)); + } catch (...) { + snap.push_back(undescribed(d)); + } + } std::lock_guard lock(m_mutex); m_snapshot = std::move(snap); } @@ -512,49 +1019,76 @@ int ModalTracker::Enter(wxDialog* dialog) // answers it, and leaving it off the stack keeps it out of the dialog tools and get_state. if (dialog != nullptr && dialog->GetName() == kHiddenFromAutomation) return wxID_NONE; - const json info = describe_dialog(dialog); + // A description that fails leaves the dialog matched by its title alone, and tracked all the same. + std::string text; + json info; + try { + info = describe_dialog(dialog, &text); + } catch (...) { + info = undescribed(dialog); + text.clear(); + } const std::string title = info["title"].get(); const std::string message = info["message"].get(); const bool web = info.value("web", false); - // A web dialog's rule whose button is not one of its wx buttons is answered on its page. - std::optional> web_rule; + const bool native = is_native_dialog(dialog); + // A web dialog's rule whose button is not one of its wx buttons is answered on its page, and a + // wx dialog's rule once its button is pressed. + std::optional> web_rule, wx_rule; const int answer = [&] { std::lock_guard lock(m_mutex); for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer) for (AutoAnswerRule& rule : layer->second) - if (rule_matches(rule, title, message)) { + if (rule_matches(rule, title, message, text)) { if (web && native_dialog_button(dialog, rule.button) == wxID_NONE) { web_rule.emplace(layer->first, rule.pattern, rule.button); return int(wxID_NONE); } const int id = resolve_dialog_button(dialog, rule.button); // A file or folder picker answered with anything but cancel would return - // without a path, so only cancel answers one. - if (id != wxID_NONE && (id == wxID_CANCEL || !is_picker(dialog))) { - ++rule.uses; - BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << info["title"].get() << "\" with " - << rule.button << " (rule \"" << rule.pattern << "\")"; + // without a path, so only cancel answers one; a message box only with a button + // it has. + if (id != wxID_NONE && (id == wxID_CANCEL || !is_picker(dialog)) && box_answers(dialog, id)) { + if (native) { + ++rule.uses; + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << title << "\" with " << rule.button + << " (rule \"" << rule.pattern << "\")"; + } else + wx_rule.emplace(layer->first, rule.pattern, rule.button); return id; } } return int(wxID_NONE); }(); // A native dialog has no handlers to run: ShowModal() returns the id without showing it. - if (answer != wxID_NONE && is_native_dialog(dialog)) + if (answer != wxID_NONE && native) return answer; push(dialog); - publish(); + try { + publish(); + } catch (...) { + } // A wx dialog's buttons do its work in their handlers (Transfer, Discard, Clone's Fill), which // a returned id would skip. So it opens, and the button is pressed once its modal loop runs, as - // dialog_respond does. Queued on the dialog, the press goes with it if it is destroyed first; - // a modal opened above it before then leaves it to dialog_respond. The tracker lives as long - // as the app. - if (answer != wxID_NONE) - dialog->CallAfter([this, dialog, answer] { - if (top() == dialog) { - before_press(); - press_dialog_button(dialog, answer); + // dialog_respond does; the rule counts as used once that pressed the button or ended the + // dialog. A button disabled by then leaves the dialog open. Queued on the dialog, the press goes + // with it if it is destroyed first; a modal opened above it before then leaves it to + // dialog_respond. The tracker lives as long as the app. + if (wx_rule) + dialog->CallAfter([this, dialog, answer, title, rule = *wx_rule] { + if (top() != dialog) + return; + const auto& [layer, pattern, button] = rule; + before_press(); + if (const DialogPress press = press_dialog_button(dialog, answer); press == DialogPress::Disabled || press == DialogPress::Hidden) { + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << pattern << "\" for dialog \"" << title << "\": its " + << button << " button is " << (press == DialogPress::Hidden ? "not shown" : "disabled") + << "; the dialog stays open"; + return; } + count_use(layer, pattern, button); + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << title << "\" with " << button << " (rule \"" << pattern + << "\")"; }); if (web_rule) { const auto& [layer, pattern, button] = *web_rule; diff --git a/src/slic3r/GUI/Mcp/ModalTracker.hpp b/src/slic3r/GUI/Mcp/ModalTracker.hpp index 4d3b304600..efabbf0f7f 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.hpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.hpp @@ -2,11 +2,13 @@ #include +#include #include #include #include #include +#include #include #include #include @@ -29,9 +31,11 @@ struct AutoAnswerRule // Builds a rule, compiling its pattern. Throws ToolFailure on an invalid pattern. AutoAnswerRule make_rule(const std::string& pattern, const std::string& button); -// Whether the rule's pattern is found in "title\nmessage", or also in the title alone for a dialog -// with no message (a web dialog), so ^Title$ matches it. -bool rule_matches(const AutoAnswerRule& rule, const std::string& title, const std::string& message); +// Whether the rule's pattern is found in "title\nmessage" or in "title\ntext", where `text` is the +// dialog's own text (describe_dialog()), or in the title alone for a dialog with no text (a web +// dialog), so ^Title$ matches it. A rule written against a dialog's wording finds it in its text, +// however its controls read in its message. +bool rule_matches(const AutoAnswerRule& rule, const std::string& title, const std::string& message, const std::string& text); // Every modal dialog shown through ShowModal - Orca's own, wxMessageDialog and the native file // dialogs alike - passes through this hook. It keeps the stack of open modals for the guards and @@ -63,8 +67,9 @@ public: void count_use(int layer, const std::string& pattern, const std::string& button); // [{title, message, class, native, buttons:[{id,label}]}] of the open modals, outermost first. - // Any thread. - nlohmann::json snapshot() const; + // On the UI thread the dialogs are described as they are now, and that is published; other + // threads read the last description published. Any thread. + nlohmann::json snapshot(); bool any_open() const; // What runs right before a rule presses a button, its wx one or its page's: as before any other @@ -95,10 +100,40 @@ private: int m_next_layer = 1; }; -// {title, message, class, native, buttons:[{id,label}], web?} for a dialog; `web` is true for a -// dialog with a web view, whose page holds its controls (ui_snapshot root=dialog lists them). UI -// thread only. -nlohmann::json describe_dialog(wxDialog* dialog); +// {title, message, class, native, buttons:[{id,label,enabled?}], web?} for a dialog. A wx dialog's +// message reads it as a person does: its text, and its controls with their values and states, row by +// row (DialogReader in the .cpp); `enabled` is false for a disabled button. `web` is true for a dialog +// with a web view, whose page holds its controls (ui_snapshot root=dialog lists them). `text`, when +// given, receives the dialog's own text: its static text and html, one per line, without its +// controls, which auto-answer rules also search (rule_matches()). UI thread only. +nlohmann::json describe_dialog(wxDialog* dialog, std::string* text = nullptr); + +// A piece of a dialog's message: what one child window, or one container's children, read as. +struct MessageCell +{ + wxRect rect; // in the parent's coordinates + std::string text; // one or more lines + // A toggle with no label of its own (Orca's CheckBox and RadioBox): its mark, which the cell after + // it on its row completes. `suffix` follows that label, and `window` is the toggle, named another + // way when nothing completes it. + bool toggle = false; + std::string suffix; + wxWindow* window = nullptr; + // A control with its own mark and label (a labelled checkbox, a selector), which labels no toggle. + bool marked = false; +}; +// A parent's cells in reading order, rows top to bottom and each row left to right, where two cells +// are on one row when either one's vertical centre lies within the other's span; a cell over twice as +// tall as the other shares its row only with a cell beside its first line or centred on it, so a column +// of text does not draw the rows beside it into one. Equal positions keep their order. In a row, a +// toggle takes the cell to its right as its label ("[x] Remember my choice."), or with nothing there +// the topmost one to its left ("Show splash screen | [x]"), and single-line cells side by side join +// with " | " ("Layer height | 0.2 | 0.28"). +std::vector layout_cells(std::vector cells); +// A selector's options in one line, the selected one marked: "(*) A | ( ) B". +std::string selector_line(const std::vector& options, int selected); +// Whether a setting's option key names a secret: a password, API key, token or secret. +bool is_secret_key(const std::string& key); // True for dialogs implemented by the OS (wxMessageDialog, file and directory pickers): they have // no wx children to inspect or click. An open message box can still be pressed on Windows and Linux @@ -119,6 +154,12 @@ int resolve_dialog_button(wxDialog* dialog, const std::string& button); int dialog_button_by_label(wxDialog* dialog, const std::string& label); // Whether `dialog` has a shown, enabled wx button with `id`, or a message box button. bool has_dialog_button(wxDialog* dialog, int id); +enum class DialogPress; +// Why `dialog` would not take a press of its wx button `id`: Disabled for a shown button that is +// disabled (an invalid name, an unticked box), Hidden for one only a page the dialog does not show +// has, the dialog's own way of saying not now. Cancel and Close on a hidden page are not refused: they +// end the dialog as they end one without them. nullopt when the press would go ahead. +std::optional refused_press(wxDialog* dialog, int id); // The id of the shown, enabled wx button a name, label or id stands for in `dialog`, or wxID_NONE: // a web dialog whose rule names none of its wx buttons is answered on its page. UI thread only. int native_dialog_button(wxDialog* dialog, const std::string& button); @@ -126,11 +167,21 @@ int native_dialog_button(wxDialog* dialog, const std::string& button); // wxID_NONE. int standard_dialog_button(const std::string& button); +// What press_dialog_button() did. +enum class DialogPress +{ + Pressed, // the button's handler ran (a message box's press is queued to its box) + Ended, // no shown button has the id, so the dialog ended with it + Disabled, // the button is shown but disabled: nothing happened + Hidden, // the button is only on a page the dialog does not show: nothing happened + Failed, // a message box that could not be pressed: it is no longer shown, or the press was not sent +}; // Presses the button with `id` in `dialog` so the dialog's own handler runs, or ends the dialog with -// that id when no such button exists. A message box's button is pressed by message to its box, which -// closes once its own loop runs again; it has no other way to end. Returns whether a button was -// pressed. UI thread only, while the dialog is modal. -bool press_dialog_button(wxDialog* dialog, int id); +// that id when no such button exists, so `cancel` closes a dialog without a Cancel button. A button +// refused_press() refuses is neither pressed nor stood in for: the dialog disabled or hid it on +// purpose. A message box's button is pressed by message to its box, which closes once its own loop +// runs again; it has no other way to end. UI thread only, while the dialog is modal. +DialogPress press_dialog_button(wxDialog* dialog, int id); // Demangled C++ class name of a window, e.g. "Slic3r::GUI::MessageDialog". std::string class_name(const wxWindow* window); diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index 028d9da9c6..676ba36327 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -31,10 +31,15 @@ #include "slic3r/GUI/Selection.hpp" #include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" +#include "slic3r/GUI/Widgets/CheckBox.hpp" #include "slic3r/GUI/Widgets/SideButton.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" #include "slic3r/GUI/Widgets/DropDown.hpp" +#include "slic3r/GUI/Widgets/RadioBox.hpp" +#include "slic3r/GUI/Widgets/RadioGroup.hpp" #include "slic3r/GUI/Widgets/SpinInput.hpp" +#include "slic3r/GUI/Widgets/SwitchButton.hpp" +#include "slic3r/GUI/Widgets/TabCtrl.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" #include "libslic3r/AABBMesh.hpp" #include "libslic3r/BoundingBox.hpp" @@ -72,13 +77,16 @@ #include #include #include +#include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -87,6 +95,7 @@ #include #include #include +#include #include #include #include @@ -110,6 +119,7 @@ #include #include #include +#include #include #include #include @@ -141,7 +151,24 @@ std::string short_class(const wxWindow* w) return c; } -// The role a window plays for an agent; empty for plain containers. +// A name wx gives every window of a class, or the window's class itself: it says nothing. +bool is_default_name(const std::string& name, const wxWindow* w) +{ + // wx's *NameStr defaults (wxPanelNameStr, wxGaugeNameStr, wxStaticBoxNameStr...) and Orca's own. + static const std::set defaults{ + "panel", "frame", "dialog", "button", "text", "staticText", "checkbox", "check", + "radioButton", "radioBox", "comboBox", "choice", "listBox", "GLCanvas", "notebook", "wxSpinCtrl", + "wxSpinCtrlDouble", "wxSpinButton", "slider", "scrollBar", "scrolledWindow", "bitmapButton", "toggle", "staticBitmap", + "staticBox", "groupBox", "gauge", "hyperlink", "dataviewCtrl", "listCtrl", "treeCtrl", "grid", + "htmlWindow", "richText", "searchCtrl", "filepicker", "dirpicker", "colourpicker", "fontpicker", "calendar", + "datectrl", "timectrl", "webView", "wxWebView", "staticLine", "splitter", "toolbar", "statusBar", + "control", "auiToolBar", "simplebook", "book", "listbook", "choicebook", "treebook", "toolbook", + "collapsiblePane", "animationctrl", "activityindicator", "wxHeaderCtrl", "mediaCtrl", ""}; + return defaults.count(name) != 0 || name == short_class(w); +} + +} // namespace + std::string kind_of(wxWindow* w) { if (dynamic_cast(w) != nullptr) @@ -172,7 +199,8 @@ std::string kind_of(wxWindow* w) return "text"; if (dynamic_cast(w) != nullptr) return "slider"; - if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || + dynamic_cast(w) != nullptr) return "list"; #ifdef SLIC3R_CAD if (dynamic_cast(w) != nullptr) @@ -183,12 +211,16 @@ std::string kind_of(wxWindow* w) if (dynamic_cast(w) != nullptr) return "label"; // Custom-drawn controls (Orca's StaticBox family and the like) show a label but have no - // class of their own here. - if (w->GetChildren().empty() && !w->GetLabel().empty()) + // class of their own here. Windows gives a window created without a label its name as its text, + // so a label that is the window's own default name (a bare panel's "panel") is none. + const wxString label = w->GetLabel(); + if (w->GetChildren().empty() && !label.empty() && !(label == w->GetName() && is_default_name(into_u8(label), w))) return "control"; return {}; } +namespace { + wxTextEntry* text_entry(wxWindow* w) { if (dynamic_cast<::ComboBox*>(w) != nullptr) @@ -198,10 +230,95 @@ wxTextEntry* text_entry(wxWindow* w) return dynamic_cast(w); } +// A wxBookCtrlBase whose pages a person picks by their titles; a wxSimplebook shows none. +bool has_page_titles(const wxBookCtrlBase& book) +{ + if (dynamic_cast(&book) != nullptr) + return false; + for (size_t i = 0; i < book.GetPageCount(); ++i) + if (!book.GetPageText(i).empty()) + return true; + return false; +} + +} // namespace + +SelectorOption selector_option(wxWindow* w) +{ + if (dynamic_cast<::Button*>(w) == nullptr || w->GetParent() == nullptr) + return {}; + wxWindow* parent = w->GetParent(); + if (auto* group = dynamic_cast<::RadioGroup*>(parent)) { + // Its options' labels are its buttons, in order, each beside its radio icon. + int index = 0; + for (wxWindow* child : group->GetChildren()) { + if (child == w) + return {group, index, group->GetSelection() == index}; + if (dynamic_cast<::Button*>(child) != nullptr) + ++index; + } + return {}; + } + if (auto* tabs = dynamic_cast<::TabCtrl*>(parent)) { + for (unsigned int i = 0; i < tabs->GetCount(); ++i) + if (tabs->GetItemButton(i) == w) + return {tabs, int(i), tabs->GetSelection() == int(i)}; + return {}; + } + // A MultiSwitchButton keeps its option buttons in a scrolled window of its own. + if (auto* multi = dynamic_cast<::MultiSwitchButton*>(parent->GetParent())) { + for (unsigned int i = 0; i < multi->GetCount(); ++i) + if (multi->GetButton(i) == w) + return {multi, int(i), multi->GetSelection() == int(i)}; + } + return {}; +} + +std::string selector_option_label(wxWindow* button) +{ + wxString label = wxStripMenuCodes(button->GetLabel()); + if (label.Trim().Trim(false).empty()) + label = button->GetToolTipText().BeforeFirst('\n'); + label.Replace("\n", " "); + return into_u8(label); +} + +std::optional selector_choices(wxWindow* w) +{ + SelectorChoices out; + auto option = [](wxWindow* button) { return button != nullptr ? selector_option_label(button) : std::string(); }; + if (auto* group = dynamic_cast<::RadioGroup*>(w)) { + for (wxWindow* child : group->GetChildren()) + if (dynamic_cast<::Button*>(child) != nullptr) + out.options.push_back(option(child)); + out.selected = group->GetSelection(); + } else if (auto* tabs = dynamic_cast<::TabCtrl*>(w)) { + for (unsigned int i = 0; i < tabs->GetCount(); ++i) + out.options.push_back(option(tabs->GetItemButton(i))); + out.selected = tabs->GetSelection(); + } else if (auto* multi = dynamic_cast<::MultiSwitchButton*>(w)) { + for (unsigned int i = 0; i < multi->GetCount(); ++i) + out.options.push_back(option(multi->GetButton(i))); + out.selected = multi->GetSelection(); + } else if (auto* sw = dynamic_cast<::SwitchButton*>(w); sw != nullptr && !sw->GetLabelAt(0).empty()) { + out.options = {into_u8(sw->GetLabelAt(0)), into_u8(sw->GetLabelAt(1))}; + out.selected = sw->GetValue() ? 1 : 0; + } else if (auto* book = dynamic_cast(w); book != nullptr && has_page_titles(*book)) { + for (size_t i = 0; i < book->GetPageCount(); ++i) + out.options.push_back(into_u8(book->GetPageText(i))); + out.selected = book->GetSelection(); + } else + return std::nullopt; + return out; +} + std::string value_of(wxWindow* w) { if (auto* web = dynamic_cast(w)) return redact_url(into_u8(web->GetCurrentURL())); + // A switch with a label at each end shows which one it is on. + if (auto* sw = dynamic_cast<::SwitchButton*>(w); sw != nullptr && !sw->GetLabelAt(0).empty()) + return into_u8(sw->GetLabelAt(sw->GetValue() ? 1 : 0)); if (auto* spin = dynamic_cast<::SpinInput*>(w)) return std::to_string(spin->GetValue()); if (auto* spin = dynamic_cast(w)) @@ -222,8 +339,16 @@ std::string value_of(wxWindow* w) int checked_of(wxWindow* w) { - if (auto* c = dynamic_cast(w)) + if (const SelectorOption option = selector_option(w); option.selector != nullptr) + return option.selected ? 1 : 0; + if (auto* c = dynamic_cast(w)) { + if (c->Is3State() && c->Get3StateValue() == wxCHK_UNDETERMINED) + return 2; return c->GetValue() ? 1 : 0; + } + // A setting's checkbox shows neither state while the setting is unset (a nullable bool). + if (auto* c = dynamic_cast<::CheckBox*>(w); c != nullptr && c->IsHalfChecked()) + return 2; if (auto* t = dynamic_cast(w)) return t->GetValue() ? 1 : 0; if (auto* t = dynamic_cast(w)) @@ -233,7 +358,7 @@ int checked_of(wxWindow* w) return -1; } -std::string option_key_of(wxWindow* w); +namespace { // The text left of a control on its row: how Orca's forms label their fields. std::string row_label(wxWindow* w) @@ -265,7 +390,8 @@ std::string row_label(wxWindow* w) return into_u8(label.Trim().Trim(false)); } -// The label of a setting from its definition, in the UI language. +} // namespace + std::string option_label(const std::string& key) { const ConfigOptionDef* def = print_config_def.get(key.substr(0, key.find('['))); @@ -277,6 +403,9 @@ std::string label_of(wxWindow* w) // A popup has no title, and a drop-down list's tooltip is the hovered item's. if (dynamic_cast(w) != nullptr) return {}; + // A selector's option by the name the dialog message and label lookup give it, in full. + if (selector_option(w).selector != nullptr) + return selector_option_label(w); if (auto* tlw = dynamic_cast(w)) return into_u8(tlw->GetTitle()); // Input fields are named by the setting they edit or the label on their row; their own label is @@ -299,8 +428,13 @@ std::string label_of(wxWindow* w) } label.Replace("\n", " "); std::string out = into_u8(wxStripMenuCodes(label)); - if (out.size() > 120) - out = out.substr(0, 117) + "..."; + if (out.size() > 120) { + // Cut where a character starts, so the label stays UTF-8. + std::size_t cut = 117; + while (cut > 0 && (static_cast(out[cut]) & 0xC0) == 0x80) + --cut; + out = out.substr(0, cut) + "..."; + } return out; } @@ -330,18 +464,14 @@ std::string option_key_of(wxWindow* w) return {}; } -// wx gives every window a default name for its class; those say nothing. std::string meaningful_name(wxWindow* w) { - static const std::set defaults{"panel", "frame", "dialog", "button", "text", "staticText", "checkbox", "radioButton", - "comboBox", "choice", "listBox", "GLCanvas", "notebook", "wxSpinCtrl", "wxSpinCtrlDouble", - "slider", "scrolledWindow", "bitmapButton", "toggle", "staticBitmap", "staticBox", - "hyperlink", "dataviewCtrl", "listCtrl", "webView", "staticLine", "splitter", "toolbar", - "statusBar", "control", "wxWebView", "auiToolBar", "simplebook", "book", "check", ""}; const std::string name = into_u8(w->GetName()); - return defaults.count(name) != 0 || name == short_class(w) ? std::string() : name; + return is_default_name(name, w) ? std::string() : name; } +namespace { + wxPoint client_pos_in_tlw(wxWindow* w) { wxWindow* tlw = wxGetTopLevelParent(w); @@ -1268,19 +1398,22 @@ std::string object_row_note(ObjectDataViewModel& model, const wxDataViewItem& it } } -void data_view_rows(wxDataViewCtrl& ctrl, std::vector& out) +void data_view_rows(wxDataViewCtrl& ctrl, std::vector& out, std::size_t limit) { wxDataViewModel* model = ctrl.GetModel(); if (model == nullptr) return; const std::vector cols = shown_columns(ctrl); auto* objects = dynamic_cast(model); - // Collapsed branches too: acting on a row expands the branches above it. + // Collapsed branches too, unless the rows are limited: acting on a row expands the branches above it. + const bool limited = limit != std::numeric_limits::max(); std::function&, int, bool)> add = [&](const wxDataViewItem& parent, const std::vector& above, int depth, bool shown) { wxDataViewItemArray children; model->GetChildren(parent, children); for (const wxDataViewItem& item : children) { + if (out.size() >= limit) + return; ListRow row; row.path = above; bool labelled = false; @@ -1304,17 +1437,17 @@ void data_view_rows(wxDataViewCtrl& ctrl, std::vector& out) row.item = item; const std::vector path = row.path; out.push_back(std::move(row)); - if (model->IsContainer(item)) + if (model->IsContainer(item) && (!limited || (shown && ctrl.IsExpanded(item)))) add(item, path, depth + 1, shown && ctrl.IsExpanded(item)); } }; add(wxDataViewItem(nullptr), {}, 0, true); } -void list_box_rows(wxListBox& box, std::vector& out) +void list_box_rows(wxListBox& box, std::vector& out, std::size_t limit) { auto* checks = dynamic_cast(&box); - for (unsigned i = 0; i < box.GetCount(); ++i) { + for (unsigned i = 0; i < box.GetCount() && out.size() < limit; ++i) { ListRow row; row.path = {into_u8(box.GetString(i))}; row.checked = checks == nullptr ? -1 : checks->IsChecked(i) ? 1 : 0; @@ -1326,12 +1459,12 @@ void list_box_rows(wxListBox& box, std::vector& out) // A drop-down list's items; one of a group, which shows in a sublist, has the group's label above it. // The picked item is the checked one. -void drop_down_rows(DropDown& drop, std::vector& out) +void drop_down_rows(DropDown& drop, std::vector& out, std::size_t limit) { if (drop.IsSubList()) return; // its main list has the same items const std::vector& items = drop.GetItems(); - for (std::size_t i = 0; i < items.size(); ++i) { + for (std::size_t i = 0; i < items.size() && out.size() < limit; ++i) { const DropDown::Item& item = items[i]; if ((item.style & DD_ITEM_STYLE_SPLIT_ITEM) != 0) continue; @@ -1389,14 +1522,14 @@ int grid_name_column(const std::vector& titles) // A table's rows, read-only: named by their "Name" cell, else by their row label where the table // shows one, else by their first titled cell, with every titled cell as the value. -void grid_rows(wxGrid& grid, std::vector& out) +void grid_rows(wxGrid& grid, std::vector& out, std::size_t limit) { if (grid.GetTable() == nullptr) return; const std::vector titles = grid_titles(grid); const bool named = std::find(titles.begin(), titles.end(), "Name") != titles.end(); const int name = grid_name_column(titles); - for (int r = grid.GetColLabelSize() == 0 ? 1 : 0; r < grid.GetNumberRows(); ++r) { + for (int r = grid.GetColLabelSize() == 0 ? 1 : 0; r < grid.GetNumberRows() && out.size() < limit; ++r) { if (!grid.IsRowShown(r)) continue; ListRow row; @@ -1412,6 +1545,41 @@ void grid_rows(wxGrid& grid, std::vector& out) } } +// A report list's column titles, "#n" for an untitled one; nothing for the other list modes, whose +// items have only their text. +std::vector list_ctrl_columns(wxListCtrl& list) +{ + std::vector out; + if (!list.InReportView()) + return out; + for (int c = 0; c < list.GetColumnCount(); ++c) { + wxListItem column; + column.SetMask(wxLIST_MASK_TEXT); + list.GetColumn(c, column); + wxString title = column.GetText(); + title.Trim().Trim(false); + out.push_back(title.empty() ? "#" + std::to_string(c + 1) : into_u8(title)); + } + return out; +} + +// A list control's items: named by their first column, with the other columns as the value. +void list_ctrl_rows(wxListCtrl& list, std::vector& out, std::size_t limit) +{ + const int columns = list.InReportView() ? list.GetColumnCount() : 1; + for (long i = 0; i < list.GetItemCount() && out.size() < limit; ++i) { + ListRow row; + std::vector cells; + for (int c = 1; c < columns; ++c) + cells.push_back(into_u8(list.GetItemText(i, c))); + row.path = {into_u8(list.GetItemText(i, 0))}; + row.value = joined(cells, " | "); + row.selected = list.GetItemState(i, wxLIST_STATE_SELECTED) != 0; + row.index = int(i); + out.push_back(std::move(row)); + } +} + #ifdef SLIC3R_CAD // The Design tab's feature tree and body lists: each row with the tips of its action icons, which // `column` names. @@ -1534,6 +1702,37 @@ json click_data_view_row(wxDataViewCtrl& ctrl, const ListRow& row, const std::st return {{"clicked", joined(row.path, ">")}, {"selected", selected_rows(ctrl)}}; } +// Selects a list control's item as a click does: the list control sends wxEVT_LIST_ITEM_SELECTED for +// it (natively on Windows, from the generic control's highlighting elsewhere). +json click_list_ctrl_row(wxListCtrl& list, const ListRow& row, const ClickOptions& o) +{ + const bool right = o.button == "right"; + const long n = row.index; + const int mods = parse_modifiers(o.modifiers); + const long state = wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED; + if (!right || list.GetItemState(n, wxLIST_STATE_SELECTED) == 0) { + if (!list.HasFlag(wxLC_SINGLE_SEL) && !right && (mods & (wxMOD_CONTROL | wxMOD_SHIFT)) != 0) + list.SetItemState(n, list.GetItemState(n, wxLIST_STATE_SELECTED) != 0 ? 0 : state, state); + else { + for (long i = 0; i < list.GetItemCount(); ++i) + if (i != n && list.GetItemState(i, wxLIST_STATE_SELECTED) != 0) + list.SetItemState(i, 0, wxLIST_STATE_SELECTED); + list.SetItemState(n, state, state); + } + list.EnsureVisible(n); + } + auto item_event = [&](wxEventType type) { + wxListEvent evt(type, list.GetId()); + evt.m_itemIndex = n; + send(&list, evt); + }; + if (o.double_click && !right) + item_event(wxEVT_LIST_ITEM_ACTIVATED); + if (right) + item_event(wxEVT_LIST_ITEM_RIGHT_CLICK); + return {{"clicked", joined(row.path, ">")}, {"selected", selected_rows(list)}}; +} + json click_list_box_row(wxListBox& box, const ListRow& row, const ClickOptions& o) { const bool right = o.button == "right"; @@ -1612,17 +1811,19 @@ json click_design_row(DesignRowList& list, const ListRow& row, const std::string } // namespace -std::vector list_rows(wxWindow* list) +std::vector list_rows(wxWindow* list, std::size_t limit) { std::vector out; if (auto* view = dynamic_cast(list)) - data_view_rows(*view, out); + data_view_rows(*view, out, limit); else if (auto* box = dynamic_cast(list)) - list_box_rows(*box, out); + list_box_rows(*box, out, limit); else if (auto* drop = dynamic_cast(list)) - drop_down_rows(*drop, out); + drop_down_rows(*drop, out, limit); else if (auto* grid = dynamic_cast(list)) - grid_rows(*grid, out); + grid_rows(*grid, out, limit); + else if (auto* items = dynamic_cast(list)) + list_ctrl_rows(*items, out, limit); #ifdef SLIC3R_CAD else if (auto* design = dynamic_cast(list)) design_rows(*design, out); @@ -1641,7 +1842,7 @@ bool is_row_list(wxWindow* w) return true; #endif return dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || - dynamic_cast(w) != nullptr; + dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr; } std::vector list_columns(wxWindow* list) @@ -1655,7 +1856,8 @@ std::vector list_columns(wxWindow* list) for (const std::string& title : grid_titles(*grid)) if (!title.empty()) out.push_back(title); - } + } else if (auto* items = dynamic_cast(list)) + out = list_ctrl_columns(*items); return out; } @@ -1703,9 +1905,11 @@ json click_row(wxWindow& list, const ListRow& row, const std::string& column, co return click_design_row(*design, row, column, o); #endif if (!column.empty()) - throw ToolFailure("This list has no columns; leave out column"); + throw ToolFailure("This list's rows are clicked whole; leave out column"); if (auto* box = dynamic_cast(&list)) return click_list_box_row(*box, row, o); + if (auto* items = dynamic_cast(&list)) + return click_list_ctrl_row(*items, row, o); if (auto* drop = dynamic_cast(&list)) { if (o.button != "left" || o.double_click || !o.modifiers.empty()) throw ToolFailure("A drop-down list's row takes a plain left click, which picks it"); @@ -2997,6 +3201,10 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit) if (checked_of(w) >= 0) { const bool want = value.is_boolean() ? value.get() : (text == "1" || lower(text) == "true"); + // An option, as a radio button, is unselected by selecting another; a click would only select it again. + if (!want && checked_of(w) == 1 && (selector_option(w).selector != nullptr || dynamic_cast(w) != nullptr || + dynamic_cast(w) != nullptr)) + throw ToolFailure("An option is unselected by selecting another one; ui_input true on that one"); if ((checked_of(w) == 1) != want) click(t, ClickOptions{}); return {{"checked", checked_of(w) == 1}}; diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index fb413fafe6..863ba85357 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -284,10 +285,58 @@ std::string within_of(wxWindow* w); // The shown popups that opened from `top` or from its widgets, which ui_snapshot lists after it. std::vector popups_of(wxWindow* top); +// How an agent reads a widget. ui_snapshot and a modal dialog's description (describe_dialog()) both +// read controls through these, so they say the same about each one. UI thread only. + +// The role a window plays for an agent: button, checkbox, toggle, radio, combo, choice, spin, text, +// slider, list, tabs, label, control (a custom-drawn widget that shows a label), canvas, webview, +// dialog, window or popup. Empty for plain containers. +std::string kind_of(wxWindow* w); +// What a control shows: a field's text, a choice's selection, a spin's or slider's number, the end a +// labelled SwitchButton is on, a web view's URL (redacted). Empty for other windows. +std::string value_of(wxWindow* w); +// 1 checked, 0 not, 2 neither (a three-state wxCheckBox undetermined, Orca's CheckBox half-checked for +// an unset setting), -1 for a window with no check state. A selector's option button is checked +// while it is the selected one (selector_option()). +int checked_of(wxWindow* w); +// The name an agent knows a window by: a top-level window's title; for an input field, the setting it +// edits or the label left of it on its row; else its own label, or an icon button's tooltip. +std::string label_of(wxWindow* w); +// The option key a setting field edits, from the "parameter name" line of its tooltip, or empty. +std::string option_key_of(wxWindow* w); +// The label of the setting `key` from its definition, in the UI language; empty for an unknown key or one +// without a label. +std::string option_label(const std::string& key); +// A window's name when it says more than the name wx gives every window of its class, else empty. +std::string meaningful_name(wxWindow* w); + +// An option of a selector Orca builds of ::Button options: RadioGroup, TabCtrl and MultiSwitchButton. +// Pressing the option only selects it. +struct SelectorOption +{ + wxWindow* selector = nullptr; // null when the window is no selector's option + int index = -1; + bool selected = false; +}; +SelectorOption selector_option(wxWindow* w); +// The text a selector shows for its option `button`: its label, or for an icon option its tooltip. +// Both the message and label lookup (dialog_button_by_label()) name the option by it. +std::string selector_option_label(wxWindow* button); +// The options a selector window offers and the selected one (-1 for none): RadioGroup, TabCtrl, +// MultiSwitchButton, a SwitchButton with a label at each end, and a notebook whose pages have titles. +// nullopt for any other window. +struct SelectorChoices +{ + std::vector options; + int selected = -1; +}; +std::optional selector_choices(wxWindow* w); + // Rows of the lists ui_snapshot reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and -// wxCheckListBox, Orca's DropDown, wxGrid (read-only) and the Design tab's DesignRowList. Empty for -// other windows. -std::vector list_rows(wxWindow* list); +// wxCheckListBox, wxListCtrl, Orca's DropDown, wxGrid (read-only) and the Design tab's DesignRowList. +// Empty for other windows. With a `limit`, only shown rows are read (a tree's collapsed branches are +// skipped), and at most `limit` of them: what a summary of the list costs, whatever its size. +std::vector list_rows(wxWindow* list, std::size_t limit = std::numeric_limits::max()); bool is_row_list(wxWindow* w); // The names a row's cell is picked by (`column`): header text, "#n" for a column without one, and for // the object list, which shows no header, fixed English names. Empty for lists without columns. diff --git a/src/slic3r/GUI/Mcp/UiRefs.cpp b/src/slic3r/GUI/Mcp/UiRefs.cpp index 38ed006efa..cea2436fde 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.cpp +++ b/src/slic3r/GUI/Mcp/UiRefs.cpp @@ -79,7 +79,7 @@ std::string format_snapshot(const std::vector& nodes, std::size_t omitte if (!n.window.empty()) out += " in \"" + n.window + "\""; if (n.checked >= 0) - out += n.checked ? " [checked]" : " [unchecked]"; + out += n.checked == 2 ? " [mixed]" : n.checked ? " [checked]" : " [unchecked]"; if (!n.enabled) out += " [disabled]"; if (n.focused) diff --git a/src/slic3r/GUI/Mcp/UiRefs.hpp b/src/slic3r/GUI/Mcp/UiRefs.hpp index 413ef3b349..4dceed1060 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.hpp +++ b/src/slic3r/GUI/Mcp/UiRefs.hpp @@ -38,7 +38,7 @@ struct UiNode std::string note; // anything else worth saying, e.g. "clipped" bool enabled = true; bool focused = false; - int checked = -1; // -1 not checkable, 0/1 state + int checked = -1; // -1 not checkable, 0/1 state, 2 neither (checked_of()) int depth = 0; int x = 0, y = 0, w = 0, h = 0; // client coordinates in the parent window / canvas }; diff --git a/src/slic3r/GUI/Mcp/WebPages.cpp b/src/slic3r/GUI/Mcp/WebPages.cpp index 9c97f456ab..facfdef676 100644 --- a/src/slic3r/GUI/Mcp/WebPages.cpp +++ b/src/slic3r/GUI/Mcp/WebPages.cpp @@ -667,10 +667,16 @@ private: { wxDialog* dialog = m_dialog.get(); if (m_fallback != wxID_NONE && dialog != nullptr && m_tracker.top() == dialog) { - m_tracker.count_use(m_layer, m_pattern, m_label); - BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << m_pattern << "\": the page of \"" << title() << "\" " << why - << " for \"" << m_label << "\"; ended the dialog with " << m_label; - press_dialog_button(dialog, m_fallback); + const std::string dialog_title = title(); + if (const DialogPress press = press_dialog_button(dialog, m_fallback); press == DialogPress::Disabled || press == DialogPress::Hidden) + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << m_pattern << "\": the page of \"" << dialog_title << "\" " << why + << " for \"" << m_label << "\", and its " << m_label << " button is " + << (press == DialogPress::Hidden ? "not shown" : "disabled") << "; gave up"; + else { + m_tracker.count_use(m_layer, m_pattern, m_label); + BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << m_pattern << "\": the page of \"" << dialog_title << "\" " << why + << " for \"" << m_label << "\"; ended the dialog with " << m_label; + } } else BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << m_pattern << "\": the page of \"" << title() << "\" " << why << " for \"" << m_label << "\"; gave up"; diff --git a/src/slic3r/GUI/ReleaseNote.cpp b/src/slic3r/GUI/ReleaseNote.cpp index e7b70ab88a..9af36b676e 100644 --- a/src/slic3r/GUI/ReleaseNote.cpp +++ b/src/slic3r/GUI/ReleaseNote.cpp @@ -18,6 +18,8 @@ #include "slic3r/GUI/wxExtensions.hpp" #include "slic3r/GUI/Widgets/Label.hpp" #include "slic3r/GUI/Widgets/Button.hpp" +#include "slic3r/GUI/Widgets/TextInput.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" #include #include "slic3r/GUI/Printer/PrinterFileSystem.h" #include @@ -1494,6 +1496,7 @@ InputIpAddressDialog::InputIpAddressDialog(wxWindow *parent) m_tips_access_code->SetMaxSize(wxSize(FromDIP(168), -1)); m_input_access_code = new TextInput(ip_input_top_panel, wxEmptyString, wxEmptyString); + m_input_access_code->SetName(Mcp::kSecretField); m_input_access_code->Bind(wxEVT_TEXT, &InputIpAddressDialog::on_text, this); m_input_access_code->SetMinSize(wxSize(FromDIP(168), FromDIP(28))); m_input_access_code->SetMaxSize(wxSize(FromDIP(168), FromDIP(28))); diff --git a/src/slic3r/GUI/Widgets/SwitchButton.hpp b/src/slic3r/GUI/Widgets/SwitchButton.hpp index 7444420c8c..24a9733b1b 100644 --- a/src/slic3r/GUI/Widgets/SwitchButton.hpp +++ b/src/slic3r/GUI/Widgets/SwitchButton.hpp @@ -30,6 +30,10 @@ public: public: void SetLabels(wxString const & lbl_on, wxString const & lbl_off); + // The label shown at the left (0) or right (1) end; the thumb sits on the right one while the switch + // is on. Empty for a switch without labels. + const wxString& GetLabelAt(int index) const { return labels[index == 0 ? 0 : 1]; } + void SetTextColor(StateColor const &color); void SetTextColor2(StateColor const &color); diff --git a/src/slic3r/GUI/Widgets/TabCtrl.hpp b/src/slic3r/GUI/Widgets/TabCtrl.hpp index f80a1aa08c..428328be22 100644 --- a/src/slic3r/GUI/Widgets/TabCtrl.hpp +++ b/src/slic3r/GUI/Widgets/TabCtrl.hpp @@ -52,6 +52,8 @@ public: virtual void Rescale(); wxString GetItemText(unsigned int item) const; + // The button that shows tab `item`, or null. + Button* GetItemButton(unsigned int item) const { return item < btns.size() ? btns[item] : nullptr; } void SetItemText(unsigned int item, wxString const& value); void SetItemBitmap(unsigned int item, const wxBitmap& bitmap); diff --git a/tests/slic3rutils/test_mcp_results.cpp b/tests/slic3rutils/test_mcp_results.cpp index 414ade9af8..8306b9d4dd 100644 --- a/tests/slic3rutils/test_mcp_results.cpp +++ b/tests/slic3rutils/test_mcp_results.cpp @@ -54,23 +54,40 @@ #include #include +#include #include +#include #include +#include #include #include #include #include #include #include +#include #include #include #include +#include +#include +#include #include #include #include +#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include @@ -80,9 +97,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -960,6 +979,13 @@ TEST_CASE("snapshot text shows a row's value, check state and note", "[Mcp]") " [r2] row \"Cube\" = \"1\" [object 0, selected]\n" " [r3] row \"Cylinder\" [checked] [object 0 part 1, modifier]\n" " [r4] row \"Brim\" [checked] [disabled]\n"); + // A checkbox that shows neither state. + UiNode mixed; + mixed.ref = "w5"; + mixed.kind = "toggle"; + mixed.label = "Detach"; + mixed.checked = 2; + CHECK(format_snapshot({mixed}, 0) == "[w5] toggle \"Detach\" [mixed]\n"); } namespace { @@ -1220,6 +1246,785 @@ TEST_CASE("a click on a row selects it as a person's does and tells its owner on } } +TEST_CASE("a list control's rows are listed with their columns and picked as a click picks them", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxFrame frame(nullptr, wxID_ANY, "hosts", wxDefaultPosition, wxSize(640, 520)); + auto* hosts = new wxListView(&frame, wxID_ANY, wxPoint(0, 0), wxSize(400, 300)); + hosts->AppendColumn("Address"); + hosts->AppendColumn("Hostname"); + hosts->InsertItem(0, "192.168.1.10"); + hosts->SetItem(0, 1, "x1c"); + hosts->InsertItem(1, "192.168.1.11"); + hosts->SetItem(1, 1, "p1s"); + frame.Show(); + + CHECK(kind_of(hosts) == "list"); + CHECK(is_row_list(hosts)); + CHECK(list_columns(hosts) == std::vector{"Address", "Hostname"}); + const std::vector rows = list_rows(hosts); + REQUIRE(rows.size() == 2); + CHECK(rows[1].path == std::vector{"192.168.1.11"}); + CHECK(rows[1].value == "p1s"); + CHECK_FALSE(rows[1].selected); + CHECK(list_rows(hosts, 1).size() == 1); + + // The list tells its owner of the pick, as a person's click makes it do. + long selected = -1, activated = -1; + hosts->Bind(wxEVT_LIST_ITEM_SELECTED, [&selected](wxListEvent& e) { selected = e.GetIndex(); }); + hosts->Bind(wxEVT_LIST_ITEM_ACTIVATED, [&activated](wxListEvent& e) { activated = e.GetIndex(); }); + const nlohmann::json out = click_row(*hosts, row_of(*hosts, {"192.168.1.11"}), "", ClickOptions{}); + CHECK(out["selected"] == nlohmann::json{"192.168.1.11"}); + CHECK(selected == 1); + CHECK(activated == -1); + ClickOptions twice; + twice.double_click = true; + click_row(*hosts, row_of(*hosts, {"192.168.1.10"}), "", twice); + CHECK(selected == 0); + CHECK(activated == 0); + CHECK(hosts->GetSelectedItemCount() == 1); + CHECK_THROWS_AS(input_row(*hosts, row_of(*hosts, {"192.168.1.10"}), "", true), ToolFailure); + } +} + +namespace { + +bool has(const std::string& text, const std::string& part) { return text.find(part) != std::string::npos; } + +} // namespace + +TEST_CASE("a modal dialog's message reads its fields, choices, toggles and lists as they show", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxDialog dialog(nullptr, wxID_ANY, "Save preset"); + auto* top = new wxBoxSizer(wxVERTICAL); + auto row = [&](std::initializer_list windows) { + auto* line = new wxBoxSizer(wxHORIZONTAL); + for (wxWindow* w : windows) + line->Add(w, 0, wxALL, 4); + top->Add(line); + }; + auto stacked = [&](wxWindow* w) { + top->Add(w, 0, wxALL, 4); + return w; + }; + + // A field beside its label, and one created before the label above it. + row({new wxStaticText(&dialog, wxID_ANY, "Name"), new wxTextCtrl(&dialog, wxID_ANY, "Generic PLA", wxDefaultPosition, wxSize(160, -1))}); + auto* diameter = new wxTextCtrl(&dialog, wxID_ANY, "0.4"); + stacked(new wxStaticText(&dialog, wxID_ANY, "Nozzle diameter")); + stacked(diameter); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "line one\nline two", wxDefaultPosition, wxSize(200, 60), wxTE_MULTILINE | wxTE_READONLY)); + + // Secrets: by style, by the dialog's name for the field, by the setting the field edits. + stacked(new wxTextCtrl(&dialog, wxID_ANY, "hunter2", wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD)); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "12345678"))->SetName(kSecretField); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "abcdef"))->SetToolTip("parameter name: printhost_apikey"); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "user:pw@printer.local"))->SetToolTip("parameter name: print_host"); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "http://me:pw@host/api?token=x")); + stacked(new wxTextCtrl(&dialog, wxID_ANY, "http://bob:pw2@host ")); + stacked(new wxTextCtrl(&dialog, wxID_ANY, " carol:pw3@printer.local"))->SetToolTip("parameter name: print_host_webui"); + + auto* remember = new wxCheckBox(&dialog, wxID_ANY, "Don't show again"); + remember->SetValue(true); + stacked(remember); + auto* detach = new wxCheckBox(&dialog, wxID_ANY, "Detach", wxDefaultPosition, wxDefaultSize, wxCHK_3STATE); + detach->Set3StateValue(wxCHK_UNDETERMINED); + stacked(detach); + // Toggles with no label of their own, as Orca's CheckBox and RadioBox are; two of them made + // before their labels. + const wxBitmap mark(16, 16); + auto* choice_toggle = new wxBitmapToggleButton(&dialog, wxID_ANY, mark); + choice_toggle->SetValue(true); + row({choice_toggle, new wxStaticText(&dialog, wxID_ANY, "Remember my choice")}); + auto* plate_a = new wxBitmapToggleButton(&dialog, wxID_ANY, mark); + auto* plate_b = new wxBitmapToggleButton(&dialog, wxID_ANY, mark); + plate_b->SetValue(true); + auto* label_a = new wxStaticText(&dialog, wxID_ANY, "Plate A"); + auto* label_b = new wxStaticText(&dialog, wxID_ANY, "Plate B"); + row({plate_a, label_a}); + row({plate_b, label_b}); + + auto* user = new wxRadioButton(&dialog, wxID_ANY, "User preset", wxDefaultPosition, wxDefaultSize, wxRB_GROUP); + auto* project = new wxRadioButton(&dialog, wxID_ANY, "Project preset"); + project->SetValue(true); + row({user, project}); + const wxString choices[] = {"A", "B"}; + auto* choice = new wxChoice(&dialog, wxID_ANY, wxDefaultPosition, wxDefaultSize, 2, choices); + choice->SetSelection(1); + stacked(choice); + auto* copies = new wxSpinCtrl(&dialog, wxID_ANY); + copies->SetValue(3); + stacked(copies); + auto* progress = new wxGauge(&dialog, wxID_ANY, 200); + progress->SetValue(90); + stacked(progress); + auto* disabled = new wxTextCtrl(&dialog, wxID_ANY, "0.000"); + disabled->Disable(); + stacked(disabled); + + auto* box = new wxStaticBox(&dialog, wxID_ANY, "Settings"); + auto* boxed = new wxStaticBoxSizer(box, wxVERTICAL); + boxed->Add(new wxStaticText(box, wxID_ANY, "Inside the box")); + top->Add(boxed); + + auto* book = new wxNotebook(&dialog, wxID_ANY); + auto* general = new wxPanel(book); + new wxStaticText(general, wxID_ANY, "General page"); + auto* advanced = new wxPanel(book); + new wxStaticText(advanced, wxID_ANY, "Advanced page"); + book->AddPage(general, "General"); + book->AddPage(advanced, "Advanced", true); + stacked(book); + + const wxString filaments[] = {"PLA", "PETG"}; + auto* checks = new wxCheckListBox(&dialog, wxID_ANY, wxDefaultPosition, wxDefaultSize, 2, filaments); + checks->Check(0); + stacked(checks); + auto* hosts = new wxListView(&dialog, wxID_ANY, wxDefaultPosition, wxSize(300, 150)); + hosts->AppendColumn("Address"); + hosts->AppendColumn("Hostname"); + for (int i = 0; i < 30; ++i) { + hosts->InsertItem(i, "192.168.1." + std::to_string(i)); + hosts->SetItem(i, 1, "printer" + std::to_string(i)); + } + stacked(hosts); + + auto* ok = new wxButton(&dialog, wxID_OK, "OK"); + ok->Disable(); + row({ok, new wxButton(&dialog, wxID_CANCEL, "Cancel")}); + dialog.SetSizerAndFit(top); + + // A dialog of its own is described on its own. + wxDialog nested(&dialog, wxID_ANY, "Nested"); + new wxStaticText(&nested, wxID_ANY, "Nested text"); + nested.Show(); + + const nlohmann::json described = describe_dialog(&dialog); + const std::string message = described["message"].get(); + INFO(message); + CHECK(has(message, "Name | [Generic PLA]")); + CHECK(has(message, "Nozzle diameter\n[0.4]")); + CHECK(has(message, "line one\nline two")); + CHECK(has(message, "[******]")); + CHECK_FALSE(has(message, "hunter2")); + CHECK_FALSE(has(message, "12345678")); + CHECK_FALSE(has(message, "abcdef")); + CHECK(has(message, "[REDACTED:REDACTED@printer.local]")); + CHECK_FALSE(has(message, ":pw@")); + CHECK_FALSE(has(message, "token=x")); + CHECK_FALSE(has(message, "pw2")); + CHECK_FALSE(has(message, "pw3")); + CHECK(has(message, "[http://REDACTED:REDACTED@host ]")); + CHECK(has(message, "[x] Don't show again")); + CHECK(has(message, "[-] Detach")); + CHECK(has(message, "[x] Remember my choice")); + CHECK(has(message, "[ ] Plate A")); + CHECK(has(message, "[x] Plate B")); + CHECK(has(message, "( ) User preset | (*) Project preset")); + CHECK(has(message, "[B ▾]")); + CHECK(has(message, "[3]")); + CHECK(has(message, "[45%]")); + CHECK(has(message, "[0.000] (disabled)")); + CHECK_FALSE(has(message, "[Generic PLA] (disabled)")); + CHECK(has(message, "Settings\nInside the box")); + CHECK(has(message, "( ) General | (*) Advanced\nAdvanced page")); + CHECK_FALSE(has(message, "General page")); + CHECK(has(message, "- [x] PLA\n- [ ] PETG")); + CHECK(has(message, "- 192.168.1.0 | printer0")); + CHECK(has(message, "- 192.168.1.24 | printer24\n- … more rows")); + CHECK_FALSE(has(message, "printer25")); + CHECK_FALSE(has(message, "Nested text")); + CHECK(described["buttons"] == + nlohmann::json::array({{{"id", wxID_OK}, {"label", "OK"}, {"enabled", false}}, {{"id", wxID_CANCEL}, {"label", "Cancel"}}})); + + // Under another modal the dialog is disabled as a whole, which leaves its controls as they read. + dialog.Disable(); + const std::string under = describe_dialog(&dialog)["message"].get(); + CHECK(has(under, "Name | [Generic PLA]")); + CHECK_FALSE(has(under, "[Generic PLA] (disabled)")); + dialog.Enable(); + nested.Hide(); + } +} + +TEST_CASE("a dialog's cells read in rows, and the cells side by side in a row join", "[Mcp]") +{ + auto cell = [](int x, int y, int w, int h, const std::string& text, bool toggle = false) { + MessageCell c; + c.rect = wxRect(x, y, w, h); + c.text = text; + c.toggle = toggle; + return c; + }; + // Radio boxes made before their labels each take the label on their row. + std::vector out = layout_cells({cell(0, 0, 16, 16, "(*)", true), cell(0, 30, 16, 16, "( )", true), + cell(20, 0, 100, 16, "Textured PEI"), cell(20, 30, 100, 16, "Smooth PEI")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "(*) Textured PEI"); + CHECK_FALSE(out[0].toggle); + CHECK(out[1].text == "( ) Smooth PEI"); + // A table's header and rows, each cell in a panel of its own, read a row to a line. + out = layout_cells({cell(0, 0, 100, 20, "Settings"), cell(100, 0, 60, 20, "Old Value"), cell(160, 0, 60, 20, "New Value"), + cell(0, 20, 100, 20, "Layer height"), cell(100, 20, 60, 20, "0.2"), cell(160, 20, 60, 20, "0.28")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "Settings | Old Value | New Value"); + CHECK(out[1].text == "Layer height | 0.2 | 0.28"); + // A label's trailing spaces don't widen the separator. + out = layout_cells({cell(0, 0, 80, 20, "Start PA: "), cell(100, 0, 60, 20, "[0]")}); + REQUIRE(out.size() == 1); + CHECK(out[0].text == "Start PA: | [0]"); + // A label above its field reads first, whichever was made first. + out = layout_cells({cell(0, 20, 80, 20, "[0.4]"), cell(0, 0, 80, 16, "Nozzle diameter")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "Nozzle diameter"); + CHECK(out[1].text == "[0.4]"); + // A toggle takes a label of several lines; such a label joins nothing else. + out = layout_cells({cell(0, 0, 16, 16, "[x]", true), cell(20, 0, 200, 40, "Long\nlabel"), cell(230, 0, 50, 16, "after")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "[x] Long\nlabel"); + CHECK(out[1].text == "after"); + // A toggle's suffix follows its label; two toggles side by side don't take each other. + MessageCell disabled = cell(0, 0, 16, 16, "[ ]", true); + disabled.suffix = " (disabled)"; + out = layout_cells({disabled, cell(20, 0, 16, 16, "[x]", true), cell(40, 0, 80, 16, "Time-lapse")}); + REQUIRE(out.size() == 2); + CHECK(out[0].toggle); + CHECK(out[1].text == "[x] Time-lapse"); + // A tall block beside a column of label and field rows leaves those rows as they are. + out = layout_cells({cell(0, 0, 100, 200, "About\nthese"), cell(120, 10, 60, 20, "Width"), cell(200, 10, 60, 20, "[200]"), + cell(120, 40, 60, 20, "Depth"), cell(200, 40, 60, 20, "[250]")}); + REQUIRE(out.size() == 3); + CHECK(out[0].text == "About\nthese"); + CHECK(out[1].text == "Width | [200]"); + CHECK(out[2].text == "Depth | [250]"); + // A checkbox with its own label is no label for the unlabelled one before it. + MessageCell detach = cell(20, 0, 100, 16, "[x] Detach"); + detach.marked = true; + out = layout_cells({cell(0, 0, 16, 16, "[ ]", true), detach}); + REQUIRE(out.size() == 2); + CHECK(out[0].toggle); + CHECK(out[1].text == "[x] Detach"); + // A checkbox and its label, once joined, are no label for a second checkbox after them. + out = layout_cells({cell(0, 0, 16, 16, "[ ]", true), cell(20, 0, 60, 16, "Detach"), cell(90, 0, 16, 16, "[x]", true)}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "[ ] Detach"); + CHECK(out[0].marked); + CHECK(out[1].toggle); + // Beside a one-line tall cell, the band is the shorter cell's height: a field at its top shares + // its row, one a field's height lower does not. + out = layout_cells({cell(160, 10, 80, 20, "[5]"), cell(0, 0, 150, 200, "Preview")}); + REQUIRE(out.size() == 1); + CHECK(out[0].text == "Preview | [5]"); + out = layout_cells({cell(160, 20, 80, 20, "[5]"), cell(0, 0, 150, 200, "Preview")}); + REQUIRE(out.size() == 2); + out = layout_cells({cell(160, 30, 80, 20, "[5]"), cell(0, 0, 150, 200, "Preview")}); + REQUIRE(out.size() == 2); + // A field below a ten-line block's first line keeps its own row, however tall the field. + out = layout_cells({cell(0, 0, 150, 200, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"), cell(160, 20, 80, 40, "[5]")}); + REQUIRE(out.size() == 2); + CHECK(out[1].text == "[5]"); + // Rows closer together than the tall block's first lines stay rows of their own too. + out = layout_cells({cell(0, 0, 100, 200, "About\nthese"), cell(120, 0, 60, 20, "Width"), cell(200, 0, 60, 20, "[200]"), + cell(120, 25, 60, 20, "Depth"), cell(200, 25, 60, 20, "[250]")}); + REQUIRE(out.size() == 3); + CHECK(out[1].text == "Width | [200]"); + CHECK(out[2].text == "Depth | [250]"); + // A field beside a wrapped label's first line shares its row, so the two read left to right, also + // with a top margin of up to half its own height. + out = layout_cells({cell(160, 10, 80, 20, "[5]"), cell(0, 0, 150, 60, "Long\nwrapped label")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "Long\nwrapped label"); + CHECK(out[1].text == "[5]"); + out = layout_cells({cell(160, 0, 80, 20, "[5]"), cell(0, 0, 150, 60, "Long\nwrapped label")}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "Long\nwrapped label"); + CHECK(out[1].text == "[5]"); + // A checkbox at a wrapped label's first line, or centred on it, takes it; one at its third line doesn't. + out = layout_cells({cell(0, 0, 16, 16, "[x]", true), cell(20, 0, 200, 60, "A label\nwrapped over\nthree lines")}); + REQUIRE(out.size() == 1); + CHECK(out[0].text == "[x] A label\nwrapped over\nthree lines"); + out = layout_cells({cell(0, 22, 16, 16, "[x]", true), cell(20, 0, 200, 60, "A label\nwrapped over\nthree lines")}); + REQUIRE(out.size() == 1); + out = layout_cells({cell(0, 42, 16, 16, "[x]", true), cell(20, 0, 200, 60, "A label\nwrapped over\nthree lines")}); + REQUIRE(out.size() == 2); + CHECK(out[1].toggle); + // A switch centred on a title and its hint takes the title, as RecordingDialog lays them out. + out = layout_cells({cell(0, 0, 200, 19, "Highlight the pointer"), cell(0, 21, 300, 16, "A ring follows the pointer."), + cell(400, 8, 40, 22, "[ ]", true)}); + REQUIRE(out.size() == 2); + CHECK(out[0].text == "Highlight the pointer | [ ]"); + CHECK(out[1].text == "A ring follows the pointer."); + // A toggle with nothing to its right takes the label to its left, as Preferences lays out its rows. + out = layout_cells({cell(0, 0, 150, 20, "Show splash screen"), cell(200, 2, 16, 16, "[x]", true)}); + REQUIRE(out.size() == 1); + CHECK(out[0].text == "Show splash screen | [x]"); + CHECK_FALSE(out[0].toggle); + // Cells not laid out yet overlap at the origin: they keep their order, and none joins another. + out = layout_cells({cell(0, 0, 80, 20, "one"), cell(0, 0, 80, 20, "two"), cell(0, 0, 16, 16, "[x]", true)}); + REQUIRE(out.size() == 3); + CHECK(out[0].text == "one"); + CHECK(out[1].text == "two"); + CHECK(out[2].toggle); + + CHECK(selector_line({"Open as project", "Import geometry only"}, 1) == "( ) Open as project | (*) Import geometry only"); + CHECK(selector_line({"Left Nozzle", "Right Nozzle"}, -1) == "( ) Left Nozzle | ( ) Right Nozzle"); + CHECK(is_secret_key("printhost_password")); + CHECK(is_secret_key("printhost_apikey")); + CHECK_FALSE(is_secret_key("print_host")); + CHECK_FALSE(is_secret_key("layer_height")); +} + +TEST_CASE("a disabled or hidden button is neither pressed nor ends its dialog, and a rule naming it is not counted", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxDialog dialog(nullptr, wxID_ANY, "Save preset"); + int presses = 0; + auto* ok = new wxButton(&dialog, wxID_OK, "OK"); + ok->Bind(wxEVT_BUTTON, [&presses](wxCommandEvent&) { ++presses; }); + ok->Disable(); + CHECK(refused_press(&dialog, wxID_OK) == DialogPress::Disabled); + CHECK_FALSE(has_dialog_button(&dialog, wxID_OK)); + CHECK(press_dialog_button(&dialog, wxID_OK) == DialogPress::Disabled); + CHECK(presses == 0); + CHECK(dialog.GetReturnCode() != wxID_OK); + + // Named by a rule, it is not pressed once the dialog's loop runs, and the rule is not counted. + { + ModalTracker tracker; + tracker.push_rules({make_rule("Save preset", "ok")}); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(presses == 0); + CHECK(tracker.rules_json()[0]["uses"] == 0); + wxModalDialogHook::CallExit(&dialog); + } + + ok->Enable(); + CHECK_FALSE(refused_press(&dialog, wxID_OK).has_value()); + CHECK(press_dialog_button(&dialog, wxID_OK) == DialogPress::Pressed); + CHECK(presses == 1); + + // A wizard's Finish on a page it does not show yet is not pressed, nor found by its label; its + // Cancel there ends the dialog as a dialog without one ends. + wxDialog wizard(nullptr, wxID_ANY, "Wizard"); + auto* pages = new wxSimplebook(&wizard); + auto* first = new wxPanel(pages); + new wxStaticText(first, wxID_ANY, "Step 1"); + auto* last = new wxPanel(pages); + int finishes = 0; + auto* finish = new wxButton(last, wxID_OK, "Finish"); + finish->Bind(wxEVT_BUTTON, [&finishes](wxCommandEvent&) { ++finishes; }); + new wxButton(last, wxID_CANCEL, "Cancel"); + pages->AddPage(first, ""); + pages->AddPage(last, ""); + pages->SetSelection(0); + CHECK(refused_press(&wizard, wxID_OK) == DialogPress::Hidden); + CHECK(dialog_button_by_label(&wizard, "Finish") == wxID_NONE); + CHECK(press_dialog_button(&wizard, wxID_OK) == DialogPress::Hidden); + CHECK(finishes == 0); + CHECK_FALSE(refused_press(&wizard, wxID_CANCEL).has_value()); + CHECK(describe_dialog(&wizard)["buttons"].empty()); + pages->SetSelection(1); + CHECK(dialog_button_by_label(&wizard, "Finish") == wxID_OK); + CHECK(press_dialog_button(&wizard, wxID_OK) == DialogPress::Pressed); + CHECK(finishes == 1); + pages->SetSelection(0); + CHECK(press_dialog_button(&wizard, wxID_CANCEL) == DialogPress::Ended); + CHECK(wizard.GetReturnCode() == wxID_CANCEL); + + // A popup's or a nested dialog's buttons are not the dialog's. + wxDialog host(nullptr, wxID_ANY, "Host"); + auto* popup = new wxPopupWindow(&host); + int popped = 0; + auto* popup_cancel = new wxButton(popup, wxID_CANCEL, "Cancel"); + popup_cancel->Bind(wxEVT_BUTTON, [&popped](wxCommandEvent&) { ++popped; }); + popup->Show(); + wxDialog nested(&host, wxID_ANY, "Nested"); + new wxButton(&nested, wxID_APPLY, "Nested apply"); + nested.Show(); + CHECK(dialog_button_by_label(&host, "Cancel") == wxID_NONE); + CHECK(dialog_button_by_label(&host, "Nested apply") == wxID_NONE); + CHECK_FALSE(has_dialog_button(&host, wxID_CANCEL)); + CHECK_FALSE(refused_press(&host, wxID_APPLY).has_value()); + CHECK(describe_dialog(&host)["buttons"].empty()); + CHECK(popped == 0); + popup->Hide(); + nested.Hide(); + + // A message box that is not shown can't be pressed. + wxMessageDialog box(nullptr, "Continue?", "Question", wxOK | wxCANCEL); + CHECK_FALSE(refused_press(&box, wxID_OK).has_value()); +#if defined(_WIN32) || defined(__WXGTK__) + CHECK(press_dialog_button(&box, wxID_OK) == DialogPress::Failed); +#endif + } +} + +TEST_CASE("a childless window is a control by the label it shows, not by a default name", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxDialog dialog(nullptr, wxID_ANY, "Kinds"); + // Windows shows a bare panel's name as its text. + auto* bare = new wxPanel(&dialog); + bare->SetLabel("panel"); + CHECK(kind_of(bare).empty()); + auto* titled = new wxWindow(&dialog, wxID_ANY); + titled->SetLabel("Settings"); + CHECK(kind_of(titled) == "control"); + // A label the window is also named after is still its label. + auto* named = new wxWindow(&dialog, wxID_ANY); + named->SetName("Advanced"); + named->SetLabel("Advanced"); + CHECK(kind_of(named) == "control"); + CHECK(meaningful_name(named) == "Advanced"); + CHECK(meaningful_name(bare).empty()); + // Every class's default name, a gauge's and a tree's too. + auto* gauge = new wxGauge(&dialog, wxID_ANY, 100); + CHECK(kind_of(gauge) != "control"); + auto* tree_named = new wxWindow(&dialog, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, "treeCtrl"); + tree_named->SetLabel("treeCtrl"); + CHECK(kind_of(tree_named).empty()); + // A section title that happens to be another class's default name is still a title. + auto* section = new wxWindow(&dialog, wxID_ANY); + section->SetLabel("Text"); + CHECK(kind_of(section) == "control"); + } +} + +TEST_CASE("a rule answers a message box only with a button the box has", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + ModalTracker tracker; + tracker.push_rules({make_rule("Discard", "ok")}); + wxMessageDialog yes_no(nullptr, "Discard the changes?", "Changes", wxYES_NO); + // A Yes/No box has no OK: it opens for an answer instead. + CHECK(wxModalDialogHook::CallEnter(&yes_no) == wxID_NONE); + CHECK(tracker.top() == &yes_no); + CHECK(tracker.rules_json()[0]["uses"] == 0); + wxModalDialogHook::CallExit(&yes_no); + tracker.push_rules({make_rule("Discard", "no")}); + CHECK(wxModalDialogHook::CallEnter(&yes_no) == wxID_NO); + CHECK(tracker.top() == nullptr); + // Cancel answers a box with a Cancel button, not an OK-only one. + tracker.push_rules({make_rule("Saved", "cancel")}); + wxMessageDialog ok_only(nullptr, "Saved.", "Info", wxOK); + CHECK(wxModalDialogHook::CallEnter(&ok_only) == wxID_NONE); + wxModalDialogHook::CallExit(&ok_only); + wxMessageDialog ok_cancel(nullptr, "Saved. Open it?", "Info", wxOK | wxCANCEL); + CHECK(wxModalDialogHook::CallEnter(&ok_cancel) == wxID_CANCEL); + } +} + +TEST_CASE("a long label is cut where a character starts, and a toggle's tooltip name stays whole", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + std::string tip; + for (int i = 0; i < 31; ++i) + tip += "\xF0\x9F\x98\x80"; + wxDialog dialog(nullptr, wxID_ANY, "Overlay"); + auto* toggle = new wxBitmapToggleButton(&dialog, wxID_ANY, wxBitmap(16, 16)); + toggle->SetToolTip(wxString::FromUTF8(tip)); + // ui_snapshot's label is cut at 120 bytes, where a character starts. + const std::string label = label_of(toggle); + CHECK(label.size() < tip.size()); + CHECK(label.substr(label.size() - 3) == "..."); + CHECK((label.size() - 3) % 4 == 0); + CHECK_NOTHROW(nlohmann::json(label).dump()); + // The message names the toggle by its whole tooltip. + const nlohmann::json described = describe_dialog(&dialog); + CHECK_NOTHROW(described.dump()); + CHECK(has(described["message"].get(), "[ ] " + tip)); + } +} + +namespace { + +// A label that can't be read, as a widget in a bad state might fail. +class FailingLabel final : public wxStaticText +{ +public: + explicit FailingLabel(wxWindow* parent) : wxStaticText(parent, wxID_ANY, "label") {} + wxString GetLabel() const override { throw std::runtime_error("unreadable"); } +}; + +} // namespace + +TEST_CASE("a toggle left without a label is named by its own tooltip, not by its neighbour's label", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + // Two switches and one label: the first takes it, the second its tooltip. + wxDialog dialog(nullptr, wxID_ANY, "Switches"); + auto* row = new wxBoxSizer(wxHORIZONTAL); + auto* first = new wxBitmapToggleButton(&dialog, wxID_ANY, wxBitmap(16, 16)); + auto* label = new wxStaticText(&dialog, wxID_ANY, "Detach"); + auto* second = new wxBitmapToggleButton(&dialog, wxID_ANY, wxBitmap(16, 16)); + second->SetToolTip("Keep the original"); + row->Add(first, 0, wxALL, 4); + row->Add(label, 0, wxALL, 4); + row->Add(second, 0, wxALL, 4); + dialog.SetSizerAndFit(row); + const std::string message = describe_dialog(&dialog)["message"].get(); + INFO(message); + CHECK(has(message, "[ ] Detach")); + CHECK(has(message, "[ ] Keep the original")); + CHECK(message.find("Detach") == message.rfind("Detach")); + + // A setting's toggle whose setting has no label beside a wrapped label it can't take: named by + // its window name, not by that label. + wxDialog setting(nullptr, wxID_ANY, "Setting"); + auto* line = new wxBoxSizer(wxHORIZONTAL); + auto* text = new wxStaticText(&setting, wxID_ANY, "Wrapped\nneighbour"); + auto* toggle = new wxBitmapToggleButton(&setting, wxID_ANY, wxBitmap(16, 16), wxDefaultPosition, wxDefaultSize, 0, + wxDefaultValidator, "unlisted_toggle"); + toggle->SetToolTip("parameter name: not_a_setting"); + line->Add(text, 0, wxALL, 4); + line->Add(toggle, 0, wxALL, 4); + setting.SetSizerAndFit(line); + const std::string read = describe_dialog(&setting)["message"].get(); + INFO(read); + CHECK(has(read, "[ ] (unlisted_toggle)")); + CHECK(read.find("neighbour") == read.rfind("neighbour")); + } +} + +TEST_CASE("a button is found by the label its dialog's description shows", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + // "&&" is a literal "&": the description shows "Save & close", and that label finds it. + wxDialog dialog(nullptr, wxID_ANY, "Labels"); + new wxButton(&dialog, 5200, "Save && close"); + new wxButton(&dialog, 5201, "&Discard"); + const nlohmann::json buttons = describe_dialog(&dialog)["buttons"]; + REQUIRE(buttons.size() == 2); + CHECK(buttons[0]["label"] == "Save & close"); + CHECK(buttons[1]["label"] == "Discard"); + CHECK(dialog_button_by_label(&dialog, "Save & close") == 5200); + CHECK(dialog_button_by_label(&dialog, "discard") == 5201); + } +} + +TEST_CASE("a notebook's tabs are no label for a toggle beside them", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxDialog dialog(nullptr, wxID_ANY, "Tabs"); + auto* row = new wxBoxSizer(wxHORIZONTAL); + auto* toggle = new wxBitmapToggleButton(&dialog, wxID_ANY, wxBitmap(16, 16)); + auto* book = new wxNotebook(&dialog, wxID_ANY); + book->AddPage(new wxPanel(book), "General"); + book->AddPage(new wxPanel(book), "Advanced", true); + row->Add(toggle, 0, wxALL, 4); + row->Add(book, 0, wxALL, 4); + dialog.SetSizerAndFit(row); + const std::string message = describe_dialog(&dialog)["message"].get(); + INFO(message); + CHECK(has(message, "( ) General | (*) Advanced")); + CHECK_FALSE(has(message, "[ ] ( ) General")); + } +} + +TEST_CASE("a dialog that can't be described is still listed, by its title", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + ModalTracker tracker; + tracker.push_rules({make_rule("^Broken$", "cancel")}); + wxDialog dialog(nullptr, wxID_ANY, "Broken"); + new FailingLabel(&dialog); + int cancels = 0; + auto* cancel = new wxButton(&dialog, wxID_CANCEL, "Cancel"); + cancel->Bind(wxEVT_BUTTON, [&cancels](wxCommandEvent&) { ++cancels; }); + CHECK_THROWS(describe_dialog(&dialog)); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + CHECK(tracker.any_open()); + const nlohmann::json snap = tracker.snapshot(); + REQUIRE(snap.size() == 1); + CHECK(snap[0]["title"] == "Broken"); + // Its rule matches it by its title alone, and presses its button. + wxTheApp->ProcessPendingEvents(); + CHECK(cancels == 1); + wxModalDialogHook::CallExit(&dialog); + CHECK_FALSE(tracker.any_open()); + } +} + +TEST_CASE("ui_input false is refused on a selected radio button, which selecting another unselects", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + McpServicePtr service(new McpService()); + UiInspector inspector(*service); + wxFrame frame(nullptr, wxID_ANY, "radios"); + auto* first = new wxRadioButton(&frame, wxID_ANY, "First", wxPoint(0, 0), wxDefaultSize, wxRB_GROUP); + auto* second = new wxRadioButton(&frame, wxID_ANY, "Second", wxPoint(0, 30)); + first->SetValue(true); + UiTarget target; + target.kind = UiTarget::Kind::Window; + target.window = first; + CHECK_THROWS_AS(inspector.input(target, false, false), ToolFailure); + CHECK(first->GetValue()); + // One already unselected stays so. + target.window = second; + CHECK(inspector.input(target, false, false)["checked"] == false); + CHECK(inspector.input(target, true, false)["checked"] == true); + CHECK(second->GetValue()); + } +} + +TEST_CASE("a dialog's message is cut where a character starts", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + // 3000 bytes of a 3-byte character: the 2000-byte cut falls inside one. + std::string long_text; + for (int i = 0; i < 1000; ++i) + long_text += "\xE4\xB8\xAD"; + wxDialog dialog(nullptr, wxID_ANY, "Long"); + new wxStaticText(&dialog, wxID_ANY, wxString::FromUTF8(long_text)); + std::string text; + const nlohmann::json described = describe_dialog(&dialog, &text); + const std::string message = described["message"].get(); + REQUIRE(message.size() > 3); + CHECK(message.substr(message.size() - 3) == "..."); + CHECK((message.size() - 3) % 3 == 0); + CHECK_NOTHROW(described.dump()); + CHECK((text.size() - 3) % 3 == 0); + CHECK_NOTHROW(nlohmann::json(text).dump()); + } +} + +TEST_CASE("the snapshot read on the UI thread shows a dialog as it is now", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + ModalTracker tracker; + wxDialog dialog(nullptr, wxID_ANY, "Bind printer"); + auto* name = new wxStaticText(&dialog, wxID_ANY, ""); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + // What a dialog fills in once it shows. + name->SetLabel("Bambu Lab X1C"); + CHECK(tracker.snapshot()[0]["message"] == "Bambu Lab X1C"); + wxModalDialogHook::CallExit(&dialog); + CHECK(tracker.snapshot().empty()); + } +} + +TEST_CASE("a rule finds the dialog's own text past what its message holds", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + // A long G-code and a long list before the label fill the message; the label is still the + // dialog's text, as it always was. + wxDialog dialog(nullptr, wxID_ANY, "Edit Custom G-code"); + auto* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(new wxTextCtrl(&dialog, wxID_ANY, std::string(3000, 'G'), wxDefaultPosition, wxSize(300, 100), wxTE_MULTILINE)); + wxArrayString placeholders; + for (int i = 0; i < 100; ++i) + placeholders.Add("placeholder_" + std::to_string(i)); + sizer->Add(new wxListBox(&dialog, wxID_ANY, wxDefaultPosition, wxSize(300, 100), placeholders)); + sizer->Add(new wxStaticText(&dialog, wxID_ANY, "Select placeholder")); + int cancels = 0; + auto* cancel = new wxButton(&dialog, wxID_CANCEL, "Cancel"); + cancel->Bind(wxEVT_BUTTON, [&cancels](wxCommandEvent&) { ++cancels; }); + sizer->Add(cancel); + dialog.SetSizerAndFit(sizer); + + std::string text; + const nlohmann::json described = describe_dialog(&dialog, &text); + CHECK_FALSE(has(described["message"].get(), "Select placeholder")); + CHECK(has(text, "Select placeholder")); + // Its buttons are listed all the same. + CHECK(described["buttons"] == nlohmann::json::array({{{"id", wxID_CANCEL}, {"label", "Cancel"}}})); + + ModalTracker tracker; + tracker.push_rules({make_rule("Select placeholder", "cancel")}); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(cancels == 1); + CHECK(tracker.rules_json()[0]["uses"] == 1); + wxModalDialogHook::CallExit(&dialog); + } +} + TEST_CASE("a widget in a popup belongs to the window the popup opened from, which lists the popup after it", "[Mcp]") { #if defined(__linux__) diff --git a/tests/slic3rutils/test_mcp_web.cpp b/tests/slic3rutils/test_mcp_web.cpp index 7edc471f49..c3930d67cc 100644 --- a/tests/slic3rutils/test_mcp_web.cpp +++ b/tests/slic3rutils/test_mcp_web.cpp @@ -27,8 +27,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -38,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -266,19 +269,32 @@ TEST_CASE("a request script asks the page's agent, and installs it only when tol TEST_CASE("an auto-answer rule is searched in title and message, or in a lone title", "[Mcp]") { - // A web dialog has no message, so a rule anchored to its title matches it; one written for the + // A web dialog has no text, so a rule anchored to its title matches it; one written for the // "title\n" it was searched in before matches as it did. - CHECK(rule_matches(make_rule("^MCP web fixture$", "Submit"), "MCP web fixture", "")); - CHECK(rule_matches(make_rule("^MCP web fixture\\n$", "Submit"), "MCP web fixture", "")); - CHECK_FALSE(rule_matches(make_rule("^MCP web fixture$", "Submit"), "MCP web fixture window", "")); + CHECK(rule_matches(make_rule("^MCP web fixture$", "Submit"), "MCP web fixture", "", "")); + CHECK(rule_matches(make_rule("^MCP web fixture\\n$", "Submit"), "MCP web fixture", "", "")); + CHECK_FALSE(rule_matches(make_rule("^MCP web fixture$", "Submit"), "MCP web fixture window", "", "")); // Case aside. - CHECK(rule_matches(make_rule("^mcp WEB", "Submit"), "MCP web fixture", "")); + CHECK(rule_matches(make_rule("^mcp WEB", "Submit"), "MCP web fixture", "", "")); // With a message, the text is "title\nmessage" as it always was: a pattern anchored to the - // message's start finds nothing there, so which of two rules answers a dialog stays the same. - CHECK(rule_matches(make_rule("preset\\nThis", "ok"), "Delete preset", "This cannot be undone")); - CHECK(rule_matches(make_rule("^Warning", "no"), "Warning", "Delete all cached files?")); - CHECK_FALSE(rule_matches(make_rule("^Delete", "yes"), "Warning", "Delete all cached files?")); - CHECK_FALSE(rule_matches(make_rule("Export", "ok"), "Delete preset", "This cannot be undone")); + // message's start finds nothing there, so which of two rules answers a dialog stays the same. A + // message box's text is its message. + CHECK(rule_matches(make_rule("preset\\nThis", "ok"), "Delete preset", "This cannot be undone", "This cannot be undone")); + CHECK(rule_matches(make_rule("^Warning", "no"), "Warning", "Delete all cached files?", "Delete all cached files?")); + CHECK_FALSE(rule_matches(make_rule("^Delete", "yes"), "Warning", "Delete all cached files?", "Delete all cached files?")); + CHECK_FALSE(rule_matches(make_rule("Export", "ok"), "Delete preset", "This cannot be undone", "This cannot be undone")); +} + +TEST_CASE("an auto-answer rule finds a dialog's own text however its controls read", "[Mcp]") +{ + // Fragments a dialog's message joins on one row are lines of its text, as rules have known them. + CHECK(rule_matches(make_rule("accept\\nTerms", "ok"), "Bind", "Read and accept | Terms and Conditions", + "Read and accept\nTerms and Conditions")); + // A dialog whose only content is a field still matches by its lone title: it has no text. + CHECK(rule_matches(make_rule("^Rename$", "ok"), "Rename", "[Cube]", "")); + CHECK_FALSE(rule_matches(make_rule("^Rename$", "ok"), "Rename", "New name\n[Cube]", "New name")); + // What the message adds can be matched too. + CHECK(rule_matches(make_rule("\\[x\\] Remember", "ok"), "Unsaved changes", "[x] Remember my choice.", "Remember my choice.")); } TEST_CASE("the journal's index counts every candidate page's matches, and only when all were heard from", "[Mcp]") @@ -342,6 +358,38 @@ TEST_CASE("a dialog with a web view is described as a web dialog", "[Mcp]") } } +namespace { + +// A label that can't be read, as a widget in a bad state might fail. +class FailingLabel final : public wxStaticText +{ +public: + explicit FailingLabel(wxWindow* parent) : wxStaticText(parent, wxID_ANY, "label") {} + wxString GetLabel() const override { throw std::runtime_error("unreadable"); } +}; + +} // namespace + +TEST_CASE("a web dialog that can't be described is still listed as a web dialog", "[Mcp]") +{ + if (!have_display()) + SKIP("This test needs a display (for example, xvfb-run)."); + wxInitializer init; + REQUIRE(init.IsOk()); + { + ModalTracker tracker; + wxDialog dialog(nullptr, wxID_ANY, "Color Picker"); + new StubWebView(&dialog); + new FailingLabel(&dialog); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + const json snap = tracker.snapshot(); + REQUIRE(snap.size() == 1); + CHECK(snap[0]["title"] == "Color Picker"); + CHECK(snap[0].value("web", false)); + wxModalDialogHook::CallExit(&dialog); + } +} + TEST_CASE("a web dialog's rule names a wx button of it by label, standard name or id", "[Mcp]") { if (!have_display())