diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index d0669b697f..6a89600d9e 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -551,7 +551,7 @@ nothing from it, and `plugin/` includes nothing from `GUI/Mcp`. | `PresetOps` | `resolve_preset`, `select_preset` | `preset_select`, the plugin API's `begin_update(preset_name)` | | | `assign_filament_preset` | `preset_select`, the plugin API's `begin_update(slot_number, preset_name)` (the sidebar's selector calls the same owner effect, `Sidebar::select_filament_preset()`) | | | `import_presets`, `sync_presets` | `preset_import`, `preset_sync` | -| | `add_filament_slot`, `delete_filament_slot`, `add_mixed_filament` | `filament_add`, `filament_delete`, `filament_add_mixed` | +| | `add_filament_slot`, `delete_filament_slot`, `add_mixed_filament`, `edit_mixed_filament` | `filament_add`, `filament_delete`, `filament_add_mixed`, `filament_edit_mixed` | | | `sync_filaments_from_ams` | `filament_sync_ams`; the AMS sync dialog applies its choice through the same `apply_ams_sync()` | | `InstallOps` | `printer_models`, `install_printers`, `uninstall_printers` | `printer_list_models`, `printer_install`, `printer_uninstall` | | | `install_filaments`, `uninstall_filaments` | `filament_install`, `filament_uninstall` | @@ -1282,57 +1282,33 @@ so replays create it first with `preset_save`. ### Project settings -`project_get_settings` and `project_set_settings` read and write the settings of the project itself, -which it stores outside any preset (`PresetBundle::project_config`), as a plate's are stored on the plate: -they are not print settings a preset or an object holds, so they have commands of their own beside the -settings commands. They are what a person sets in the sidebar, on the canvas or in their dialogs: -`curr_bed_type`, `filament_colour`, `flush_volumes_matrix`, `flush_multiplier`, `prime_volume_mode` -and `wipe_tower_x`/`wipe_tower_y`, plus the read-only `filament_is_mixed` and, on a printer with -several extruders, the read-only `filament_map_mode` and `filament_map`; `project_get_settings` with no -`keys` returns them all, each with its value and meta (`meta.offered`, the choices this printer has, and -`meta.read_only`). A generic config write would skip what each control does after setting its value, so -`project_set_settings` writes every key through that control's own code. Everything is checked before -anything changes, `null` is refused (project values always exist), and `{"index": i, "value": v}` sets -one slot's colour, one matrix cell or one plate's tower position. +`project_get_settings` and `project_set_settings` read and write the project's own settings for its +plates, which it stores outside any preset (`PresetBundle::project_config`), as a plate's are stored on +the plate: they are not print settings a preset or an object holds, so they have commands of their own +beside the settings commands. They are `curr_bed_type` and `wipe_tower_x`/`wipe_tower_y` and, on a +printer with several extruders, the read-only `filament_map_mode` and `filament_map`; +`project_get_settings` with no `keys` returns them all, each with its value and meta (`meta.offered`, +the choices this printer has, and `meta.read_only`). A generic config write would skip what each +control does after setting its value, so `project_set_settings` writes every key through that +control's own code. Everything is checked before anything changes, `null` is refused (project values +always exist), and `{"index": i, "value": v}` sets one plate's tower position. - `curr_bed_type` goes through the plate type selector (`Sidebar::set_bed_type_accord_combox()`, whose handler updates the project, the printer's remembered plate type and the plates on the global type). Only the types the selector lists are taken (`meta.offered`), and none while the selector is hidden for the printer. -- `filament_colour` is one `#RRGGBB` per slot in config order. Each changed slot goes through its - colour button's code: `PlaterPresetComboBox::sync_colour_config()` and the queued - `EVT_FILAMENT_COLOR_CHANGED`, which recalculates that slot's flushing volumes when the "Auto flush - after changing" preference is on. -- `flush_volumes_matrix` and `flush_multiplier` go through `apply_flushing_volumes()`, the Flushing - volumes dialog's OK split from the dialog, then the button's scene reload and update. The matrix is - N x N per nozzle (row = from slot, column = to slot) in config order over every slot, as - `project_config` and the G-code header hold it, not over the physical slots the dialog shows. The - values are before the multiplier: the header prints the matrix multiplied by it, and the dialog - shows and edits each entry multiplied by it, so its meta's `description` (the option has no tooltip) - says so, since agents otherwise type the dialog's value as the stored one. Volumes are limited - to `g_max_flush_volume` / multiplier as the dialog limits them; negative volumes and a non-zero - diagonal are refused. A multiplier is one per nozzle (one value sets all) within the dialog's 0..3. -- `prime_volume_mode` is what the Purge mode dialog's OK writes, followed by the update it does. It is - offered only while the Purge mode button shows (printers with several nozzles per extruder or fast - purge), with the dialog's choices. - `wipe_tower_x`/`wipe_tower_y` are one position per plate, in mm from the plate's origin, as a tower drag stores them: one undo step ("Move object", which takes the old positions along), then an update. A position off the plate is refused; one where the tower does not fit is re-placed by the scene reload, as after a drag, with its notification, and the reply's `note` says so. -Colours are applied in a first UI closure and the rest in a second after a settle, so a matrix given -in the same call is written after the recalculation the colour change triggered, and a matrix cell -given by index is set in the matrix that recalculation left. The recalculation also runs when a slot -is added and, depending on the preference, when a slot's preset changes, so a matrix is best set -last; a replay matches only on a datadir with the same preference. - -A mixed filament is a virtual slot made of physical ones (the sidebar's mixed filament list); its -colour comes from its components and it is never flushed. `filament_is_mixed` tells which slots they -are, and their colours and matrix rows and columns are refused unless left as they are, as the -dialog keeps them. The filament grouping is set per plate in the Filament grouping dialog, and every -plate carries its own mode from the start, so a project-wide `filament_map_mode` or `filament_map` -would not change a slice: both are listed for reading only, and a plate's are written with -`plate_set_settings`. Nothing here except the tower position enters the undo stack, as in the GUI. +The filament grouping is set per plate in the Filament grouping dialog, and every plate carries its +own mode from the start, so a project-wide `filament_map_mode` or `filament_map` would not change a +slice: both are listed for reading only, and a plate's are written with `plate_set_settings`. The same +`project_config` holds the filament list's state, its slot colours, mixed filaments and flushing, which +belongs to the filament commands (The filament list, below): a call that names one of those keys here +is refused, naming the command that reads or sets it. Nothing here except the tower position enters the +undo stack, as in the GUI. ### Plate settings @@ -1531,15 +1507,82 @@ to say than their descriptions: Delete would ask about (part of a cut object, an object's last solid part) with the question as its reason, and its Speed Dial action leaves those to the object list, which asks. -### Filament slots and the AMS +### The filament list -`filament_add`, `filament_delete` and `filament_add_mixed` change the project's filament slots as the -sidebar's filament list does (`Ops::add_filament_slot()`, `Ops::delete_filament_slot()`, -`Ops::add_mixed_filament()`, see Commands that replace a dialog). `filament_add_mixed` adds what the Add -Mixed Filament dialog's OK adds with no gradient (`Sidebar::ensure_mixed_filament()`): `components`, two or -more physical slots of one filament type, each named once, and `ratios`, whole percentages adding up to 100; -a mix the project has already is not added again, and the reply names its slot. None of the three is in the -undo history, as in the GUI. +The sidebar's filament section holds the filament slots, the mixed filament list under them, and the +Flushing volumes and Purge mode buttons in its title bar. Their state is stored in `project_config` +beside the project's settings, but the app keeps it with the printer: `PresetBundle::export_selections()` +writes the slot colours, the mixed filaments and the flushing into the app configuration under the +printer, so they outlast a new project and a restart and come back when the printer is selected again, +and a saved project keeps a copy of its own (`s_project_options`). So the filament list has commands of +its own, in the Filaments group, rather than the project's. + +`filament_list` reads it as the sidebar shows it: a row per slot in config order, the physical filaments +first and then the mixed ones (`filament_slot`, `mixed`, `colour`; a physical row's `preset` and `type`; +a mixed row's `components`, `ratios`, `gradient` and `broken`), then `flush_multiplier`, +`flush_volumes_matrix` and `prime_volume_mode`, with `prime_volume_modes` where the printer offers a +choice. A mixed row's components are as stored, a deleted one as 0; its ratios, in whole percentages as +the commands take them, and its gradient are as the Edit Mixed Filament dialog reads them +(`Sidebar::mixed_filament_result()`). The slicer reads `filament_mixed_gradient_range` as the first +component's share at the bottom and at the top, so a gradient is given as the components that lead +`bottom` and `top`, with `per_part` and whether its `curve` is the default straight line or a custom one. +`broken` is what the sidebar marks (`Sidebar::broken_mixed_filaments()`): a component deleted or past the +physical filaments, fewer than two, or components of different filament types; slicing an object on a +broken mix is refused. + +A mixed slot's `filament_presets` entry is a copy of its first component's preset name +(`create_mixed_filament_from_result()`), which no reader takes for the slot's preset: a mixed slot has no +selector and no filament tab, so `filament_list` gives its row no preset, `preset_list`'s `filament_slots` +leaves mixed slots out, and `preset_select`, `settings_get`, `settings_set`, `settings_list` and +`preset_save` refuse a mixed slot (`mixed_filament_slot`), as the plugin API's preset editing does. + +`filament_add`, `filament_delete`, `filament_add_mixed` and `filament_edit_mixed` change the slots as the +list does (`Ops::add_filament_slot()`, `Ops::delete_filament_slot()`, `Ops::add_mixed_filament()`, +`Ops::edit_mixed_filament()`, see Commands that replace a dialog). None of them is in the undo history, as +in the GUI. + +- `filament_add_mixed` adds what the Add Mixed Filament dialog's OK adds with no gradient + (`Sidebar::ensure_mixed_filament()`): `components`, two or more physical slots of one filament type, + each named once, and `ratios`, whole percentages adding up to 100; a mix the project has already is not + added again, and the reply names its slot. +- `filament_edit_mixed` changes a mix as the Edit Mixed Filament dialog's OK does + (`Sidebar::apply_mixed_filament_edit()`, the OK split from the dialog): the slot keeps its number and the + objects on it, its colour becomes the blend, and a gradient stays for a mix of two filaments and goes for + more, which the dialog shows none for. An edit that names its filaments again repairs a broken mix. +- Without `components` and `ratios`, `filament_add_mixed` opens the Add Mixed Filament dialog, as the + sidebar's button does, and `filament_edit_mixed` with only `filament_slot` opens the Edit Mixed Filament + dialog on that mix, as a click on its swatch does; both reply `blocked_by_dialog`. This is how an agent + sets a gradient, which has no argument: the dialog names its controls for `widget_set_value` + (`filament_1` to `filament_3`, `gradient`, `gradient_direction`, whose item 0 puts the first filament at + the bottom, and `per_part_gradient`), and its OK makes what it shows. The gradient curve is drawn, so + only a drag changes it. +- `filament_delete` deletes a physical filament that a mixed filament mixes as the sidebar does, without a + question: `remap_mixed_components_on_delete()` leaves a 0 in the mix's components, the mix is broken, and + the reply's `broken_mixed` names the broken mixes until an edit repairs them. A merge into a mixed + filament that mixes the slot asks first, as Merge with does (`Sidebar::change_filament()`), so the call + replies `blocked_by_dialog`, unless `break_mix` answers ahead: true merges, false refuses + (`mixed_uses_slot`). With one physical filament left the sidebar hides the mixed filament list and deletes + nothing (`Sidebar::delete_filament()`), so a mix is refused then (`mixed_list_hidden`) until a slot is added. +- `filament_set_colour` sets one physical slot's `#RRGGBB` through its colour button's code: + `PlaterPresetComboBox::sync_colour_config()` and the queued `EVT_FILAMENT_COLOR_CHANGED`, which + recalculates that slot's flushing volumes when the "Auto flush after changing" preference is on. A mixed + filament's colour is its components' blend and is refused unless left as it is. The recalculation also + runs when a slot is added and, depending on the preference, when a slot's preset changes, so a matrix is + best set after the colours; a replay matches only on a datadir with the same preference. +- `filament_set_flushing` writes what the Flushing volumes and Purge mode dialogs' OK write, through the + code `project_set_settings` runs for its keys. `flush_volumes_matrix` and `flush_multiplier` go through + `apply_flushing_volumes()`, the Flushing volumes dialog's OK split from the dialog, then the button's scene + reload and update. The matrix is N x N per nozzle (row = from slot, column = to slot) in config order + over every slot, as `project_config` and the G-code header hold it, not over the physical slots the + dialog shows. The values are before the multiplier: the header prints the matrix multiplied by it, and + the dialog shows and edits each entry multiplied by it, which `filament_list`'s description says, since + agents otherwise type the dialog's value as the stored one. Volumes are limited to `g_max_flush_volume` / + multiplier as the dialog limits them; negative volumes and a non-zero diagonal are refused, and a mixed + filament's rows and columns, which are never flushed, are refused unless left as they are, as the dialog + keeps them. A multiplier is one per nozzle (one value sets all) within the dialog's 0..3. + `prime_volume_mode` is what the Purge mode dialog's OK writes, followed by the update it does, offered + only while the Purge mode button shows (printers with several nozzles per extruder or fast purge), with + the dialog's choices. `filament_sync_ams` takes the filament list from the AMS of the printer selected on the Device tab. As its Speed Dial action, with no arguments, it opens the sync dialog where the project has objects. With `mode` it @@ -2477,9 +2520,9 @@ buttons and a slot's Delete and Merge with menu items (`Ops::add_filament_slot() `Ops::delete_filament_slot()`): they run where the buttons show, for printers that take several filaments through one extruder, and refuse elsewhere, at the slot limit, and for the only physical slot. `filament_delete` deletes a mixed filament as the -mixed filament list does, and refuses to merge one, and to delete a physical slot a mixed filament mixes: the -sidebar would leave the mix naming a slot that is gone, which nothing can repair. A new slot goes after the physical slots, so mixed filaments move up by one with the -objects on them. `filament_delete` takes a 1-based `filament_slot`, the last physical one without it, and +mixed filament list does and refuses to merge one, which the list offers no Merge with for; a physical slot a +mixed filament mixes is deleted as the sidebar deletes it, leaving the mix broken (The filament list). A new +slot goes after the physical slots, so mixed filaments move up by one with the objects on them. `filament_delete` takes a 1-based `filament_slot`, the last physical one without it, and `merge_into`, the slot its objects go to in place of the first. `preset_sync` refuses while no account is signed in, and `filament_sync_ams` with no printer, no AMS or no filament. diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index 92f1e46b07..144e0fd060 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -131,8 +131,8 @@ them and `tool_call` runs them. | `project_new` | Start a new, empty project | `discard_changes`; `preset_changes`: keep, discard | | `project_save` | Save the project to its file, or as a .3mf at a path, which becomes its file | `path`, `overwrite`; `save_as` | | `project_export` | Write a plate's G-code, a sliced 3MF, a 3MF, the objects as STL or Draco, or the shown toolpaths as OBJ | `format`: gcode, sliced_3mf, 3mf, stl, drc, toolpaths_obj; `path`, `overwrite`; `plates`; `per_object`, `objects` | -| `project_get_settings` | The settings the project keeps outside any preset: the plate type, slot colours, flushing volumes, purge mode, prime tower positions, mixed slots and filament grouping | `keys`, `include_meta` | -| `project_set_settings` | Change those settings as the sidebar's controls write them | `values` | +| `project_get_settings` | The project's own settings for its plates: the plate type, prime tower positions and filament grouping | `keys`, `include_meta` | +| `project_set_settings` | Change those settings as their controls write them | `values` | ### Objects @@ -221,9 +221,13 @@ them and `tool_call` runs them. | Command | What it does | Variants and main arguments | |---|---|---| +| `filament_list` | The filament list as the sidebar shows it: each slot's colour and preset, or a mixed filament's filaments, ratios, gradient and whether it is broken; the flushing volumes, multiplier and purge mode | | | `filament_add` | Add a filament slot, as the + button above the filament list does | | -| `filament_delete` | Delete a slot, or merge it into another, as its Delete and Merge with items do | `filament_slot`, `merge_into` | +| `filament_delete` | Delete a slot, or merge it into another, as its Delete and Merge with items do | `filament_slot`, `merge_into`, `break_mix` | | `filament_add_mixed` | Add a mixed filament, which prints physical slots in turn, layer by layer, in given ratios | `components`, `ratios` | +| `filament_edit_mixed` | Change a mixed filament's filaments and ratios, as the Edit Mixed Filament dialog's OK does | `filament_slot`, `components`, `ratios` | +| `filament_set_colour` | Set a physical slot's colour, as its colour button does | `filament_slot`, `colour` | +| `filament_set_flushing` | Change the flushing volumes, multiplier and purge mode, as their dialogs' OK does | `flush_multiplier`, `flush_volumes_matrix`, `prime_volume_mode` | | `filament_sync_ams` | Synchronize the filament list from the connected printer's AMS | `mode`: map, overwrite | | `filament_install` | Install system filaments, as the System Filaments dialog's Confirm does | `names`; or `vendor` and `filament_type` | | `filament_uninstall` | Uninstall system filaments | `names` | @@ -439,6 +443,9 @@ and opens nothing.** A command's own action is `{}`. | `preset_import {}` | a file dialog | `path` | | `plugin_install_local {}` | a file dialog, and whether to replace an installed plugin | `path`, with `overwrite` | | `filament_sync_ams {}` | the sync dialog | `mode` | +| `filament_add_mixed {}` | the Add Mixed Filament dialog, where a gradient is set | `components` and `ratios` | +| `filament_edit_mixed {filament_slot}` | the Edit Mixed Filament dialog on that mix, where a gradient is set | `components` and `ratios` | +| `filament_delete {filament_slot, merge_into}` into a mixed filament that mixes the slot | Merge with's question | `break_mix` | | `recording_start {}` | the Start Recording dialog | any argument, or `silent: true` | | `window_open {window}`, `app_open_web_page {page}` | nothing: opening is the job | the same call | @@ -625,7 +632,7 @@ Access labels, which `tools/list` sends as MCP's annotations (mcp-server.md, Too set as it is): - **read_only**, 21 commands: `tool_search`, `action_search`, `app_state`, `app_wait`, `app_log`, - `preferences_get`, `project_get_settings`, `object_list`, `plate_get_settings`, `plate_list`, + `preferences_get`, `project_get_settings`, `filament_list`, `object_list`, `plate_get_settings`, `plate_list`, `plate_slice_stats`, `preset_list`, `settings_list`, `settings_get`, `printer_list_models`, `printer_status`, `plugin_list`, `window_list`, `window_screenshot`, `script_search_api` and `widget_list`. These are idempotent too, and so is `dialog_auto_answer`. @@ -648,7 +655,8 @@ set as it is): - **Undo.** A command that changes the objects, their parts or the plates is one undo step; `object_clone` with `arrange` is two, the copies and then the arrangement, and `project_set_settings` takes one for a prime tower move. A gizmo that records undo steps of its own as it opens or closes, as Cut, Brim Ears and the painting - gizmos do, adds them around a gizmo command's call. Not in the undo history: `filament_delete`, `filament_add_mixed`, `filament_sync_ams`, + gizmos do, adds them around a gizmo command's call. Not in the undo history: `filament_delete`, `filament_add_mixed`, + `filament_edit_mixed`, `filament_set_colour`, `filament_set_flushing`, `filament_sync_ams`, `filament_install`, `filament_uninstall`, `printer_install`, `printer_uninstall`, a preset's change by `settings_set`, `preferences_set`, and `plate_set_custom_gcode`, as in the layer slider. - **Unsaved changes.** `project_open`, `project_new` and `calibration_generate_test` refuse while the project @@ -657,7 +665,7 @@ set as it is): preset or a printer is selected (`preset_select`, `printer_install`, `printer_uninstall`); `preset_select` without it opens the Transfer-or-discard prompt. - **Settings values** are strings in OrcaSlicer's format (`"15%"`, `"0.2"`, `"1,2"`) or JSON numbers, - booleans and arrays. `settings_set`, `preferences_set`, `project_set_settings` and `plate_set_settings` + booleans and arrays. `settings_set`, `preferences_set`, `project_set_settings`, `filament_set_flushing` and `plate_set_settings` check every value first and write them together, so nothing changes when one is refused. - **What is shown.** A command that acts on the 3D selection shows the Prepare view first; `plate_slice` shows the Preview, as the Slice button does; `plate_set_custom_gcode` selects its plate and shows the @@ -698,6 +706,9 @@ set as it is): | Export Preset Bundle | `preset_export` | | Mode: Simple, Advanced, Expert | `settings_set_mode {mode}` | | the filament list's + and -, Merge with | `filament_add`, `filament_delete`, `{merge_into}` | +| a slot's colour button | `filament_set_colour` | +| Flushing volumes, Purge mode | `filament_set_flushing` | +| Add Mixed Filament, a mixed filament's swatch (Edit Mixed Filament) | `filament_add_mixed`, `filament_edit_mixed` | | System Filaments dialog | `filament_install`, `filament_uninstall` | | Printer Selection dialog | `printer_install`, `printer_uninstall` | | Send G-code to printer host, the Print button's Send and Send all | `printer_send`, `{plates: "all"}` | diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 6981fe6819..82988f2d4f 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -422,17 +422,17 @@ nlohmann::json unsaved_changes_outcome(const nlohmann::json& before); nlohmann::json check_preset_deletable(const PresetCollection& presets, const std::string& name, bool delete_attached, const PresetCollection& prints, const PresetCollection& filaments); -// project_set_settings' filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in +// The slot colours filament_set_colour writes: one colour per slot of `current`, each #RRGGBB (stored in // upper case, as the colour pickers store it) or the slot's current colour in any case. `mixed` flags the // mixed slots, whose colour comes from their components and cannot change. Throws ToolFailure otherwise. std::vector check_filament_colours(std::vector colours, const std::vector& current, const std::vector& mixed); -// project_set_settings' flush_multiplier to write: one per nozzle, or one value for all, each within the +// filament_set_flushing's flush_multiplier to write: one per nozzle, or one value for all, each within the // Flushing volumes dialog's 0..3. Throws ToolFailure otherwise. std::vector check_flush_multipliers(std::vector multipliers, std::size_t nozzles); -// project_set_settings' flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from, +// filament_set_flushing's flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from, // column = to) in config order over every slot, as project_config and the G-code header hold it, limited // as the Flushing volumes dialog limits them (g_max_flush_volume / the nozzle's multiplier). Throws // ToolFailure for another length, a negative volume, a non-zero diagonal, or a changed entry of a mixed diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index 1c53cfdb5d..4bd0403104 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -24,6 +24,7 @@ #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/IMSlider.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/MixedFilamentDialog.hpp" #include "slic3r/GUI/NativeCommandMenuItems.hpp" #include "slic3r/GUI/NativeCommands.hpp" #include "slic3r/GUI/ObjectDataViewModel.hpp" @@ -45,6 +46,7 @@ #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/FilamentMixer.hpp" #include "libslic3r/FlushVolCalc.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" #include "libslic3r/LocalesUtils.hpp" @@ -210,24 +212,56 @@ struct ConfigTarget std::vector options; // the keys these settings have }; -// The project's settings: the project's own settings (PresetBundle::project_config) that a person sets in the -// sidebar, on the canvas or in their dialogs, and the filament slot facts they depend on, which are set -// elsewhere and listed for reading only. +// The project's settings: the project's own settings (PresetBundle::project_config) that a person sets for its plates, +// with the plate type selector and a prime tower's drag, and the filament grouping, which the Filament grouping dialog +// sets for each plate and which is listed for reading only. The same config holds the filament list's state, its +// colours, mixed filaments and flushing, which filament_list reads instead (filament_list_hint()). bool project_key_read_only(const std::string& key) { - return key == "filament_is_mixed" || key == "filament_map_mode" || key == "filament_map"; + return key == "filament_map_mode" || key == "filament_map"; } std::vector project_options() { - std::vector keys{"curr_bed_type", "filament_colour", "filament_is_mixed", "flush_volumes_matrix", - "flush_multiplier", "prime_volume_mode", "wipe_tower_x", "wipe_tower_y"}; + std::vector keys{"curr_bed_type", "wipe_tower_x", "wipe_tower_y"}; // The filament grouping of a printer with several extruders. if (wxGetApp().preset_bundle->get_printer_extruder_count() > 1) keys.insert(keys.end(), {"filament_map_mode", "filament_map"}); return keys; } +// The flushing that the filament list's Flushing volumes and Purge mode buttons set: filament_list reads it and +// filament_set_flushing writes it, with the code project_set_settings runs for its own keys (set_project_values()). +const std::vector& flushing_options() +{ + static const std::vector keys{"flush_multiplier", "flush_volumes_matrix", "prime_volume_mode"}; + return keys; +} + +// Where a key of the filament list's state is read and set, for a call that names it among the project's settings; +// empty for any other key. +std::string filament_list_hint(const std::string& key) +{ + if (key == "filament_colour") + return "filament_list reads the slot colours and filament_set_colour sets one"; + if (key == "filament_is_mixed") + return "filament_list reads which slots are mixed filaments"; + const std::vector& flushing = flushing_options(); + if (std::find(flushing.begin(), flushing.end(), key) != flushing.end()) + return "filament_list reads it and filament_set_flushing sets it"; + return {}; +} + +// Per filament slot, in config order, whether it is a mixed filament. UI thread. +std::vector mixed_slots() +{ + const PresetBundle& bundle = *wxGetApp().preset_bundle; + std::vector mixed; + for (std::size_t i = 0; i < bundle.project_config.option("filament_colour")->size(); ++i) + mixed.push_back(bundle.is_mixed_filament(i)); + return mixed; +} + // The types settings_get looks through when keys or a query come without one: the process, filament and printer // settings being edited, since a question about an effect rarely knows which tab answers it. const char* const kSearchTypes[]{"process", "filament", "printer"}; @@ -246,6 +280,8 @@ std::string type_of_key(const std::string& key) return "printer"; if (!print_config_def.has(key)) return {}; + if (!filament_list_hint(key).empty()) + return "filament_list"; const std::vector project = project_options(); return std::find(project.begin(), project.end(), key) != project.end() ? "project" : ""; } @@ -270,21 +306,24 @@ void add_unknown_keys(json& out, const json& unknown) // process). UI thread. ToolFailure unknown_setting(const std::string& key, const std::string& where, json details) { + if (const std::string hint = filament_list_hint(key); !hint.empty()) + return ToolFailure("\"" + key + "\" belongs to the filament list: " + hint); if (const std::string other = type_of_key(key); !other.empty() && other != where) return ToolFailure(other == "project" ? "\"" + key + "\" is one of the project's own settings: project_set_settings changes it" : "\"" + key + "\" is a " + other + " setting: settings_set takes it with type \"" + other + "\""); return ToolFailure("Unknown setting \"" + key + "\" for the " + where + " settings", std::move(details)); } -// The project's settings: project_config's, with the wipe tower position one entry per plate and a -// mixed flag per slot, since a project can store fewer of either. UI thread. +// The project's settings and the filament list's flushing: project_config's, with the wipe tower position one entry +// per plate, since a project can store fewer. UI thread. DynamicPrintConfig project_settings() { const PresetBundle& bundle = *wxGetApp().preset_bundle; DynamicPrintConfig out; - for (const std::string& key : project_options()) - if (const ConfigOption* opt = bundle.project_config.option(key)) - out.set_key_value(key, opt->clone()); + for (const std::vector& keys : {project_options(), flushing_options()}) + for (const std::string& key : keys) + if (const ConfigOption* opt = bundle.project_config.option(key)) + out.set_key_value(key, opt->clone()); const int plates = ui_plater().get_partplate_list().get_plate_count(); for (const char* key : {"wipe_tower_x", "wipe_tower_y"}) { // What the canvas reads for each plate (get_at() takes the first entry for a plate without one). @@ -294,10 +333,6 @@ DynamicPrintConfig project_settings() per_plate.push_back(position->get_at(std::size_t(i))); position->values = std::move(per_plate); } - std::vector mixed; - for (std::size_t i = 0; i < bundle.project_config.option("filament_colour")->size(); ++i) - mixed.push_back(bundle.is_mixed_filament(i)); - out.set_key_value("filament_is_mixed", new ConfigOptionBools(std::move(mixed))); return out; } @@ -327,23 +362,19 @@ std::vector project_offered(const std::string& key) return out; } -// project_set_settings. Every key is written by the code its control runs: the plate type selector, a colour -// button's picker, the Flushing volumes and Purge mode dialogs' OK, a wipe tower drag. Everything is checked before -// anything changes. Colours go first, in a closure of their own, so the flushing volumes their change recalculates -// ("Auto flush after changing") are in place before a matrix given in the same call replaces them. -ToolResult set_project_settings(const json& args, ToolContext& ctx) +// project_set_settings, with the project's keys, and filament_set_flushing, with the filament list's flushing +// (`flushing`). Every key is written by the code its control runs: the plate type selector, the Flushing volumes and +// Purge mode dialogs' OK, a wipe tower drag. Everything is checked before anything changes. +ToolResult set_project_values(const json& values_in, ToolContext& ctx, bool flushing) { - const json values_in = args.value("values", json::object()); - if (values_in.empty()) - throw ToolFailure("values must be a non-empty object {key: value}"); DynamicPrintConfig before; - DynamicPrintConfig values; // checked, in the form project_get_settings reads them + DynamicPrintConfig values; // checked, in the form project_settings() reads them // The matrix to write, given whole or as one entry of `basis`'s matrix. const auto checked_matrix = [&](const DynamicPrintConfig& basis) { const char* const key = "flush_volumes_matrix"; DynamicPrintConfig given; given.set_deserialize_strict(key, preset_setting_value(key, values_in[key], basis, {}, {})); - const std::vector& mixed = before.option("filament_is_mixed")->values; + const std::vector mixed = mixed_slots(); return check_flush_matrix(given.option(key)->values, mixed.size(), (values.has("flush_multiplier") ? values : before).option("flush_multiplier")->values, basis.option(key)->values, mixed); @@ -351,13 +382,11 @@ ToolResult set_project_settings(const json& args, ToolContext& ctx) ctx.run_ui([&]() -> json { ui_plater(); before = project_settings(); - const std::vector options = project_options(); + const std::vector options = flushing ? flushing_options() : project_options(); for (auto it = values_in.begin(); it != values_in.end(); ++it) { const std::string& key = it.key(); if (std::find(options.begin(), options.end(), key) == options.end()) - throw unknown_setting(key, "project", {{"keys", options}}); - if (key == "filament_is_mixed") - throw ToolFailure("filament_is_mixed is read-only: mixed filaments are made in the sidebar's mixed filament list"); + throw unknown_setting(key, flushing ? "filament list" : "project", {{"keys", options}}); if (project_key_read_only(key)) throw ToolFailure(key + " is read-only here: the Filament grouping dialog sets it for each plate, and every plate keeps " "its own grouping"); @@ -381,11 +410,6 @@ ToolResult set_project_settings(const json& args, ToolContext& ctx) throw ToolFailure("This printer does not offer " + std::string(key) + " \"" + values.opt_serialize(key) + "\"", {{"offered", offered}}); } - const std::vector& mixed = before.option("filament_is_mixed")->values; - if (values.has("filament_colour")) { - auto* colours = values.option("filament_colour"); - colours->values = check_filament_colours(colours->values, before.option("filament_colour")->values, mixed); - } if (values.has("flush_multiplier")) { auto* multipliers = values.option("flush_multiplier"); const std::size_t nozzles = before.option("flush_multiplier")->size(); @@ -409,38 +433,16 @@ ToolResult set_project_settings(const json& args, ToolContext& ctx) to_config_string(json(extent)) + " mm from the plate's origin"); } } - // A colour button's picker, then its EVT_FILAMENT_COLOR_CHANGED, slot by slot. - if (values.has("filament_colour")) { - const std::vector& colours = values.option("filament_colour")->values; - const std::vector& current = before.option("filament_colour")->values; - for (std::size_t i = 0; i < colours.size(); ++i) { - if (colours[i] == current[i]) - continue; - auto& combos = ui_plater().sidebar().combos_filament(); - auto combo = std::find_if(combos.begin(), combos.end(), - [i](PlaterPresetComboBox* c) { return c != nullptr && c->get_filament_idx() == int(i); }); - if (combo == combos.end()) - throw ToolFailure("Filament slot " + std::to_string(i + 1) + " has no colour button"); - (*combo)->sync_colour_config({colours[i]}, false); - wxCommandEvent* evt = new wxCommandEvent(EVT_FILAMENT_COLOR_CHANGED); - evt->SetInt(int(i)); - wxQueueEvent(&ui_plater(), evt); - } - } return json(); }); - settle(ctx); json reply = ctx.run_ui([&]() -> json { Plater& plater = ui_plater(); PresetBundle& bundle = *wxGetApp().preset_bundle; if (values.has("curr_bed_type")) plater.sidebar().set_bed_type_accord_combox(values.opt_enum("curr_bed_type")); - // One entry given: the others are as the colour change may just have recalculated them. - if (values_in.contains("flush_volumes_matrix") && values_in["flush_volumes_matrix"].is_object()) - values.option("flush_volumes_matrix")->values = checked_matrix(project_settings()); bool update = false; if (values.has("flush_volumes_matrix") || values.has("flush_multiplier")) { - // Without a matrix, the one the colour change may just have recalculated. + // Without a matrix, the stored one, which the new multiplier scales. const DynamicPrintConfig& source = values.has("flush_volumes_matrix") ? values : bundle.project_config; const DynamicPrintConfig& multipliers = values.has("flush_multiplier") ? values : bundle.project_config; apply_flushing_volumes(source.option("flush_volumes_matrix")->values, @@ -491,6 +493,111 @@ ToolResult set_project_settings(const json& args, ToolContext& ctx) return ToolResult::ok(reply); } +ToolResult set_project_settings(const json& args, ToolContext& ctx) +{ + const json values_in = args.value("values", json::object()); + if (values_in.empty()) + throw ToolFailure("values must be a non-empty object {key: value}"); + return set_project_values(values_in, ctx, false); +} + +// What a slot's colour button does with the colour its picker gives: the slot's colour, then its +// EVT_FILAMENT_COLOR_CHANGED, which recalculates the flushing volumes where Auto flush after changing is on. UI thread. +void apply_slot_colour(std::size_t slot, const std::string& colour) +{ + auto& combos = ui_plater().sidebar().combos_filament(); + auto combo = std::find_if(combos.begin(), combos.end(), + [slot](PlaterPresetComboBox* c) { return c != nullptr && c->get_filament_idx() == int(slot); }); + if (combo == combos.end()) + throw ToolFailure("Filament slot " + std::to_string(slot + 1) + " has no colour button"); + (*combo)->sync_colour_config({colour}, false); + wxCommandEvent* evt = new wxCommandEvent(EVT_FILAMENT_COLOR_CHANGED); + evt->SetInt(int(slot)); + wxQueueEvent(&ui_plater(), evt); +} + +// filament_set_colour: one slot's colour, checked as check_filament_colours() checks a colour list. The reply reads it +// back once the change has settled. +ToolResult set_filament_colour(const json& args, ToolContext& ctx) +{ + const int slot = arg_int(args, "filament_slot", 1); + const std::string colour = arg_string(args, "colour"); + bool changed = false; + ctx.run_ui([&]() -> json { + ui_plater(); + const std::vector& current = + wxGetApp().preset_bundle->project_config.option("filament_colour")->values; + if (slot < 1 || std::size_t(slot) > current.size()) + throw ToolFailure("filament_slot must be 1.." + std::to_string(current.size())); + std::vector colours = current; + colours[std::size_t(slot) - 1] = colour; + colours = check_filament_colours(colours, current, mixed_slots()); + changed = colours[std::size_t(slot) - 1] != current[std::size_t(slot) - 1]; + if (changed) + apply_slot_colour(std::size_t(slot) - 1, colours[std::size_t(slot) - 1]); + return json(); + }); + settle(ctx); + return ToolResult::ok(ctx.run_ui([&]() -> json { + const std::vector& colours = + wxGetApp().preset_bundle->project_config.option("filament_colour")->values; + return {{"filament_slot", slot}, {"colour", colours[std::size_t(slot) - 1]}, {"changed", changed}}; + })); +} + +// filament_list: the filament list as the sidebar shows it, a row per slot in config order (the physical filaments, +// then the mixed ones), with the flushing its Flushing volumes and Purge mode buttons set. UI thread. +json filament_list() +{ + Sidebar& sidebar = ui_plater().sidebar(); + PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::vector& colours = bundle.project_config.option("filament_colour")->values; + const auto* components = bundle.project_config.option("filament_mixed_components"); + const std::vector broken = sidebar.broken_mixed_filaments(); + json rows = json::array(); + for (std::size_t i = 0; i < colours.size(); ++i) { + const bool mixed = bundle.is_mixed_filament(i); + json row{{"filament_slot", i + 1}, {"mixed", mixed}, {"colour", colours[i]}}; + if (!mixed) { + const std::string name = i < bundle.filament_presets.size() ? bundle.filament_presets[i] : std::string(); + Preset* preset = bundle.filaments.find_preset(name); + std::string display; + row["preset"] = name; + row["type"] = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); + rows.push_back(std::move(row)); + continue; + } + // The components as stored, a deleted one as 0; the ratios and the gradient as the Edit Mixed Filament dialog + // reads them. + json parts = json::array(); + if (components != nullptr && i < components->size()) + for (const unsigned int component : parse_mixed_components(components->values[i])) + parts.push_back(component); + const MixedFilamentResult mix = sidebar.mixed_filament_result(i); + row["components"] = std::move(parts); + row["ratios"] = mix.ratios; + row["gradient"] = nullptr; + if (mix.gradient_enabled && mix.components.size() == 2) { + // Direction 0 starts with the first component's share high: it leads at the bottom (filament_mixed_gradient_range). + const bool first_at_bottom = mix.gradient_direction == 0; + row["gradient"] = {{"bottom", first_at_bottom ? mix.components[0] : mix.components[1]}, + {"top", first_at_bottom ? mix.components[1] : mix.components[0]}, + {"per_part", mix.per_part_gradient}, + {"curve", mix.gradient_curve.empty() ? "linear" : "custom"}}; + } + row["broken"] = std::find(broken.begin(), broken.end(), i) != broken.end(); + rows.push_back(std::move(row)); + } + const DynamicPrintConfig settings = project_settings(); + json out{{"filaments", std::move(rows)}, + {"flush_multiplier", settings.option("flush_multiplier")->values}, + {"flush_volumes_matrix", settings.option("flush_volumes_matrix")->values}, + {"prime_volume_mode", settings.opt_serialize("prime_volume_mode")}}; + if (std::vector offered = project_offered("prime_volume_mode"); !offered.empty()) + out["prime_volume_modes"] = std::move(offered); + return out; +} + bool is_plate_setting(const std::string& key) { const std::vector& keys = plate_setting_keys(); @@ -707,8 +814,8 @@ ToolResult set_plate_settings(const json& args, ToolContext& ctx) // The dialog greys the custom orders out while a slot is a mixed filament, which prints a different // physical filament from layer to layer. if (!value.is_null() && wxGetApp().preset_bundle->num_mixed_filaments() > 0) - throw ToolFailure(key + " cannot be set while the project has mixed filaments (see filament_is_mixed of " - "project_get_settings); null sets Auto"); + throw ToolFailure(key + " cannot be set while the project has mixed filaments (filament_list's mixed rows); " + "null sets Auto"); if (key == "first_layer_print_sequence") first_layer = value.is_null() ? std::vector() : filament_order(value, slots); else @@ -1001,12 +1108,16 @@ AppActionRunResult filament_delete_command(const json& args) op.filament_slot = arg_int(args, "filament_slot", 1); if (args.contains("merge_into")) op.merge_into = arg_int(args, "merge_into", 1); + if (args.contains("break_mix")) + op.break_mix = arg_bool(args, "break_mix", false); const Ops::Outcome deleted = Ops::delete_filament_slot(op); if (!deleted) return filament_refused(deleted.refusal()); json reply{{"filament_slot", deleted.value().filament_slot}}; if (deleted.value().merged_into) reply["merged_into"] = *deleted.value().merged_into; + if (!deleted.value().broken_mixed.empty()) + reply["broken_mixed"] = deleted.value().broken_mixed; // TRN %1% is a filament slot number. return filament_reply(format_wxstr(_L("Deleted filament slot %1%."), deleted.value().filament_slot), std::move(reply)); } @@ -1124,6 +1235,10 @@ ConfigTarget resolve_target(const json& args, bool for_write) const int slot = arg_int(args, "filament_slot", 1); if (slot < 1 || slot > int(bundle.filament_presets.size())) throw ToolFailure("filament_slot must be 1.." + std::to_string(bundle.filament_presets.size())); + // A mixed filament's slot names its first component's preset, which belongs to that component's slot: a mixed + // slot has no filament tab of its own. + if (const std::optional refusal = Ops::mixed_slot_refusal(slot)) + throw refused(*refusal); const std::string& name = bundle.filament_presets[size_t(slot - 1)]; if (for_write) edit_filament_slot(slot); @@ -1470,13 +1585,15 @@ json change_keys(const json& changes) return keys; } -// The 1-based filament slots that use the preset `name`. +// The 1-based filament slots that use the preset `name`: the physical ones, since a mixed filament's slot names its +// first component's preset without using it. json filament_slots(const std::string& name) { - const std::vector& presets = wxGetApp().preset_bundle->filament_presets; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::vector& presets = bundle.filament_presets; json slots = json::array(); for (std::size_t s = 0; s < presets.size(); ++s) - if (presets[s] == name) + if (presets[s] == name && !bundle.is_mixed_filament(s)) slots.push_back(int(s + 1)); return slots; } @@ -2531,15 +2648,10 @@ json read_target(const json& args, const ConfigTarget& t, bool listing) if (const auto place = places.find(key); place != places.end()) item["meta"]["where"] = place->second; if (t.project) { - if (key == "curr_bed_type" || key == "prime_volume_mode") + if (key == "curr_bed_type") item["meta"]["offered"] = project_offered(key); if (project_key_read_only(key)) item["meta"]["read_only"] = true; - if (key == "flush_volumes_matrix") - item["meta"]["description"] = "Purge volume in cubic millimeters for each change from one filament (row) to another " - "(column), stored before flush_multiplier: the Flushing volumes dialog shows " - "and edits each entry multiplied by its nozzle's flush_multiplier, and the " - "G-code purges that product."; } else if (t.object == nullptr) { if (json v = variant_entries(key, *t.config, extruders.first, extruders.second); !v.is_null()) item["meta"].update(v); @@ -3270,13 +3382,12 @@ void register_config_tools(CommandCatalog& catalog) catalog.add(inspect_tool( "project_get_settings", L("Read the project's settings"), - "Read the settings the project stores outside any preset: the plate type (curr_bed_type), slot colours " - "(filament_colour), flushing volumes (flush_volumes_matrix, flush_multiplier), purge mode (prime_volume_mode), " - "prime tower position per plate (wipe_tower_x, wipe_tower_y), mixed slots (filament_is_mixed) and, with several " - "extruders, the filament grouping (filament_map_mode, filament_map); all of them, or those named in keys. Each item " - "has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is set " - "elsewhere.", - object_schema({{"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"filament_colour\"].")}, + "Read the project's own settings for its plates: the plate type (curr_bed_type), the prime tower position per plate " + "(wipe_tower_x, wipe_tower_y) and, with several extruders, the filament grouping (filament_map_mode, filament_map); " + "all of them, or those named in keys. The filament list's colours, mixed filaments and flushing are filament_list's. " + "Each item has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is " + "set elsewhere.", + object_schema({{"keys", array_prop({{"type", "string"}}, "Setting keys, e.g. [\"curr_bed_type\"].")}, {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { @@ -3287,12 +3398,11 @@ void register_config_tools(CommandCatalog& catalog) catalog.add(mutate_tool( "project_set_settings", L("Change the project's settings"), - "Change the project's own settings as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB " - "per slot), flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's " - "origin, one per plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over " - "every slot, before the multiplier; a mixed slot's entries must be given as they are, and a colour change can " - "recalculate it, so set it last. Values are checked before anything changes; a prime tower move is one undo step. " - "Reply: applied, changed, and a note when the app moved a prime tower that did not fit.", + "Change the project's own settings as their controls write them: curr_bed_type, as the plate type selector, and " + "wipe_tower_x/y (mm from the plate's origin, one per plate), as a prime tower's drag. The filament list's colours " + "and flushing are set with filament_set_colour and filament_set_flushing. Values are checked before anything " + "changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower " + "that did not fit.", object_schema({{"values", {{"type", "object"}, {"description", "{key: value}, or {key: {index, value}} for one entry"}}}}, {"values"}), [](const json& args, ToolContext& ctx) { return set_project_settings(args, ctx); })); @@ -3465,11 +3575,31 @@ void register_config_tools(CommandCatalog& catalog) // The + and - buttons above the filament list and a slot's Delete menu item, each named as the button or menu item is, in the Speed // Dial's section Filament. const std::string slot_buttons = "Refused for a printer that has one filament per extruder, which shows no + and - buttons."; + catalog.add(inspect_tool( + "filament_list", L("List the filaments"), + "Read the filament list as the sidebar shows it. filaments has a row per slot in config order, the physical " + "filaments first, then the mixed ones: filament_slot (1-based), mixed, colour (#RRGGBB) and, for a physical " + "filament, preset and type; for a mixed filament, components (the physical slots it mixes, 1-based, 0 for one " + "deleted), ratios (whole percentages, as filament_add_mixed takes them), gradient (null, or {bottom, top: the " + "components that lead at the bottom and at the top, per_part, curve: linear or custom}) and broken (a component " + "deleted or of another filament type: the sidebar marks it, slicing an object on it is refused, and " + "filament_edit_mixed repairs it). Then the flushing the list's Flushing volumes and Purge mode buttons set: " + "flush_multiplier (one per nozzle), flush_volumes_matrix (per nozzle, slots x slots from row to column in config " + "order over every slot, before the multiplier: the dialog shows each entry multiplied by its nozzle's multiplier, " + "and the G-code purges that product) and prime_volume_mode, with prime_volume_modes where the printer offers a " + "choice. The printer keeps all of it across new projects and restarts; a saved project keeps its own.", + object_schema({}), + [](const json&, ToolContext& ctx) { + return ToolResult::ok(ctx.run_ui([] { + ui_plater(); + return filament_list(); + })); + })); catalog.add(reaching({"add_filament_slot"}, own_action(menu_command("filament_add", L("Add Filament Slot"), "Add a filament slot, as the + button above the filament list does. It takes the next " - "colour and the last slot's preset (change them with preset_select filament_slot and " - "project_set_settings filament_colour). It goes after the physical slots: mixed " + "colour and the last slot's preset (change them with filament_set_colour and " + "preset_select filament_slot). It goes after the physical slots: mixed " "filaments move up by one, and objects on them follow. " + slot_buttons + " Reply: filament_slot (the new slot) and filament_slots (how many the " "project has).", @@ -3480,11 +3610,17 @@ void register_config_tools(CommandCatalog& catalog) own_action(menu_command("filament_delete", L("Delete Filament Slot"), "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; " "with merge_into, as its Merge with item does, the objects on it taking that slot. The slots after " - "it move down by one. A mixed filament (project_get_settings filament_is_mixed) is deleted as " - "the mixed filament list deletes it, and not merged. Refused: the only physical slot, and a " - "slot a mixed filament mixes, which the mix needs (delete the mix first). " + + "it move down by one. A mixed filament (filament_list's mixed rows) is deleted as the mixed " + "filament list deletes it, and not merged. A physical filament that a mixed filament mixes is " + "deleted as the sidebar deletes it: the mix is broken (broken_mixed) until filament_edit_mixed " + "names its filaments again. A merge into a mixed filament that mixes the slot asks first, as Merge " + "with does, and replies blocked_by_dialog, unless break_mix answers: true merges, false refuses " + "(mixed_uses_slot). Refused: the only physical slot, and a mixed filament while one physical " + "slot is left, where the sidebar hides the mixed filaments (filament_add first). " + slot_buttons + " Not in the undo history. Reply: filament_slot (the slot deleted), merged_into " - "(the slot its objects went to, as numbered afterwards) and filament_slots.", + "(the slot its objects went to, as numbered afterwards), filament_slots, and " + "broken_mixed (the mixed filaments broken afterwards, as numbered then) where " + "there are any.", object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The 1-based filament slot. Default: the last " @@ -3492,10 +3628,33 @@ void register_config_tools(CommandCatalog& catalog) {"merge_into", {{"type", "integer"}, {"minimum", 1}, {"description", "The 1-based slot the objects on it go to, as Merge " - "with does. Default: they take the first filament."}}}}), + "with does. Default: they take the first filament."}}}, + {"break_mix", prop("boolean", "The answer to Merge with's question about a merge into " + "a mixed filament that mixes the slot: true merges, " + "false merges nothing. Default: the question opens.")}}), json(), filament_delete_command), L("Filament"), "delete_filament"))); + // The Add and Edit Mixed Filament dialogs' controls, for an agent that drives a dialog to set a gradient. + const std::string mixed_dialog = + "replies blocked_by_dialog. Its controls are named filament_1 to filament_3 (the components), gradient, " + "gradient_direction (item 0 puts the first filament at the bottom, item 1 the second) and per_part_gradient, for " + "widget_set_value with within the dialog's title; the gradient shows for a mix of two filaments only, and its curve " + "is drawn, changed only by dragging it (mouse_gesture). Its OK makes what it shows; Cancel changes nothing."; + const auto mix_props = [](const char* components) { + return std::vector{ + {"components", array_prop({{"type", "integer"}, {"minimum", 1}}, components)}, + {"ratios", array_prop({{"type", "integer"}, {"exclusiveMinimum", 0}}, + "Each component's share in percent, in the order of components, adding up to 100.")}}; + }; + const auto mix_args = [](const json& args, std::vector& components, std::vector& ratios) { + for (const json& component : args.value("components", json::array())) + components.push_back(component.get()); + for (const json& ratio : args.value("ratios", json::array())) + ratios.push_back(ratio.get()); + }; + const std::vector add_props = mix_props("The physical filament slots to mix, 1-based, two or more, each once, of " + "filaments of one type. Omitted with ratios: the dialog opens."); NativeCommand mixed = reaching( {"add_mixed_filament"}, mutate_tool( @@ -3503,28 +3662,23 @@ void register_config_tools(CommandCatalog& catalog) "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as " "the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots " "(1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to " - "100. It goes after every other slot. A mix the " - "project has already is not added again: the reply names its slot. Not in the undo history. Reply: " - "filament_slot (1-based) and added (false for a mix the project had).", - object_schema({{"components", array_prop({{"type", "integer"}, {"minimum", 1}}, - "The physical filament slots to mix, 1-based, two or more, each once, of " - "filaments of one type.")}, - {"ratios", array_prop({{"type", "integer"}, {"exclusiveMinimum", 0}}, - "Each component's share in percent, in the order of components, adding up to " - "100.")}}, - {"components", "ratios"}), - [](const json& args, ToolContext& ctx) { + "100. It goes after every other slot. A mix the project has already is not added again: the reply names its " + "slot. With neither components nor ratios it opens the Add Mixed Filament dialog, as the sidebar's button does, " + "and " + mixed_dialog + " Not in the undo history. Reply: filament_slot (1-based, where one was added or " + "found) and added (false for a mix the project had, or a dialog cancelled).", + object_schema({add_props[0], add_props[1]}), + [mix_args](const json& args, ToolContext& ctx) { Ops::AddMixedFilamentArgs op; - for (const json& component : args.at("components")) - op.components.push_back(component.get()); - for (const json& ratio : args.at("ratios")) - op.ratios.push_back(ratio.get()); + mix_args(args, op.components, op.ratios); json reply = ctx.run_ui([&] { ui_plater(); const Ops::Outcome mixed = Ops::add_mixed_filament(op); if (!mixed) throw refused(mixed.refusal()); - return json{{"filament_slot", mixed.value().filament_slot}, {"added", mixed.value().added}}; + json out{{"added", mixed.value().added}}; + if (mixed.value().filament_slot > 0) + out["filament_slot"] = mixed.value().filament_slot; + return out; }); settle(ctx); return ToolResult::ok(reply); @@ -3536,6 +3690,73 @@ void register_config_tools(CommandCatalog& catalog) {"tool": "filament_add_mixed", "args": {"components": [1, 2, 3], "ratios": [25, 25, 50]}}]}])json"); catalog.add(std::move(mixed)); + const std::vector edit_props = mix_props("The physical filament slots it mixes from now on, as filament_add_mixed " + "takes them. Omitted with ratios: the dialog opens."); + NativeCommand edit_mixed = reaching( + {"edit_mixed_filament"}, + mutate_tool( + "filament_edit_mixed", L("Edit Mixed Filament"), + "Change a mixed filament (filament_list's mixed rows) as the Edit Mixed Filament dialog's OK does: components " + "and ratios as filament_add_mixed takes them. The slot keeps its number and the objects on it, and its colour " + "becomes the blend; a gradient stays for a mix of two filaments and goes for more, as the dialog shows none for " + "them. An edit that names its filaments again repairs a broken mix. With filament_slot alone it opens the Edit " + "Mixed Filament dialog on the mix, as a click on its swatch does, and " + mixed_dialog + + " Not in the undo history. Reply: filament_slot and changed.", + object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The mixed filament's 1-based slot."}}}, + edit_props[0], edit_props[1]}, + {"filament_slot"}), + [mix_args](const json& args, ToolContext& ctx) { + Ops::EditMixedFilamentArgs op; + op.filament_slot = arg_int(args, "filament_slot", 1); + mix_args(args, op.components, op.ratios); + json reply = ctx.run_ui([&] { + ui_plater(); + const Ops::Outcome edited = Ops::edit_mixed_filament(op); + if (!edited) + throw refused(edited.refusal()); + return json{{"filament_slot", edited.value().filament_slot}, {"changed", edited.value().changed}}; + }); + settle(ctx); + return ToolResult::ok(reply); + })); + edit_mixed.examples = json::parse(R"json([ + {"title": "Make the mixed filament in slot 3 mostly its first filament", "calls": [ + {"tool": "filament_edit_mixed", "args": {"filament_slot": 3, "components": [1, 2], "ratios": [75, 25]}}]}])json"); + catalog.add(std::move(edit_mixed)); + + catalog.add(mutate_tool( + "filament_set_colour", L("Set a filament's colour"), + "Set a physical filament slot's colour, as its colour button's picker does: colour is #RRGGBB. Where Auto flush " + "after changing is on, the flushing volumes are recalculated, so set flush_volumes_matrix (filament_set_flushing) " + "after the colours. A mixed filament's colour is its components' blend and is not set. Reply: filament_slot, " + "colour (as stored, upper case) and changed.", + object_schema({{"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "The 1-based filament slot."}}}, + {"colour", prop("string", "#RRGGBB.")}}, + {"filament_slot", "colour"}), + [](const json& args, ToolContext& ctx) { return set_filament_colour(args, ctx); })); + + catalog.add(mutate_tool( + "filament_set_flushing", L("Set the flushing"), + "Change the flushing the filament list's Flushing volumes and Purge mode buttons set, as their dialogs' OK does, " + "any of: flush_multiplier (one per nozzle, or one value for all, within the Flushing volumes dialog's range), " + "flush_volumes_matrix (per nozzle, slots x slots from row to column in config order over every slot, before the " + "multiplier; whole, or one entry as {index, value}; a mixed filament's entries, which are never flushed, must be " + "given as they are) and prime_volume_mode (one of filament_list's prime_volume_modes). A colour change " + "(filament_set_colour) can recalculate the matrix, so set it after the colours. Values are checked before " + "anything changes. Reply: applied and changed.", + object_schema({{"flush_multiplier", {{"type", {"number", "array"}}, {"description", "One value, or one per nozzle."}}}, + {"flush_volumes_matrix", {{"type", {"array", "object"}}, {"description", "The whole matrix, or {index, value}."}}}, + {"prime_volume_mode", prop("string", "The purge mode, e.g. \"Default\".")}}), + [](const json& args, ToolContext& ctx) { + json values = json::object(); + for (const char* key : {"flush_multiplier", "flush_volumes_matrix", "prime_volume_mode"}) + if (args.contains(key)) + values[key] = args[key]; + if (values.empty()) + throw ToolFailure("Give flush_multiplier, flush_volumes_matrix or prime_volume_mode"); + return set_project_values(values, ctx, true); + })); + const std::string ams = "Synchronize the filament list from the connected printer's AMS."; NativeCommand sync_ams = reaching( {"sync_filaments_from_ams"}, diff --git a/src/slic3r/GUI/MixedFilamentDialog.cpp b/src/slic3r/GUI/MixedFilamentDialog.cpp index d15d14c74d..bfbe1f2c25 100644 --- a/src/slic3r/GUI/MixedFilamentDialog.cpp +++ b/src/slic3r/GUI/MixedFilamentDialog.cpp @@ -297,6 +297,9 @@ void MixedFilamentDialog::append_material_row() auto* combo = new ComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(FromDIP(166), FromDIP(24)), 0, nullptr, wxCB_READONLY); combo->SetKeepDropArrow(true); + // Named so that automation finds each component's selector (widget_set_value {"target": {"name": "filament_1"}}), + // as it finds the gradient controls below. + combo->SetName(wxString::Format("filament_%d", (int)(m_combo_filaments.size() + 1))); combo->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent&) { on_filament_changed(); }); row->Add(combo, 1, wxALIGN_CENTER_VERTICAL); @@ -1071,6 +1074,7 @@ wxBoxSizer* MixedFilamentDialog::create_gradient_section() m_gradient_sizer = new wxBoxSizer(wxHORIZONTAL); m_chk_gradient = new ::CheckBox(this); + m_chk_gradient->SetName("gradient"); m_chk_gradient->SetValue(m_result.gradient_enabled); m_chk_gradient->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { e.Skip(); on_gradient_toggled(); }); m_gradient_sizer->Add(m_chk_gradient, 0, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(4)); @@ -1082,6 +1086,8 @@ wxBoxSizer* MixedFilamentDialog::create_gradient_section() m_combo_gradient_dir = new ComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(FromDIP(152), FromDIP(24)), 0, nullptr, wxCB_READONLY); m_combo_gradient_dir->SetKeepDropArrow(true); + // Its items are pictures of the two filaments, the first item the first filament at the bottom. + m_combo_gradient_dir->SetName("gradient_direction"); update_gradient_direction_items(); m_combo_gradient_dir->SetSelection(m_result.gradient_direction); m_combo_gradient_dir->Bind(wxEVT_COMBOBOX, [this](wxCommandEvent&) { on_gradient_direction_changed(); }); @@ -1112,6 +1118,7 @@ wxBoxSizer* MixedFilamentDialog::create_gradient_section() m_per_part_gradient_sizer = new wxBoxSizer(wxHORIZONTAL); m_chk_per_part_gradient = new ::CheckBox(this); + m_chk_per_part_gradient->SetName("per_part_gradient"); m_chk_per_part_gradient->SetValue(m_result.per_part_gradient); m_chk_per_part_gradient->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { e.Skip(); on_per_part_gradient_toggled(); }); diff --git a/src/slic3r/GUI/Operations/PresetOps.cpp b/src/slic3r/GUI/Operations/PresetOps.cpp index 85d0b01f83..e10f31e87a 100644 --- a/src/slic3r/GUI/Operations/PresetOps.cpp +++ b/src/slic3r/GUI/Operations/PresetOps.cpp @@ -6,6 +6,7 @@ #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/MixedFilamentDialog.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/DeviceCore/DevManager.h" #include "slic3r/GUI/DeviceManager.hpp" @@ -15,7 +16,6 @@ #include "slic3r/GUI/Tab.hpp" #include "libslic3r/Config.hpp" -#include "libslic3r/FilamentMixer.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/ProjectTask.hpp" @@ -420,20 +420,39 @@ Refusal too_many_filaments() { return {RefusalKind::Precondition, "too_many_fila Refusal last_filament_slot() { return {RefusalKind::Precondition, "last_filament_slot", L("The only filament slot cannot be deleted.")}; } -// The 1-based slot of a mixed filament that mixes the physical slot `slot`, or 0 when none does. -int mix_using(const PresetBundle& bundle, int slot) +Refusal components_and_ratios() { - const auto* components = bundle.project_config.option("filament_mixed_components"); - if (components == nullptr) - return 0; - for (std::size_t i = 0; i < components->values.size() && i < bundle.filament_presets.size(); ++i) { - if (!bundle.is_mixed_filament(i)) - continue; - const std::vector mixed = parse_mixed_components(components->values[i]); - if (std::find(mixed.begin(), mixed.end(), unsigned(slot)) != mixed.end()) - return int(i) + 1; + return {RefusalKind::Precondition, "components_and_ratios", + L("Give the filaments and their ratios together, or neither for the dialog.")}; +} + +// The filament types of the filaments a mix can mix, the physical ones, a selector each, as the sidebar reads them +// for its mixed filament list (slot 1 first; a preset with no type counts as PLA). +std::vector physical_filament_types(Sidebar& sidebar, PresetBundle& presets) +{ + std::vector types; + for (std::size_t slot = 0; slot < sidebar.combos_filament().size(); ++slot) { + Preset* preset = slot < presets.filament_presets.size() ? presets.filaments.find_preset(presets.filament_presets[slot]) : + nullptr; + std::string display; + std::string type = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); + types.push_back(type.empty() ? "PLA" : type); } - return 0; + return types; +} + +// What a mixed filament is, as the project stores it: its components, ratios, gradient and colour, to tell whether an +// edit changed it. +std::vector mixed_definition(const PresetBundle& bundle, std::size_t index) +{ + std::vector out; + for (const char* key : {"filament_mixed_components", "filament_mixed_sublayer_ratios", "filament_mixed_gradient", + "filament_mixed_gradient_range", "filament_mixed_gradient_curve", "filament_mixed_gradient_per_part", + "filament_colour"}) { + const auto* vec = dynamic_cast(bundle.project_config.option(key)); + out.push_back(vec != nullptr && index < vec->size() ? vec->vserialize()[index] : std::string()); + } + return out; } } // namespace @@ -493,33 +512,40 @@ Outcome delete_filament_slot(const DeleteFilamentArgs& args) L("Filament slot %1% is a mixed filament, which can be deleted but not merged."), {std::to_string(slot)}}; if (!mixed && physical < 2) return last_filament_slot(); + // With one physical filament the sidebar hides the mixed filament list and deletes nothing + // (Sidebar::delete_filament()), so a mix left then stays until a slot is added. + if (mixed && physical < 2) + return Refusal{RefusalKind::Precondition, "mixed_list_hidden", + L("With one physical filament the mixed filaments are hidden and cannot be deleted; add a filament slot first.")}; Sidebar& sidebar = plater.sidebar(); - if (args.merge_into && sidebar.merge_removes_component(std::size_t(slot) - 1, std::size_t(*args.merge_into) - 1)) + // Merge with asks before it merges a filament into a mixed filament that mixes it, which leaves the mix broken. + const bool breaks_mix = args.merge_into && + sidebar.merge_removes_component(std::size_t(slot) - 1, std::size_t(*args.merge_into) - 1); + if (breaks_mix && args.break_mix == std::optional(false)) return Refusal{RefusalKind::Precondition, "mixed_uses_slot", - L("The target mixed filament uses this physical filament as a component. " - "Merging will remove this physical filament and may invalidate the mixed filament. Continue?")}; - // The sidebar deletes a physical filament a mix uses and leaves the mix naming a slot that is gone, which nothing - // can repair; the operation refuses it, so a caller deletes the mix first. - if (!mixed) { - if (const int mix = mix_using(bundle, slot)) - return Refusal{RefusalKind::Precondition, "mixed_uses_slot", - // TRN %1% is a filament slot number, %2% the slot of the mixed filament that mixes it. - L("Filament slot %1% is mixed in the mixed filament of slot %2%; delete that mixed filament first."), - {std::to_string(slot), std::to_string(mix)}}; - } - if (args.merge_into) { + // TRN %1% is a filament slot number, %2% the slot of the mixed filament that mixes it. + L("Merging filament slot %1% into the mixed filament of slot %2% removes a filament that mixed filament mixes."), + {std::to_string(slot), std::to_string(*args.merge_into)}}; + if (breaks_mix && args.break_mix.value_or(false)) + sidebar.delete_filament(std::size_t(slot) - 1, *args.merge_into - 1); // what Merge with does after its question's OK + else if (args.merge_into) sidebar.change_filament(std::size_t(slot) - 1, std::size_t(*args.merge_into) - 1); - } else { + else sidebar.delete_filament(std::size_t(slot) - 1); - } sidebar.update_filaments_counter(); - if (int(bundle.filament_presets.size()) == slots) + if (int(bundle.filament_presets.size()) == slots) { + if (breaks_mix && !args.break_mix) + // TRN %1% is a filament slot number. + return Refusal{RefusalKind::Failed, "merge_cancelled", L("Merging filament slot %1% was cancelled."), {std::to_string(slot)}}; return Refusal{RefusalKind::Failed, "not_deleted", L("The filament slot was not deleted.")}; + } DeletedFilament deleted; deleted.filament_slot = slot; // The slots after the deleted one move down by one. if (args.merge_into) deleted.merged_into = *args.merge_into > slot ? *args.merge_into - 1 : *args.merge_into; + for (const std::size_t broken : sidebar.broken_mixed_filaments()) + deleted.broken_mixed.push_back(int(broken) + 1); return deleted; } @@ -562,36 +588,86 @@ Outcome add_mixed_filament(const AddMixedFilamentArgs& args) Plater& plater = *wxGetApp().plater(); if (std::optional refusal = filament_list_refusal(plater)) return *refusal; - Sidebar& sidebar = plater.sidebar(); - // The filaments that mix are the physical ones, a selector each, each of the type the sidebar reads for them. - PresetBundle& presets = *wxGetApp().preset_bundle; - std::vector types; - for (std::size_t slot = 0; slot < sidebar.combos_filament().size(); ++slot) { - Preset* preset = slot < presets.filament_presets.size() ? presets.filaments.find_preset(presets.filament_presets[slot]) : - nullptr; - std::string display; - std::string type = preset != nullptr ? preset->config.get_filament_type(display) : std::string(); - types.push_back(type.empty() ? "PLA" : type); + if (args.components.empty() != args.ratios.empty()) + return components_and_ratios(); + Sidebar& sidebar = plater.sidebar(); + PresetBundle& presets = *wxGetApp().preset_bundle; + const std::size_t before = presets.filament_presets.size(); + if (args.components.empty()) { + // The sidebar offers Add Mixed Filament from two physical filaments on, and up to the last slot. + if (sidebar.combos_filament().size() < 2) + return Refusal{RefusalKind::Precondition, "too_few_components", L("A mixed filament mixes two filaments or more.")}; + if (before >= std::size_t(EnforcerBlockerType::ExtruderMax)) + return too_many_filaments(); + sidebar.add_mixed_filament(); + MixedFilament mixed; + mixed.added = presets.filament_presets.size() > before; + mixed.filament_slot = mixed.added ? int(before) + 1 : 0; + return mixed; } - if (std::optional refusal = mixed_filament_refusal(types, args.components, args.ratios)) + if (std::optional refusal = mixed_filament_refusal(physical_filament_types(sidebar, presets), args.components, args.ratios)) return *refusal; const std::vector components(args.components.begin(), args.components.end()); std::vector ratios; for (double ratio : args.ratios) ratios.push_back(int(std::lround(ratio))); - const PresetBundle& bundle = *wxGetApp().preset_bundle; - const std::size_t before = bundle.filament_presets.size(); - const int index = sidebar.ensure_mixed_filament(components, ratios); + const int index = sidebar.ensure_mixed_filament(components, ratios); if (index < 0 && before >= std::size_t(EnforcerBlockerType::ExtruderMax)) return too_many_filaments(); if (index < 0) return Refusal{RefusalKind::Failed, "not_mixed", L("No mixed filament was added.")}; MixedFilament mixed; mixed.filament_slot = index + 1; - mixed.added = bundle.filament_presets.size() > before; + mixed.added = presets.filament_presets.size() > before; return mixed; } +Outcome edit_mixed_filament(const EditMixedFilamentArgs& args) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + if (std::optional refusal = filament_list_refusal(plater)) + return *refusal; + PresetBundle& presets = *wxGetApp().preset_bundle; + const std::size_t slots = presets.filament_presets.size(); + if (args.filament_slot < 1 || std::size_t(args.filament_slot) > slots) + return no_such_slot(args.filament_slot, slots); + const std::size_t index = std::size_t(args.filament_slot) - 1; + if (!presets.is_mixed_filament(index)) + // TRN %1% is a filament slot number. + return Refusal{RefusalKind::Precondition, "not_mixed_filament", L("Filament slot %1% is not a mixed filament."), + {std::to_string(args.filament_slot)}}; + if (args.components.empty() != args.ratios.empty()) + return components_and_ratios(); + Sidebar& sidebar = plater.sidebar(); + const std::vector before = mixed_definition(presets, index); + if (args.components.empty()) { + // The mixed filament list's rows, one per mix in slot order; a click on a row's swatch edits it. + const std::vector rows = plater.mixed_filament_config_indices(); + sidebar.edit_mixed_filament(std::size_t(std::find(rows.begin(), rows.end(), index) - rows.begin())); + } else { + if (std::optional refusal = mixed_filament_refusal(physical_filament_types(sidebar, presets), args.components, + args.ratios)) + return *refusal; + MixedFilamentResult result = sidebar.mixed_filament_result(index); + result.components.assign(args.components.begin(), args.components.end()); + result.ratios.clear(); + for (double ratio : args.ratios) + result.ratios.push_back(int(std::lround(ratio))); + // The dialog shows a gradient for a mix of two filaments only, and turns it off for more. + if (result.components.size() != 2) { + result.gradient_enabled = false; + result.per_part_gradient = false; + result.gradient_curve.clear(); + } + sidebar.apply_mixed_filament_edit(index, result); + } + EditedMixedFilament edited; + edited.filament_slot = args.filament_slot; + edited.changed = mixed_definition(presets, index) != before; + return edited; +} + // ---- Syncing the filament list from the AMS ---- AmsSyncState ams_sync_state() diff --git a/src/slic3r/GUI/Operations/PresetOps.hpp b/src/slic3r/GUI/Operations/PresetOps.hpp index 887c8cba40..4dbc529db3 100644 --- a/src/slic3r/GUI/Operations/PresetOps.hpp +++ b/src/slic3r/GUI/Operations/PresetOps.hpp @@ -106,7 +106,7 @@ std::vector similar_preset_names(const PresetCollection& presets, c // Refuses: not_signed_in. Outcome sync_presets(); -// ---- Filament slots: the + and - buttons above the filament list, a slot's Delete and Merge with, Add Mixed Filament ---- +// ---- Filament slots: the + and - buttons above the filament list, a slot's Delete and Merge with, the mixed filament list ---- // Adds a physical filament slot after the physical ones, as the + button does: it takes the next colour and the last // slot's preset, and the mixed filaments, with the objects on them, move up by one. Returns the new slot's number @@ -123,21 +123,28 @@ std::optional filament_delete_refusal(int slots, int slot, std::optiona struct DeleteFilamentArgs { - std::optional filament_slot; // 1-based; none: the last physical slot, as the - button - std::optional merge_into; // 1-based; none: the objects on the slot take the first filament, as its Delete does + std::optional filament_slot; // 1-based; none: the last physical slot, as the - button + std::optional merge_into; // 1-based; none: the objects on the slot take the first filament, as its Delete does + // The answer to the question Merge with asks before it merges a physical filament into a mixed filament that mixes + // it: true merges, false merges nothing; none asks it. + std::optional break_mix; }; struct DeletedFilament { int filament_slot = 0; // the slot deleted, by its number before the delete std::optional merged_into; // the slot its objects went to, by its number afterwards + std::vector broken_mixed; // the mixed filaments the sidebar marks broken afterwards, 1-based, as numbered then }; // Deletes a filament slot as its Delete menu item does, or, with merge_into, as its Merge with item does // (Sidebar::change_filament()): the objects on it go to that slot. A mixed filament is deleted as the mixed filament -// list deletes it. Not in the undo history, as none of them is. -// Refuses: filaments_unavailable, one_filament_per_extruder, the only physical slot (last_filament_slot), what -// filament_delete_refusal() gives, a merge of a mixed filament (mixed_filament_slot), a physical slot a mixed -// filament mixes (mixed_uses_slot; for a merge into that mix, with the question Merge with asks there), and a -// delete the sidebar did not make (not_deleted). +// list deletes it. A physical filament a mixed filament mixes is deleted as the sidebar deletes it, without a question: +// the mix keeps a component that is gone and is broken until it is edited (edit_mixed_filament()). Not in the undo +// history, as none of them is. +// Refuses: filaments_unavailable, one_filament_per_extruder, the only physical slot (last_filament_slot), a mixed +// filament while one physical filament is left, whose list the sidebar then hides (mixed_list_hidden), what +// filament_delete_refusal() gives, a merge of a mixed filament (mixed_filament_slot), a merge into a mixed +// filament that mixes the slot answered no ahead (mixed_uses_slot, break_mix false) or at its question +// (merge_cancelled), and a delete the sidebar did not make (not_deleted). Outcome delete_filament_slot(const DeleteFilamentArgs& args); // What keeps a mixed filament of `components` (1-based filament slots) in `ratios` (percentages, one per component) @@ -151,20 +158,44 @@ std::optional mixed_filament_refusal(const std::vector& ty struct AddMixedFilamentArgs { - std::vector components; // 1-based physical filament slots + std::vector components; // 1-based physical filament slots; none, with no ratios: the dialog std::vector ratios; // whole percentages, one per component, as the dialog sets them }; struct MixedFilament { - int filament_slot = 0; // 1-based - bool added = false; // false: the project mixes these filaments in these ratios already, in that slot + int filament_slot = 0; // 1-based; 0 when the dialog added none + bool added = false; // false: the project mixes these filaments in these ratios already, in that slot, or + // the dialog was cancelled }; // Adds a mixed filament as the Add Mixed Filament dialog's OK does for these filaments and ratios with no gradient -// (Sidebar::ensure_mixed_filament()), in a slot after every other; a mix the project has already is that slot. -// Refuses: filaments_unavailable, what mixed_filament_refusal() gives, too_many_filaments, and not_mixed where the -// sidebar made none. +// (Sidebar::ensure_mixed_filament()), in a slot after every other; a mix the project has already is that slot. With +// neither components nor ratios, opens that dialog as the sidebar's Add Mixed Filament button does, and the mix is what +// its OK makes, gradient included. +// Refuses: filaments_unavailable, components_and_ratios (one given without the other), what mixed_filament_refusal() +// gives, too_few_components (for the dialog, fewer than two physical filaments, where the sidebar offers no +// mix), too_many_filaments, and not_mixed where the sidebar made none. Outcome add_mixed_filament(const AddMixedFilamentArgs& args); +struct EditMixedFilamentArgs +{ + int filament_slot = 0; // 1-based, a mixed filament + std::vector components; // 1-based physical filament slots; none, with no ratios: the dialog + std::vector ratios; // whole percentages, one per component +}; +struct EditedMixedFilament +{ + int filament_slot = 0; // 1-based, as before the edit + bool changed = false; +}; +// Changes a mixed filament as the Edit Mixed Filament dialog's OK does for these filaments and ratios +// (Sidebar::apply_mixed_filament_edit()): the slot keeps its number and the objects on it, its colour becomes the +// blend, and a gradient stays for a mix of two filaments and goes for more, which the dialog shows no gradient for. +// With neither components nor ratios, opens that dialog on the mix as a click on its swatch does, and the mix is what +// its OK makes. A mix the sidebar marks broken is repaired by an edit that names its filaments again. +// Refuses: filaments_unavailable, no_such_slot, not_mixed_filament (a physical slot), components_and_ratios, and what +// mixed_filament_refusal() gives. +Outcome edit_mixed_filament(const EditMixedFilamentArgs& args); + // ---- Syncing the filament list from the AMS: Synchronize Filament List from AMS and its dialog ---- // The sync dialog's two choices: map each of the project's filaments to a slot of the printer, or overwrite the filament diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 6f77c5dc6b..c27f110598 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -4374,7 +4374,6 @@ void Sidebar::update_mixed_filament_list() auto mixed_indices = plater->mixed_filament_config_indices(); size_t num_physical = p->combos_filament.size(); - auto* is_mixed_opt = project_config.option("filament_is_mixed"); auto* components_opt = project_config.option("filament_mixed_components"); auto* ratios_opt = project_config.option("filament_mixed_sublayer_ratios"); auto* colours_opt = project_config.option("filament_colour"); @@ -4384,34 +4383,8 @@ void Sidebar::update_mixed_filament_list() bool can_mix = (num_physical >= 2); bool has_mixed = can_mix && !mixed_indices.empty(); - // Check integrity of mixed filament component references - std::vector broken_slots; - if (is_mixed_opt && components_opt) - broken_slots = check_mixed_filament_integrity(is_mixed_opt->values, components_opt->values, num_physical); - std::set broken_set(broken_slots.begin(), broken_slots.end()); - - // Type consistency check - if (is_mixed_opt && components_opt) { - std::vector physical_types; - auto& preset_bundle = *wxGetApp().preset_bundle; - for (size_t i = 0; i < num_physical; ++i) { - std::string ft; - if (i < preset_bundle.filament_presets.size()) { - auto* preset = preset_bundle.filaments.find_preset(preset_bundle.filament_presets[i]); - if (preset) { - std::string display_type; - ft = preset->config.get_filament_type(display_type); - } - } - if (ft.empty()) ft = "PLA"; - physical_types.push_back(ft); - } - auto type_mismatch_slots = check_mixed_filament_type_consistency( - is_mixed_opt->values, components_opt->values, physical_types); - for (size_t s : type_mismatch_slots) - broken_set.insert(s); - broken_slots.insert(broken_slots.end(), type_mismatch_slots.begin(), type_mismatch_slots.end()); - } + const std::vector broken_slots = broken_mixed_filaments(); + std::set broken_set(broken_slots.begin(), broken_slots.end()); bool at_limit = (wxGetApp().preset_bundle->filament_presets.size() >= size_t(EnforcerBlockerType::ExtruderMax)); p->m_btn_add_mixed_filament->Show(can_mix && !has_mixed && !at_limit); @@ -4900,41 +4873,46 @@ bool Sidebar::has_broken_mixed_filament() const return has_broken_mixed_filament(plater->get_partplate_list().get_curr_plate()); } +std::vector Sidebar::broken_mixed_filaments() const +{ + auto& preset_bundle = *wxGetApp().preset_bundle; + auto* is_mixed_opt = preset_bundle.project_config.option("filament_is_mixed"); + auto* comp_strs_opt = preset_bundle.project_config.option("filament_mixed_components"); + if (!is_mixed_opt || !comp_strs_opt) + return {}; + + const size_t num_physical = p->combos_filament.size(); + std::vector broken = check_mixed_filament_integrity(is_mixed_opt->values, comp_strs_opt->values, num_physical); + + // A mix of filaments of different types, which the Add Mixed Filament dialog does not take. + std::vector physical_types; + for (size_t i = 0; i < num_physical; ++i) { + std::string ft; + if (i < preset_bundle.filament_presets.size()) { + auto* preset = preset_bundle.filaments.find_preset(preset_bundle.filament_presets[i]); + if (preset) { + std::string display_type; + ft = preset->config.get_filament_type(display_type); + } + } + if (ft.empty()) ft = "PLA"; + physical_types.push_back(ft); + } + const std::vector type_mismatch_slots = check_mixed_filament_type_consistency(is_mixed_opt->values, comp_strs_opt->values, + physical_types); + broken.insert(broken.end(), type_mismatch_slots.begin(), type_mismatch_slots.end()); + std::sort(broken.begin(), broken.end()); + broken.erase(std::unique(broken.begin(), broken.end()), broken.end()); + return broken; +} + bool Sidebar::has_broken_mixed_filament(const PartPlate* plate) const { if (!plate) return false; auto* plater = dynamic_cast(GetParent()); if (!plater) return false; - auto& project_config = wxGetApp().preset_bundle->project_config; - auto* is_mixed_opt = project_config.option("filament_is_mixed"); - auto* comp_strs_opt = project_config.option("filament_mixed_components"); - if (!is_mixed_opt || !comp_strs_opt) return false; - - size_t num_physical = p->combos_filament.size(); - auto broken_slots = check_mixed_filament_integrity(is_mixed_opt->values, comp_strs_opt->values, num_physical); - - // Type consistency check - { - std::vector physical_types; - auto& preset_bundle = *wxGetApp().preset_bundle; - for (size_t i = 0; i < num_physical; ++i) { - std::string ft; - if (i < preset_bundle.filament_presets.size()) { - auto* preset = preset_bundle.filaments.find_preset(preset_bundle.filament_presets[i]); - if (preset) { - std::string display_type; - ft = preset->config.get_filament_type(display_type); - } - } - if (ft.empty()) ft = "PLA"; - physical_types.push_back(ft); - } - auto type_mismatch_slots = check_mixed_filament_type_consistency( - is_mixed_opt->values, comp_strs_opt->values, physical_types); - broken_slots.insert(broken_slots.end(), type_mismatch_slots.begin(), type_mismatch_slots.end()); - } - + const std::vector broken_slots = broken_mixed_filaments(); if (broken_slots.empty()) return false; std::set broken_1based; @@ -5223,6 +5201,13 @@ void Sidebar::edit_mixed_filament(size_t panel_idx) std::vector color_strs, names, types; collect_physical_filament_info(color_strs, names, types); + MixedFilamentDialog dlg(this, mixed_filament_result(cfg_idx), color_strs, names, types); + if (dlg.ShowModal() == wxID_OK) + apply_mixed_filament_edit(cfg_idx, dlg.get_result()); +} + +MixedFilamentResult Sidebar::mixed_filament_result(size_t cfg_idx) const +{ auto& project_config = wxGetApp().preset_bundle->project_config; MixedFilamentResult existing; auto* components_opt = project_config.option("filament_mixed_components"); @@ -5283,90 +5268,97 @@ void Sidebar::edit_mixed_filament(size_t panel_idx) auto* per_part_opt = project_config.option("filament_mixed_gradient_per_part"); if (existing.gradient_enabled && per_part_opt && cfg_idx < per_part_opt->values.size()) existing.per_part_gradient = per_part_opt->values[cfg_idx]; + return existing; +} - MixedFilamentDialog dlg(this, existing, color_strs, names, types); - if (dlg.ShowModal() == wxID_OK) { - auto result = dlg.get_result(); - if (result.components.size() < 2 || result.ratios.size() < 2) return; +void Sidebar::apply_mixed_filament_edit(size_t cfg_idx, const MixedFilamentResult& result) +{ + if (result.components.size() < 2 || result.ratios.size() < 2) return; - // Serialize components - std::string comp_str; - for (size_t i = 0; i < result.components.size(); ++i) { - if (i > 0) comp_str += ","; - comp_str += std::to_string(result.components[i]); - } - components_opt->values[cfg_idx] = comp_str; + std::vector color_strs, names, types; + collect_physical_filament_info(color_strs, names, types); - // Serialize ratios - int ratio_sum = 0; - for (int r : result.ratios) ratio_sum += r; - if (ratio_sum <= 0) ratio_sum = 100; + auto& project_config = wxGetApp().preset_bundle->project_config; + auto* components_opt = project_config.option("filament_mixed_components"); + auto* ratios_opt = project_config.option("filament_mixed_sublayer_ratios"); - std::string ratio_str; - { - CNumericLocalesSetter c_locale_setter; - for (size_t i = 0; i < result.ratios.size(); ++i) { - if (i > 0) ratio_str += ","; - char buf[32]; - std::snprintf(buf, sizeof(buf), "%.4f", (float)result.ratios[i] / ratio_sum); - ratio_str += buf; - } - } - ratios_opt->values[cfg_idx] = ratio_str; - - // Gradient settings — ensure keys exist in dynamic config - if (!project_config.option("filament_mixed_gradient")) - project_config.set_key_value("filament_mixed_gradient", new ConfigOptionBools({false})); - if (!project_config.option("filament_mixed_gradient_range")) - project_config.set_key_value("filament_mixed_gradient_range", new ConfigOptionStrings({""}) ); - if (!project_config.option("filament_mixed_gradient_curve")) - project_config.set_key_value("filament_mixed_gradient_curve", new ConfigOptionStrings({""}) ); - if (!project_config.option("filament_mixed_gradient_per_part")) - project_config.set_key_value("filament_mixed_gradient_per_part", new ConfigOptionBools({false})); - - { - auto* grad_opt = project_config.option("filament_mixed_gradient"); - while (grad_opt->values.size() <= cfg_idx) grad_opt->values.push_back(false); - grad_opt->values[cfg_idx] = result.gradient_enabled; - } - { - auto* grad_range_opt = project_config.option("filament_mixed_gradient_range"); - while (grad_range_opt->values.size() <= cfg_idx) grad_range_opt->values.push_back(""); - if (result.gradient_enabled && result.components.size() == 2) { - const char* fmt = (result.gradient_direction == 0) ? "0.9000,0.1000" : "0.1000,0.9000"; - grad_range_opt->values[cfg_idx] = fmt; - } else { - grad_range_opt->values[cfg_idx] = ""; - } - } - { - auto* grad_curve_opt = project_config.option("filament_mixed_gradient_curve"); - while (grad_curve_opt->values.size() <= cfg_idx) grad_curve_opt->values.push_back(""); - grad_curve_opt->values[cfg_idx] = serialize_mixed_gradient_curve_if_custom(result); - } - { - auto* per_part_opt = project_config.option("filament_mixed_gradient_per_part"); - while (per_part_opt->values.size() <= cfg_idx) per_part_opt->values.push_back(false); - per_part_opt->values[cfg_idx] = result.gradient_enabled && result.per_part_gradient; - } - - // Compute blended color - std::string blended = blend_mixed_color(result.components, result.ratios, color_strs); - auto* colours_opt = project_config.option("filament_colour"); - if (colours_opt && cfg_idx < colours_opt->values.size()) - colours_opt->values[cfg_idx] = blended; - - auto* multi_colour_opt = project_config.option("filament_multi_colour"); - if (multi_colour_opt && cfg_idx < multi_colour_opt->values.size()) - multi_colour_opt->values[cfg_idx] = blended; - - // The edited slot keeps its index, so nothing else refreshes the per-feature filament - // lists - and its blended colour and type are what they show for it. - update_mixed_filament_list(); - update_dynamic_filament_list(); - wxGetApp().plater()->update_project_dirty_from_presets(); - wxPostEvent(this, SimpleEvent(EVT_SCHEDULE_BACKGROUND_PROCESS, this)); + // Serialize components + std::string comp_str; + for (size_t i = 0; i < result.components.size(); ++i) { + if (i > 0) comp_str += ","; + comp_str += std::to_string(result.components[i]); } + components_opt->values[cfg_idx] = comp_str; + + // Serialize ratios + int ratio_sum = 0; + for (int r : result.ratios) ratio_sum += r; + if (ratio_sum <= 0) ratio_sum = 100; + + std::string ratio_str; + { + CNumericLocalesSetter c_locale_setter; + for (size_t i = 0; i < result.ratios.size(); ++i) { + if (i > 0) ratio_str += ","; + char buf[32]; + std::snprintf(buf, sizeof(buf), "%.4f", (float)result.ratios[i] / ratio_sum); + ratio_str += buf; + } + } + ratios_opt->values[cfg_idx] = ratio_str; + + // Gradient settings — ensure keys exist in dynamic config + if (!project_config.option("filament_mixed_gradient")) + project_config.set_key_value("filament_mixed_gradient", new ConfigOptionBools({false})); + if (!project_config.option("filament_mixed_gradient_range")) + project_config.set_key_value("filament_mixed_gradient_range", new ConfigOptionStrings({""}) ); + if (!project_config.option("filament_mixed_gradient_curve")) + project_config.set_key_value("filament_mixed_gradient_curve", new ConfigOptionStrings({""}) ); + if (!project_config.option("filament_mixed_gradient_per_part")) + project_config.set_key_value("filament_mixed_gradient_per_part", new ConfigOptionBools({false})); + + { + auto* grad_opt = project_config.option("filament_mixed_gradient"); + while (grad_opt->values.size() <= cfg_idx) grad_opt->values.push_back(false); + grad_opt->values[cfg_idx] = result.gradient_enabled; + } + { + auto* grad_range_opt = project_config.option("filament_mixed_gradient_range"); + while (grad_range_opt->values.size() <= cfg_idx) grad_range_opt->values.push_back(""); + if (result.gradient_enabled && result.components.size() == 2) { + const char* fmt = (result.gradient_direction == 0) ? "0.9000,0.1000" : "0.1000,0.9000"; + grad_range_opt->values[cfg_idx] = fmt; + } else { + grad_range_opt->values[cfg_idx] = ""; + } + } + { + auto* grad_curve_opt = project_config.option("filament_mixed_gradient_curve"); + while (grad_curve_opt->values.size() <= cfg_idx) grad_curve_opt->values.push_back(""); + grad_curve_opt->values[cfg_idx] = serialize_mixed_gradient_curve_if_custom(result); + } + { + auto* per_part_opt = project_config.option("filament_mixed_gradient_per_part"); + while (per_part_opt->values.size() <= cfg_idx) per_part_opt->values.push_back(false); + per_part_opt->values[cfg_idx] = result.gradient_enabled && result.per_part_gradient; + } + + // Compute blended color + std::string blended = blend_mixed_color(result.components, result.ratios, color_strs); + auto* colours_opt = project_config.option("filament_colour"); + if (colours_opt && cfg_idx < colours_opt->values.size()) + colours_opt->values[cfg_idx] = blended; + + auto* multi_colour_opt = project_config.option("filament_multi_colour"); + if (multi_colour_opt && cfg_idx < multi_colour_opt->values.size()) + multi_colour_opt->values[cfg_idx] = blended; + + // The edited slot keeps its index, so nothing else refreshes the per-feature filament + // lists - and its blended colour and type are what they show for it. + update_mixed_filament_list(); + update_dynamic_filament_list(); + wxGetApp().plater()->update_project_dirty_from_presets(); + wxPostEvent(this, SimpleEvent(EVT_SCHEDULE_BACKGROUND_PROCESS, this)); } void Sidebar::remove_all_mixed_filaments() diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index c7ad0468cb..e087b8b7c6 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -103,6 +103,7 @@ namespace UndoRedo { namespace GUI { enum class LoadType : unsigned char; class SyncAmsInfoDialog; +struct MixedFilamentResult; class MainFrame; class ConfigOptionsGroup; class ObjectSettings; @@ -350,6 +351,11 @@ public: // interleaving from its own paint mask to the slicer, where it happens per layer. int ensure_mixed_filament(const std::vector &components, const std::vector &ratios); void edit_mixed_filament(size_t idx); + // The mixed filament in filament slot `cfg_idx` (0-based) as the Edit Mixed Filament dialog opens with it. + MixedFilamentResult mixed_filament_result(size_t cfg_idx) const; + // What the Edit Mixed Filament dialog's OK does with `result` for filament slot `cfg_idx` (0-based): the slot keeps its + // number and the objects on it, and its colour becomes the components' blend. + void apply_mixed_filament_edit(size_t cfg_idx, const MixedFilamentResult& result); void delete_mixed_filament_at(size_t idx); // Drops every mixed filament at once, after confirming. The texture displacement gizmo can create // one slot per colour in its palette, so clearing them one at a time is tedious. @@ -357,6 +363,9 @@ public: void decompose_filament_color(int filament_idx); void recalc_filament_scroll_sizes(); void update_mixed_filament_list(); + // The mixed filaments the sidebar marks broken, as 0-based filament indices: a component deleted or past the physical + // filaments, fewer than two components, or components of different filament types. + std::vector broken_mixed_filaments() const; bool has_broken_mixed_filament() const; bool has_broken_mixed_filament(const PartPlate* plate) const; void collect_physical_filament_info(std::vector& color_strs, diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index d4d471aaf9..05b262c379 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -1231,7 +1231,7 @@ }, { "completion": "immediate", - "description": "Read the settings the project stores outside any preset: the plate type (curr_bed_type), slot colours (filament_colour), flushing volumes (flush_volumes_matrix, flush_multiplier), purge mode (prime_volume_mode), prime tower position per plate (wipe_tower_x, wipe_tower_y), mixed slots (filament_is_mixed) and, with several extruders, the filament grouping (filament_map_mode, filament_map); all of them, or those named in keys. Each item has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is set elsewhere.", + "description": "Read the project's own settings for its plates: the plate type (curr_bed_type), the prime tower position per plate (wipe_tower_x, wipe_tower_y) and, with several extruders, the filament grouping (filament_map_mode, filament_map); all of them, or those named in keys. The filament list's colours, mixed filaments and flushing are filament_list's. Each item has its value and meta; meta.offered lists the choices this printer has, and meta.read_only marks what is set elsewhere.", "destructive": false, "group": "The project", "guard": "inspect", @@ -1245,7 +1245,7 @@ "type": "boolean" }, "keys": { - "description": "Setting keys, e.g. [\"filament_colour\"].", + "description": "Setting keys, e.g. [\"curr_bed_type\"].", "items": { "type": "string" }, @@ -1263,7 +1263,7 @@ }, { "completion": "immediate", - "description": "Change the project's own settings as the sidebar's controls write them: curr_bed_type, filament_colour (#RRGGBB per slot), flush_multiplier, flush_volumes_matrix, prime_volume_mode, and wipe_tower_x/y (mm from the plate's origin, one per plate). flush_volumes_matrix is per nozzle, slots x slots from row to column, in config order over every slot, before the multiplier; a mixed slot's entries must be given as they are, and a colour change can recalculate it, so set it last. Values are checked before anything changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower that did not fit.", + "description": "Change the project's own settings as their controls write them: curr_bed_type, as the plate type selector, and wipe_tower_x/y (mm from the plate's origin, one per plate), as a prime tower's drag. The filament list's colours and flushing are set with filament_set_colour and filament_set_flushing. Values are checked before anything changes; a prime tower move is one undo step. Reply: applied, changed, and a note when the app moved a prime tower that did not fit.", "destructive": false, "group": "The project", "guard": "mutate", @@ -5826,10 +5826,30 @@ "read_only": false, "title": "Toggle Developer Mode" }, + { + "completion": "immediate", + "description": "Read the filament list as the sidebar shows it. filaments has a row per slot in config order, the physical filaments first, then the mixed ones: filament_slot (1-based), mixed, colour (#RRGGBB) and, for a physical filament, preset and type; for a mixed filament, components (the physical slots it mixes, 1-based, 0 for one deleted), ratios (whole percentages, as filament_add_mixed takes them), gradient (null, or {bottom, top: the components that lead at the bottom and at the top, per_part, curve: linear or custom}) and broken (a component deleted or of another filament type: the sidebar marks it, slicing an object on it is refused, and filament_edit_mixed repairs it). Then the flushing the list's Flushing volumes and Purge mode buttons set: flush_multiplier (one per nozzle), flush_volumes_matrix (per nozzle, slots x slots from row to column in config order over every slot, before the multiplier: the dialog shows each entry multiplied by its nozzle's multiplier, and the G-code purges that product) and prime_volume_mode, with prime_volume_modes where the printer offers a choice. The printer keeps all of it across new projects and restarts; a saved project keeps its own.", + "destructive": false, + "group": "Filaments", + "guard": "inspect", + "has_own_action": false, + "idempotent": true, + "input_schema": { + "additionalProperties": false, + "properties": {}, + "type": "object" + }, + "key": "filament_list", + "listed": true, + "open_world": false, + "operations": [], + "read_only": true, + "title": "List the filaments" + }, { "action_group": "Filament", "completion": "immediate", - "description": "Add a filament slot, as the + button above the filament list does. It takes the next colour and the last slot's preset (change them with preset_select filament_slot and project_set_settings filament_colour). It goes after the physical slots: mixed filaments move up by one, and objects on them follow. Refused for a printer that has one filament per extruder, which shows no + and - buttons. Reply: filament_slot (the new slot) and filament_slots (how many the project has).", + "description": "Add a filament slot, as the + button above the filament list does. It takes the next colour and the last slot's preset (change them with filament_set_colour and preset_select filament_slot). It goes after the physical slots: mixed filaments move up by one, and objects on them follow. Refused for a printer that has one filament per extruder, which shows no + and - buttons. Reply: filament_slot (the new slot) and filament_slots (how many the project has).", "destructive": false, "group": "Filaments", "guard": "mutate", @@ -5853,7 +5873,7 @@ { "action_group": "Filament", "completion": "immediate", - "description": "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; with merge_into, as its Merge with item does, the objects on it taking that slot. The slots after it move down by one. A mixed filament (project_get_settings filament_is_mixed) is deleted as the mixed filament list deletes it, and not merged. Refused: the only physical slot, and a slot a mixed filament mixes, which the mix needs (delete the mix first). Refused for a printer that has one filament per extruder, which shows no + and - buttons. Not in the undo history. Reply: filament_slot (the slot deleted), merged_into (the slot its objects went to, as numbered afterwards) and filament_slots.", + "description": "Delete a filament slot, as its Delete menu item does, the objects on it taking the first filament; with merge_into, as its Merge with item does, the objects on it taking that slot. The slots after it move down by one. A mixed filament (filament_list's mixed rows) is deleted as the mixed filament list deletes it, and not merged. A physical filament that a mixed filament mixes is deleted as the sidebar deletes it: the mix is broken (broken_mixed) until filament_edit_mixed names its filaments again. A merge into a mixed filament that mixes the slot asks first, as Merge with does, and replies blocked_by_dialog, unless break_mix answers: true merges, false refuses (mixed_uses_slot). Refused: the only physical slot, and a mixed filament while one physical slot is left, where the sidebar hides the mixed filaments (filament_add first). Refused for a printer that has one filament per extruder, which shows no + and - buttons. Not in the undo history. Reply: filament_slot (the slot deleted), merged_into (the slot its objects went to, as numbered afterwards), filament_slots, and broken_mixed (the mixed filaments broken afterwards, as numbered then) where there are any.", "destructive": false, "group": "Filaments", "guard": "mutate", @@ -5863,6 +5883,10 @@ "input_schema": { "additionalProperties": false, "properties": { + "break_mix": { + "description": "The answer to Merge with's question about a merge into a mixed filament that mixes the slot: true merges, false merges nothing. Default: the question opens.", + "type": "boolean" + }, "filament_slot": { "description": "The 1-based filament slot. Default: the last physical slot, as the - button.", "minimum": 1, @@ -5887,7 +5911,7 @@ }, { "completion": "immediate", - "description": "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots (1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to 100. It goes after every other slot. A mix the project has already is not added again: the reply names its slot. Not in the undo history. Reply: filament_slot (1-based) and added (false for a mix the project had).", + "description": "Add a mixed filament: a slot that prints its physical filaments in turn, layer by layer, in the ratios given, as the Add Mixed Filament dialog's OK does with no gradient. components are two or more of the physical slots (1-based), each named once, whose filaments are of one type; ratios a whole percentage for each, adding up to 100. It goes after every other slot. A mix the project has already is not added again: the reply names its slot. With neither components nor ratios it opens the Add Mixed Filament dialog, as the sidebar's button does, and replies blocked_by_dialog. Its controls are named filament_1 to filament_3 (the components), gradient, gradient_direction (item 0 puts the first filament at the bottom, item 1 the second) and per_part_gradient, for widget_set_value with within the dialog's title; the gradient shows for a mix of two filaments only, and its curve is drawn, changed only by dragging it (mouse_gesture). Its OK makes what it shows; Cancel changes nothing. Not in the undo history. Reply: filament_slot (1-based, where one was added or found) and added (false for a mix the project had, or a dialog cancelled).", "destructive": false, "examples": [ { @@ -5937,7 +5961,7 @@ "additionalProperties": false, "properties": { "components": { - "description": "The physical filament slots to mix, 1-based, two or more, each once, of filaments of one type.", + "description": "The physical filament slots to mix, 1-based, two or more, each once, of filaments of one type. Omitted with ratios: the dialog opens.", "items": { "minimum": 1, "type": "integer" @@ -5953,10 +5977,6 @@ "type": "array" } }, - "required": [ - "components", - "ratios" - ], "type": "object" }, "key": "filament_add_mixed", @@ -5968,6 +5988,147 @@ "read_only": false, "title": "Add Mixed Filament" }, + { + "completion": "immediate", + "description": "Change a mixed filament (filament_list's mixed rows) as the Edit Mixed Filament dialog's OK does: components and ratios as filament_add_mixed takes them. The slot keeps its number and the objects on it, and its colour becomes the blend; a gradient stays for a mix of two filaments and goes for more, as the dialog shows none for them. An edit that names its filaments again repairs a broken mix. With filament_slot alone it opens the Edit Mixed Filament dialog on the mix, as a click on its swatch does, and replies blocked_by_dialog. Its controls are named filament_1 to filament_3 (the components), gradient, gradient_direction (item 0 puts the first filament at the bottom, item 1 the second) and per_part_gradient, for widget_set_value with within the dialog's title; the gradient shows for a mix of two filaments only, and its curve is drawn, changed only by dragging it (mouse_gesture). Its OK makes what it shows; Cancel changes nothing. Not in the undo history. Reply: filament_slot and changed.", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "components": [ + 1, + 2 + ], + "filament_slot": 3, + "ratios": [ + 75, + 25 + ] + }, + "tool": "filament_edit_mixed" + } + ], + "title": "Make the mixed filament in slot 3 mostly its first filament" + } + ], + "group": "Filaments", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "components": { + "description": "The physical filament slots it mixes from now on, as filament_add_mixed takes them. Omitted with ratios: the dialog opens.", + "items": { + "minimum": 1, + "type": "integer" + }, + "type": "array" + }, + "filament_slot": { + "description": "The mixed filament's 1-based slot.", + "minimum": 1, + "type": "integer" + }, + "ratios": { + "description": "Each component's share in percent, in the order of components, adding up to 100.", + "items": { + "exclusiveMinimum": 0, + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "filament_slot" + ], + "type": "object" + }, + "key": "filament_edit_mixed", + "listed": true, + "open_world": false, + "operations": [ + "edit_mixed_filament" + ], + "read_only": false, + "title": "Edit Mixed Filament" + }, + { + "completion": "immediate", + "description": "Set a physical filament slot's colour, as its colour button's picker does: colour is #RRGGBB. Where Auto flush after changing is on, the flushing volumes are recalculated, so set flush_volumes_matrix (filament_set_flushing) after the colours. A mixed filament's colour is its components' blend and is not set. Reply: filament_slot, colour (as stored, upper case) and changed.", + "destructive": false, + "group": "Filaments", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "colour": { + "description": "#RRGGBB.", + "type": "string" + }, + "filament_slot": { + "description": "The 1-based filament slot.", + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "filament_slot", + "colour" + ], + "type": "object" + }, + "key": "filament_set_colour", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Set a filament's colour" + }, + { + "completion": "immediate", + "description": "Change the flushing the filament list's Flushing volumes and Purge mode buttons set, as their dialogs' OK does, any of: flush_multiplier (one per nozzle, or one value for all, within the Flushing volumes dialog's range), flush_volumes_matrix (per nozzle, slots x slots from row to column in config order over every slot, before the multiplier; whole, or one entry as {index, value}; a mixed filament's entries, which are never flushed, must be given as they are) and prime_volume_mode (one of filament_list's prime_volume_modes). A colour change (filament_set_colour) can recalculate the matrix, so set it after the colours. Values are checked before anything changes. Reply: applied and changed.", + "destructive": false, + "group": "Filaments", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "flush_multiplier": { + "description": "One value, or one per nozzle.", + "type": [ + "number", + "array" + ] + }, + "flush_volumes_matrix": { + "description": "The whole matrix, or {index, value}.", + "type": [ + "array", + "object" + ] + }, + "prime_volume_mode": { + "description": "The purge mode, e.g. \"Default\".", + "type": "string" + } + }, + "type": "object" + }, + "key": "filament_set_flushing", + "listed": true, + "open_world": false, + "operations": [], + "read_only": false, + "title": "Set the flushing" + }, { "actions": [ { diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index bbd8647234..3eb1158b40 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -173,7 +173,8 @@ const std::vector>> kPlaces{ {"preset_list", "preset_select", "preset_save", "preset_delete", "settings_list", "settings_get", "settings_set", "preset_import", "preset_export", "preset_sync", "settings_set_mode", "preset_migrate_filaments", "settings_toggle_developer_mode"}}, {"Filaments", - {"filament_add", "filament_delete", "filament_sync_ams", "filament_add_mixed", "filament_install", "filament_uninstall"}}, + {"filament_list", "filament_add", "filament_delete", "filament_sync_ams", "filament_add_mixed", "filament_edit_mixed", + "filament_set_colour", "filament_set_flushing", "filament_install", "filament_uninstall"}}, {"Printers and prints", {"printer_send", "printer_list_models", "printer_install", "printer_uninstall", "print_start", "printer_test_host", "printer_status", "print_pause", "print_resume", "print_stop"}}, @@ -452,9 +453,10 @@ TEST_CASE("outside the Design tab the catalog has its commands and 129 actions", CHECK(c.action_group == section.at(c.key)); } // The commands outside the Design tab: the typed tools, the commands made from menu items, the seven Parts 4a to 4c - // add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the seven gizmo commands and the six printing - // commands. - CHECK(commands == 131); + // add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the seven gizmo commands, the six printing + // commands and the four of the filament list (filament_list, filament_edit_mixed, filament_set_colour and + // filament_set_flushing). + CHECK(commands == 135); // The eight commands named as their menu items keep an action of their own; the other 121 actions are items. CHECK(own == std::set{"plate_add", "plate_delete", "plate_duplicate", "plate_rename", "filament_add", "filament_delete", "undo", "redo"}); @@ -481,7 +483,7 @@ TEST_CASE("the commands outside the Design tab are the design's, under its headi commands += keys.size(); } CHECK(by_heading.size() == kPlaces.size()); - CHECK(commands == 131); + CHECK(commands == 135); // tool_search's group says which there are. const NativeCommand* search = NativeCommands::find("tool_search"); @@ -522,8 +524,8 @@ TEST_CASE("every command that runs from arguments is in the tool list, by place" // The three menu items with no argument form, which tool_search finds and tool_call runs. CHECK(unlisted == std::set{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"}); // Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four, the - // seven gizmo commands and the six printing commands. - CHECK(listed.size() == 128); + // seven gizmo commands, the six printing commands and the filament list's four. + CHECK(listed.size() == 132); // The search, the generic call and the app's state first; then each heading's commands together, in the // design's order, Driving the GUI last. @@ -553,7 +555,7 @@ TEST_CASE("only deleting a preset, uninstalling a plugin and stopping a print ar "plate_get_settings", "project_get_settings", "plate_list", "object_list", "window_screenshot", "plate_slice_stats", "script_search_api", "action_search", "window_list", "widget_list", "printer_list_models", "plugin_list", - "printer_status"}; + "printer_status", "filament_list"}; // The commands made from menu items whose item reaches a printer, the cloud account or the network. const std::set menu_items_reaching_out{"printer_send", "preset_sync", "filament_sync_ams", "app_check_for_updates", "app_open_web_page", "plugin_refresh"}; diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index 33ab4d5d3b..fdb8d74100 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -1949,11 +1949,11 @@ TEST_CASE("every example passes its command's schema", "[Mcp][CAD]") } } // The 83 Design commands with a silent form, undo and redo, the six object and part commands of Parts 4a and 4b, - // Part 4c's filament_add_mixed, Part 5a's printer_list_models, printer_install and printer_uninstall, Part 5b's + // Part 4c's filament_add_mixed, filament_edit_mixed, Part 5a's printer_list_models, printer_install and printer_uninstall, Part 5b's // filament_install and filament_uninstall, Part 5c's preferences_set, Part 5d's plugin_list, plugin_enable, // plugin_reload and plugin_uninstall, the seven gizmo commands, and the six printing commands (print_start, // printer_test_host, printer_status, print_pause, print_resume and print_stop). - CHECK(described == 115); + CHECK(described == 116); } TEST_CASE("an example's argument goes by a name its command takes", "[Mcp][CAD]") diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index 1107bcd041..946ae37d28 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -193,8 +193,10 @@ TEST_CASE("the commands that replace a dialog take the arguments the table gives REQUIRE(names("plate_duplicate") == Names{"plate"}); REQUIRE(names("plate_rename") == Names{"plate", "name", "silent"}); REQUIRE(names("plate_lock") == Names{"plate", "locked"}); - REQUIRE(names("filament_delete") == Names{"filament_slot", "merge_into"}); + REQUIRE(names("filament_delete") == Names{"filament_slot", "merge_into", "break_mix"}); REQUIRE(names("filament_add_mixed") == Names{"components", "ratios"}); + REQUIRE(names("filament_edit_mixed") == Names{"filament_slot", "components", "ratios"}); + REQUIRE(names("filament_set_colour") == Names{"filament_slot", "colour"}); REQUIRE(names("recording_start") == recording); // The object arrange fills a plate with is named as an object, not as a count. CHECK(names("object_arrange").count("fill_object") == 1); diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 12cf535269..37aac932f7 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -408,7 +408,8 @@ TEST_CASE("preset_export takes the folder of its dialog and has no silent form", CHECK_THAT(argument_error(*export_, silent), Catch::Matchers::ContainsSubstring("silent")); } -TEST_CASE("the filament commands take the filaments they mix, and the slot a deleted one merges into", "[Mcp]") +TEST_CASE("the filament commands take the filaments they mix or open their dialog without them, and the slot a deleted one merges into", + "[Mcp]") { using Catch::Matchers::ContainsSubstring; const NativeCommand* mixed = NativeCommands::find("filament_add_mixed"); @@ -416,7 +417,10 @@ TEST_CASE("the filament commands take the filaments they mix, and the slot a del CHECK(mixed->listed); CHECK_FALSE(mixed->has_own_action); CHECK(mixed->actions.is_null()); - CHECK(mixed->input_schema["required"] == json::array({"components", "ratios"})); + // Without components and ratios it opens the Add Mixed Filament dialog; the operation refuses one without the other. + CHECK_FALSE(mixed->input_schema.contains("required")); + json dialog = json::object(); + CHECK(argument_error(*mixed, dialog).empty()); json half{{"components", json::array({1, 2})}, {"ratios", json::array({50, 50})}}; CHECK(argument_error(*mixed, half).empty()); json thirds{{"components", json::array({1, 2, 3})}, {"ratios", json::array({33, 33, 34})}}; @@ -428,8 +432,17 @@ TEST_CASE("the filament commands take the filaments they mix, and the slot a del CHECK_THAT(argument_error(*mixed, slot_zero), ContainsSubstring("components")); json no_share{{"components", json::array({1, 2})}, {"ratios", json::array({0, 100})}}; CHECK_THAT(argument_error(*mixed, no_share), ContainsSubstring("ratios")); - json no_ratios{{"components", json::array({1, 2})}}; - CHECK_THAT(argument_error(*mixed, no_ratios), ContainsSubstring("ratios")); + + // Edit Mixed Filament names the mix, and takes what Add Mixed Filament takes, or nothing more for its dialog. + const NativeCommand* edit = NativeCommands::find("filament_edit_mixed"); + REQUIRE(edit != nullptr); + CHECK(edit->input_schema["required"] == json::array({"filament_slot"})); + json edit_dialog{{"filament_slot", 3}}; + CHECK(argument_error(*edit, edit_dialog).empty()); + json edited{{"filament_slot", 3}, {"components", json::array({1, 2})}, {"ratios", json::array({70, 30})}}; + CHECK(argument_error(*edit, edited).empty()); + json no_slot{{"components", json::array({1, 2})}, {"ratios", json::array({70, 30})}}; + CHECK_THAT(argument_error(*edit, no_slot), ContainsSubstring("filament_slot")); // Delete Filament Slot keeps an action of its own, which deletes the last physical slot, and takes the slot to merge into. const NativeCommand* remove = NativeCommands::find("filament_delete"); @@ -440,6 +453,9 @@ TEST_CASE("the filament commands take the filaments they mix, and the slot a del CHECK(argument_error(*remove, merge).empty()); json merge_zero{{"filament_slot", 2}, {"merge_into", 0}}; CHECK_THAT(argument_error(*remove, merge_zero), ContainsSubstring("merge_into")); + // break_mix answers Merge with's question ahead, for a merge into a mixed filament that mixes the slot. + json break_mix{{"filament_slot", 1}, {"merge_into", 3}, {"break_mix", true}}; + CHECK(argument_error(*remove, break_mix).empty()); } TEST_CASE("project_export writes six formats, and project_import takes the entries of a ZIP archive", "[Mcp]") @@ -650,14 +666,14 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") CHECK(first_sentence(command->description) == r.first_sentence); } - // Outside the Design group 128 commands are listed: every one that runs from its arguments, all but the three menu + // Outside the Design group 132 commands are listed: every one that runs from its arguments, all but the three menu // items that take none (Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, - // Part 5d's four, the seven gizmo commands and the six printing commands). + // Part 5d's four, the seven gizmo commands, the six printing commands and the filament list's four). std::size_t listed = 0; for (const NativeCommand& c : catalog.commands()) if (c.listed && c.group != Slic3r::GUI::kDesignGroup) ++listed; - CHECK(listed == 128); + CHECK(listed == 132); } TEST_CASE("opening a project and importing models are two commands", "[Mcp]") diff --git a/tests/slic3rutils/test_operations.cpp b/tests/slic3rutils/test_operations.cpp index 8d51006472..afd5a22ce4 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -2055,7 +2055,8 @@ const std::set kOperations = { "order_objects", "mirror_objects", "center_objects", "scale_to_fit", "drop_objects", "orient_objects", "add_primitive", "delete_plate", "duplicate_plate", "rename_plate", "set_objects_printable", "set_objects_auto_drop", "fix_objects", "clone_objects", "reload_parts", "replace_part", - "add_filament_slot", "delete_filament_slot", "add_mixed_filament", "sync_presets", "export_toolpaths_obj", + "add_filament_slot", "delete_filament_slot", "add_mixed_filament", "edit_mixed_filament", "sync_presets", + "export_toolpaths_obj", "printer_models", "install_printers", "uninstall_printers", "install_filaments", "uninstall_filaments", "set_preferences", "set_plugin_enabled", "uninstall_plugin", "reload_plugin", "start_plugin_refresh", "reorder_objects", "sync_filaments_from_ams", "open_gizmo", "cut_object", @@ -2104,6 +2105,8 @@ const std::map kExceptions = { {"settings_set", kOneEntryPoint}, {"plate_set_settings", kOneEntryPoint}, {"project_set_settings", kOneEntryPoint}, + {"filament_set_colour", kOneEntryPoint}, + {"filament_set_flushing", kOneEntryPoint}, // The commands made from menu items, which run their items' functions. {"object_add_handy_model", kMenuItemAdds}, {"object_add_text", kMenuItemAdds}, diff --git a/tools/mcp/README.md b/tools/mcp/README.md index 815a51e94d..f5754c951e 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -295,8 +295,9 @@ the caption, the pointer and the dialog. sidebar's selector, its value set with `widget_set_value`, `preset_select` and the plugin API. On one slot it answers the filament tab's unsaved-changes prompt every way; on three it checks what the Auto-flush preference does to the flushing volumes when a slot's preset or colour changes. Then it assigns filaments to objects and parts with -`settings_set` and sets the project's slot colours, flushing volumes, plate type and prime tower with -`project_set_settings`, and checks what reaches the print and what the project file keeps. +`settings_set`, sets the slot colours and flushing volumes with `filament_set_colour` and `filament_set_flushing` and +the plate type and prime tower with `project_set_settings`, and checks what reaches the print and what the project file +keeps. `test_presets.py` checks the presets of the three types: selecting one by the name its selector shows, hidden ones included; `preset_list`'s filters; what a setting is and where it lives (`settings_get`, `settings_list`); saving, diff --git a/tools/mcp/TESTS.md b/tools/mcp/TESTS.md index 4666ca0032..695d76fb7e 100644 --- a/tools/mcp/TESTS.md +++ b/tools/mcp/TESTS.md @@ -97,7 +97,8 @@ printer's own behaviour, such as Send over the Bambu network, starts on the Bamb project with its changes discarded, then `printer` selected, installed first with `printer_install` when the data folder lacks it, then `process` (default: the printer's default process), then one filament slot per name in `filaments` (default: the printer's default filament), with any mixed filament slot an earlier test left removed - first, each switch discarding unsaved preset changes. It returns + first (after adding a slot where one physical slot is left, beside which the sidebar deletes no mix), each switch + discarding unsaved preset changes. It returns `presets()`, which the test compares with the start its entry writes out. `KLIPPER`, `KLIPPER_STD` and `GENERIC_PLA` name the default printer's three presets; `X1C`, `X1C_STD` and `BAMBU_PLA` the Bambu Lab X1 Carbon 0.4 nozzle's. @@ -175,7 +176,7 @@ until they leave the sweep. | [Plates](test-entries/plates.md) | [`test_plates`](test-entries/plates.md#test_plates) | — | | [Objects](test-entries/objects.md) | [`test_objects`](test-entries/objects.md#test_objects), [`test_object_structure`](test-entries/objects.md#test_object_structure) | — | | [Presets and calibration](test-entries/presets.md) | [`test_presets`](test-entries/presets.md#test_presets), [`test_calibration`](test-entries/presets.md#test_calibration) | — | -| [Filaments and settings](test-entries/filaments_settings.md) | [`test_filaments`](test-entries/filaments_settings.md#test_filaments), [`test_settings`](test-entries/filaments_settings.md#test_settings) | — | +| [Filaments and settings](test-entries/filaments_settings.md) | [`test_filaments`](test-entries/filaments_settings.md#test_filaments), [`test_mixed_filaments`](test-entries/filaments_settings.md#test_mixed_filaments), [`test_settings`](test-entries/filaments_settings.md#test_settings) | — | | [Project files, imports and exports](test-entries/files.md) | [`test_files`](test-entries/files.md#test_files) | — | | [Slicing, layers and the Preview](test-entries/slice_preview.md) | [`test_slice_preview`](test-entries/slice_preview.md#test_slice_preview) | — | | [Gizmos and canvas input](test-entries/gizmos.md) | [`test_gizmos`](test-entries/gizmos.md#test_gizmos), [`test_gizmo_commands`](test-entries/gizmos.md#test_gizmo_commands) | — | @@ -197,6 +198,7 @@ The 62 tests `sweep.json` lists: 46 Strong, 14 Partial, 2 Smoke. | [`test_presets`](test-entries/presets.md#test_presets) | [Presets and calibration](test-entries/presets.md) | Python | Strong | | [`test_calibration`](test-entries/presets.md#test_calibration) | [Presets and calibration](test-entries/presets.md) | Python | Strong | | [`test_filaments`](test-entries/filaments_settings.md#test_filaments) | [Filaments and settings](test-entries/filaments_settings.md) | Python | Strong | +| [`test_mixed_filaments`](test-entries/filaments_settings.md#test_mixed_filaments) | [Filaments and settings](test-entries/filaments_settings.md) | Python | Strong | | [`test_settings`](test-entries/filaments_settings.md#test_settings) | [Filaments and settings](test-entries/filaments_settings.md) | Python | Strong | | [`test_files`](test-entries/files.md#test_files) | [Project files, imports and exports](test-entries/files.md) | Python | Strong | | [`test_slice_preview`](test-entries/slice_preview.md#test_slice_preview) | [Slicing, layers and the Preview](test-entries/slice_preview.md) | Python | Strong | diff --git a/tools/mcp/checks.py b/tools/mcp/checks.py index c79be809b1..5e6857e14f 100644 --- a/tools/mcp/checks.py +++ b/tools/mcp/checks.py @@ -150,15 +150,17 @@ def start(client, printer=KLIPPER, process=None, filaments=None): if presets(client)["process"] != process: run(client, "preset_select", type="process", name=process, preset_changes="discard") - def slots(): - return client.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"].split(",") - + # With one physical filament the sidebar hides the mixed filaments and deletes none, so a mix an earlier test left + # beside one physical slot goes once a slot is added. + rows = filament_rows(client) + if any(row["mixed"] for row in rows) and sum(not row["mixed"] for row in rows) < 2: + run(client, "filament_add") # Last to first, so the numbers of the mixed slots still to go hold. - for slot in reversed([n for n, mixed in enumerate(slots(), 1) if mixed == "1"]): + for slot in reversed([row["filament_slot"] for row in filament_rows(client) if row["mixed"]]): run(client, "filament_delete", filament_slot=slot) - while len(slots()) > len(filaments): + while len(filament_rows(client)) > len(filaments): run(client, "filament_delete") - while len(slots()) < len(filaments): + while len(filament_rows(client)) < len(filaments): run(client, "filament_add") for slot, name in enumerate(filaments, 1): if presets(client)["filaments"][slot - 1] != name: @@ -435,7 +437,17 @@ def answer_all(client, checks, label, expected, timeout_s=30): checks.equal(f"{label}: no dialog is left open", dialogs(client), []) +def filament_rows(client): + """filament_list's rows, one per filament slot in config order, the physical ones first.""" + return client.call("filament_list")["filaments"] + + def slots(client): - """The filament slots as filament_is_mixed from project_get_settings, one digit per slot ("0,0,1": three slots, - the third a mixed filament), as test_plates reads them.""" - return client.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"] + """The filament slots as the mixed flag of each filament_list row, one digit per slot ("0,0,1": three slots, the + third a mixed filament), as test_plates reads them.""" + return ",".join("1" if row["mixed"] else "0" for row in filament_rows(client)) + + +def slot_colours(client): + """Each filament slot's colour from filament_list, joined by ";" as the project stores them.""" + return ";".join(row["colour"] for row in filament_rows(client)) diff --git a/tools/mcp/sweep.json b/tools/mcp/sweep.json index 14cd7997c9..2a97e4a5c2 100644 --- a/tools/mcp/sweep.json +++ b/tools/mcp/sweep.json @@ -35,6 +35,7 @@ "test_presets": {"path": "test_presets.py", "timeout_s": 1500}, "test_calibration": {"path": "test_calibration.py"}, "test_filaments": {"path": "test_filaments.py", "timeout_s": 1500}, + "test_mixed_filaments": {"path": "test_mixed_filaments.py"}, "test_settings": {"path": "test_settings.py"}, "test_files": {"path": "test_files.py", "timeout_s": 1200}, "test_slice_preview": {"path": "test_slice_preview.py", "timeout_s": 1500}, diff --git a/tools/mcp/test-entries/commands.md b/tools/mcp/test-entries/commands.md index 9243544356..e7ccd2054c 100644 --- a/tools/mcp/test-entries/commands.md +++ b/tools/mcp/test-entries/commands.md @@ -71,18 +71,18 @@ in [TESTS.md](../TESTS.md). **Strength:** Strong — refusal codes and the state after each refusal are compared exactly, and each pick's notice is its own; only a few picks rest on notice text alone. ## `test_additions_refusals` -`test_additions_refusals.py` · Python, 67 checks +`test_additions_refusals.py` · Python, 65 checks -**Tests:** Refusals of the filament, preset, export, import and settings commands. Covers `preset_sync` and `filament_sync_ams` with no account or printer, `view_set` of a layer with no slice, per-object STL and toolpath exports of an empty project (called and picked), a ZIP entry the archive lacks, `layer_height` on a part or a height range, a missing height range, the sidebar while a bare G-code file is open, deleting the only filament slot or one a mixed filament mixes, merging a slot into the mixed filament that mixes it or the mixed filament into a slot, the 64-slot limit, and an `object_order` that leaves an object out. It also checks that a height range's own settings show on its object-list row. +**Tests:** Refusals of the filament, preset, export, import and settings commands. Covers `preset_sync` and `filament_sync_ams` with no account or printer, `view_set` of a layer with no slice, per-object STL and toolpath exports of an empty project (called and picked), a ZIP entry the archive lacks, `layer_height` on a part or a height range, a missing height range, the sidebar while a bare G-code file is open, deleting the only filament slot, merging a slot into the mixed filament that mixes it with the question answered no ahead (`break_mix: false`), merging the mixed filament into a slot, the 64-slot limit, and an `object_order` that leaves an object out. It also checks that a height range's own settings show on its object-list row. **Starts from:** `start(client)`, which "starts from the Generic Klipper Printer" compares with `{printer: "MyKlipper 0.4 nozzle", process: "0.20mm Standard @MyKlipper", filaments: ["Generic PLA @System"]}`; its one filament slot is the slot "the project has one filament slot" reads. The `preset_sync` refusal needs no account signed in and the `filament_sync_ams` refusals no printer connected, which hold in every data folder the sweep makes: a seeded folder keeps its login in its own token file (`use_encrypted_token_file`), no test signs in, and no test connects to a printer. The ZIP archive is written again on every run (`refusals.zip`, a name only this test uses, in `mcp/filaments_and_files` in the data folder). Its picks click the app's own row by its label, ` from Orcaslicer`, as test_menu_items_refusals's do, so a plugin's action never stands in for one. -**Leaves:** a project of two unsaved cubes, `second` and `first`, with 64 filament slots, the last a mixed filament of the first two (the app numbers mixed slots after the physical ones, so the mixed filament made as slot 3 is slot 64 once the slots are added), which the app keeps as its filaments for its next start. It leaves the mixed filament as a person who made it would keep it. There a test that deletes slots down to one with a plain `filament_delete`, which deletes the last physical slot, is refused at three slots: "Filament slot 2 is mixed in the mixed filament of slot 3; delete that mixed filament first." (`mixed_uses_slot`); and the Add Mixed Filament button is hidden at the limit. So the tests after it set their slots with `start()`, which deletes the mixed slot first and leaves no mixed filament. Also `refusals.zip` in the data folder, the handy models' folder as the last folder opened (`recent.last_opened_folder`) and the Speed Dial's usage counts raised for its three picks. +**Leaves:** a project of two unsaved cubes, `second` and `first`, with 64 filament slots, the last a mixed filament of the first two (the app numbers mixed slots after the physical ones, so the mixed filament made as slot 3 is slot 64 once the slots are added), which the app keeps as its filaments for its next start. It leaves the mixed filament as a person who made it would keep it. There a test that deletes slots down to one with a plain `filament_delete`, which deletes the last physical slot, breaks the mix when slot 2 goes and is then refused at the one physical slot left (`last_filament_slot`), the broken mix still there; and the Add Mixed Filament button is hidden at the limit. So the tests after it set their slots with `start()`, which deletes the mixed slot first and leaves no mixed filament. Also `refusals.zip` in the data folder, the handy models' folder as the last folder opened (`recent.last_opened_folder`) and the Speed Dial's usage counts raised for its three picks. **Decides by:** Exits 1 when any check fails. - Start: `starts from the Generic Klipper Printer`, `presets()` as written above. -- Refusals: error text holds a phrase and the details' `code` is exact (`not_signed_in`, `no_printer` ×3, `no_layers`, `no_objects` ×2, `no_toolpaths`, `no_such_entry`, `last_filament_slot`, `mixed_uses_slot` ×2, `mixed_filament_slot`, `too_many_filaments`, `order_misses_object`). Some are checked by text only (see below). -- Filament slots: with one slot, `filament_delete {}` is refused as `last_filament_slot` ("only filament slot"). With a second slot and `filament_add_mixed {components: [1, 2], ratios: [50, 50]}`, whose reply names slot 3, three refusals each leave the three slots: `filament_delete {filament_slot: 1}` as `mixed_uses_slot` with "Filament slot 1 is mixed in the mixed filament of slot 3"; `{filament_slot: 1, merge_into: 3}` as `mixed_uses_slot` with "uses this physical filament", the question Merge with asks; and `{filament_slot: 3, merge_into: 1}` as `mixed_filament_slot` with "can be deleted but not merged". +- Refusals: error text holds a phrase and the details' `code` is exact (`not_signed_in`, `no_printer` ×3, `no_layers`, `no_objects` ×2, `no_toolpaths`, `no_such_entry`, `last_filament_slot`, `mixed_uses_slot`, `mixed_filament_slot`, `too_many_filaments`, `order_misses_object`). Some are checked by text only (see below). +- Filament slots: with one slot, `filament_delete {}` is refused as `last_filament_slot` ("only filament slot"). With a second slot and `filament_add_mixed {components: [1, 2], ratios: [50, 50]}`, whose reply names slot 3, two refusals each leave the three slots: `{filament_slot: 1, merge_into: 3, break_mix: false}` as `mixed_uses_slot` with "removes a filament that mixed filament mixes", Merge with's question answered no ahead; and `{filament_slot: 3, merge_into: 1}` as `mixed_filament_slot` with "can be deleted but not merged". Deleting a filament a mix mixes is no refusal: `test_mixed_filaments`. - Details: `entries` == `["cube.stl", "parts/block.stl"]`, and `height_ranges` == the two ranges. - State left: `gcode_window` and `legend_collapsed` unchanged, export folder empty, `object_list.total` 0, part and range overrides unchanged, `sidebar_collapsed` unchanged, slot count 1/3/64. - Picks: exact notice text in `notifications` ("The project has no objects.", "No more filament slots can be added.", or containing "The Preview shows no toolpaths"), and `dialogs` == `[]`. @@ -269,7 +269,7 @@ in [TESTS.md](../TESTS.md). - Layers: the action and `view_set {layer: 1}` both refuse with `no_layers`, and "in the same words (layer)" compares the texts exactly. - Arrange from the assemble view: no refusal and `off_plate` eq `[]`, the offsets changed, and the selection's `canvas` is `3d` afterwards. - Arrange with the Move gizmo: both cubes are first moved to the bed's centre with `object_transform {object: i, position: [125, 125, 10]}`, and "the cubes are back on one spot" reads both instance offsets from `object_list` as x 125 and y 125. Then the gizmo opens (`active`), `object_arrange` is not refused, and "object_arrange arranges with the Move gizmo open" reads `object_list` again: both cubes are on plate 0 and their 20 mm squares are apart, their offsets differing by at least 20 mm in x or in y. A gizmo is still open afterwards. -- Mixed slot: with a second slot added, `filament_is_mixed` holds a 1; `preset_select` refuses with `mixed_filament_slot`; the plugin API raises `ValueError` with a message equal to `preset_select`'s text. +- Mixed slot: with a second slot added, `filament_list`'s third row is `mixed`; `preset_select` refuses with `mixed_filament_slot`; the plugin API raises `ValueError` with a message equal to `preset_select`'s text. - Hidden printer: a printer listed with `installed: false` exists; after the plugin API's `begin_update(name)`, nothing raised and `app_state.presets.printer` equals it. **Not checked:** diff --git a/tools/mcp/test-entries/filaments_settings.md b/tools/mcp/test-entries/filaments_settings.md index 88597b62c8..b0753a4084 100644 --- a/tools/mcp/test-entries/filaments_settings.md +++ b/tools/mcp/test-entries/filaments_settings.md @@ -3,15 +3,16 @@ The design of this area's sweep tests. The rules every entry follows, the grades and the table of all tests are in [TESTS.md](../TESTS.md). -Two tests, not one. `test_filaments` is about what a filament slot holds and what the project does with it (the -preset in a slot, the unsaved-changes prompt, the flushing volumes, the filaments of objects and parts, the project's -colours and prime tower); `test_settings` is about where a setting applies (a preset, an object, a part, a height -range) and how the settings commands name those targets. They share no state: each sets the start it needs, so the +Three tests. `test_filaments` is about what a filament slot holds and what the project does with it (the preset in a +slot, the unsaved-changes prompt, the flushing volumes, the filaments of objects and parts, the slot colours and the +prime tower); `test_mixed_filaments` is about the mixed filaments of the filament list (adding, changing and breaking +one, and its dialogs); `test_settings` is about where a setting applies (a preset, an object, a part, a height range) +and how the settings commands name those targets. They share no state: each sets the start it needs, so the sweep can run them side by side, or one after the other on one data folder. `test_filaments` also needs filament presets the selectors do not offer yet, which it makes so itself before its first scenario. ## `test_filaments` -`test_filaments.py` · Python, 492 checks · in `sweep.json` as `{"path": "test_filaments.py", "timeout_s": 1500}` +`test_filaments.py` · Python, 495 checks · in `sweep.json` as `{"path": "test_filaments.py", "timeout_s": 1500}` **Tests:** Assigning a filament preset to a filament slot through each route a person or a plugin has: a pick in the slot's selector in the sidebar, the selector's value set (`widget_set_value`), `preset_select`, and the plugin API's @@ -20,8 +21,9 @@ slot's selector in the sidebar, the selector's value set (`widget_set_value`), ` three slots, what the Auto-flush preference (`auto_calculate_flush`: All, Color, None) does to the flushing volumes when a slot's preset or colour changes, the unsaved changes of the preset the tab edits, the plugin API's other forms, the refusals and the hidden presets shown by name. Then multicolour printing: the filament of an object and of a part -through `settings_set`, and the project's own settings through `project_set_settings` (slot colours, flushing volumes -and multiplier, plate type, prime tower), with what reaches the print and what the project file keeps. +through `settings_set`, the filament list's slot colours, flushing volumes and multiplier through `filament_set_colour` +and `filament_set_flushing`, and the project's plate type and prime tower through `project_set_settings`, with what +reaches the print and what the project file keeps. Every scenario runs on the Generic Klipper Printer 0.4. Nothing they check is a Bambu Lab printer's own: their filaments come from the Orca Filament Library, which fits every printer, and the colours, the flushing volumes, the @@ -87,7 +89,7 @@ The routes, for slot `n` and preset `P`: - api: `plugin("orca.host.preset.filament.begin_update(n, P).commit()")`; other forms as the rows give them. **Reads:** -- `slots()` as in `test_plates`: `filament_is_mixed` from `project_get_settings`, one digit per slot. +- `slots()` as in `test_plates`: the `mixed` of each `filament_list` row, one digit per slot. - `state()` gives five fields, written `presets | tab | edits | colours | matrix`: - presets: each slot's preset, from `app_state` `presets.filaments`: `B X B`. - tab: the filament preset `preset_list {type: "filament", limit: 500}` marks `selected`, with `*` when it is also @@ -95,9 +97,9 @@ The routes, for slot `n` and preset `P`: - edits: each slot's `slow_down_layer_time`, from `settings_get {type: "filament", filament_slot: n, keys: ["slow_down_layer_time"], include_meta: false}`, which reads the tab's unsaved value for a slot whose preset the tab edits: `9,4,9`. - - colours: `filament_colour` from `project_get_settings`. `c3` is `#111111;#222222;#333333` and `cX` is + - colours: each `filament_list` row's `colour`, joined by `;`. `c3` is `#111111;#222222;#333333` and `cX` is `#111111;#FFF8E7;#333333`. - - matrix: `flush_volumes_matrix` from `project_get_settings`, entries counted from 0 in the order it lists them (row + - matrix: `flush_volumes_matrix` from `filament_list`, entries counted from 0 in the order it lists them (row = from, column = to). `S3` is the sentinel `0,777,777,777,0,777,777,777,0`. `R2` is slot 2's row and column worked out by the app: entries 1, 3, 5 and 7 each above 0 and other than 777, entries 2 and 6 777 and the diagonal 0. `Sup` is `0,230,777,700,0,700,777,230,0`: a support filament in slot 2, 230 into it (`g_flush_volume_to_support`) @@ -113,10 +115,10 @@ The routes, for slot `n` and preset `P`: · cylinder 2`: the cube on filament 1, its part 0 on 1 and its part 1 on 2, the cylinder on 2. - `item(target, key)` gives one item of `settings_get {target, object, part, keys: [key], include_meta: false}` as `{value, effective, source, parts}` and the reply's `note`; a field the reply leaves out is absent. -- `project()` gives the project's own settings, written `colours | multiplier | matrix | plate type | tower`: from - `project_get_settings`, `filament_colour`, `flush_multiplier`, `flush_volumes_matrix`, `curr_bed_type`, and plate 0's - `wipe_tower_x` and `wipe_tower_y`; and `plate_list`'s plate 0 `curr_bed_type` and `wipe_tower`, which must agree with - them. +- `project()` gives the filament list's and the project's own settings, written `colours | multiplier | matrix | plate + type | tower`: from `filament_list`, the rows' `colour` joined by `;`, `flush_multiplier` and `flush_volumes_matrix`; + from `project_get_settings`, `curr_bed_type` and plate 0's `wipe_tower_x` and `wipe_tower_y`; and `plate_list`'s plate + 0 `curr_bed_type` and `wipe_tower`, which must agree with them. - `grams()` gives, for each slot, `model_g`, `flush_g` and `tower_g`, and the plate's `filament_changes`, from the `summary` of `plate_slice_stats {plate: 0}` read after the slice. @@ -138,8 +140,8 @@ Each case of the slot scenarios starts from `arrange(presets, dirty)`, whose res drops the tab's unsaved changes (`settings_set {type: "filament", filament_slot, reset_all: true}` on a slot holding the preset the tab edits), puts `presets` in the slots with `preset_select {preset_changes: "discard"}`, switches the tab to slot 1's preset with `settings_set {type: "filament", filament_slot: 1, reset_all: true}`, and sets the colours to -`#111111`, `#222222`, `#333333` (as many as there are slots) and the matrix to the sentinels with one -`project_set_settings` call, the colours first and the whole matrix replacing whatever they recalculated. With `dirty` +`#111111`, `#222222`, `#333333` (as many as there are slots) with `filament_set_colour`, slot by slot, then the matrix +to the sentinels with `filament_set_flushing`, the whole matrix replacing whatever the colours recalculated. With `dirty` it then sets `slow_down_layer_time` 9 on slot 1's preset with `settings_set {type: "filament", filament_slot: 1}`. **Scenario: hidden filaments, shown by name** (runs first) @@ -228,8 +230,8 @@ on slot 2: the pick and the tool leave the tab on `B`, the api moves it to the p | None | `M` | `B M B \| B \| 4,4,4 \| c3 \| S3` | `M` | | | None | `S` | `B S B \| B \| 4,8,4 \| c3 \| S3` | `S` | | -After the filament rows of each preference, one more case from the same start: `project_set_settings {values: -{filament_colour: {index: 1, value: "#FFF8E7"}}}`, the colour picker's change. Under All and Color it leaves `B B B | B +After the filament rows of each preference, one more case from the same start: `filament_set_colour {filament_slot: +2, colour: "#FFF8E7"}`, the colour picker's change. Under All and Color it leaves `B B B | B | 4,4,4 | cX | R2`; under None `B B B | B | 4,4,4 | cX | S3`. Where `R2` is expected, the three routes of `X` and the colour change give the same four entries under one preference, and Color gives what All gave for `X`: an assignment recalculates as a colour change does, and on the Klipper printer the preset a slot holds does not change what the @@ -312,34 +314,35 @@ filament change into the prime tower, so the purges of the slices below are in ` | 10 | `undo` | `cube 1 (1, 2) · cylinder 2` | `item(object 0, extruder)` as after 5; `item(object 0, wall_loops)` `{value: null, effective: "3", source: "global"}`, the `wall_loops` of `0.20mm Standard @MyKlipper`: the call was one undo step | | 11 | `plate_slice` | as after 10 | outcome `ok`; `grams()` slot 2 `model_g` above step 6's: the cylinder prints with filament 2 too; slot 1 `model_g` above 0; `filament_changes` above 0 | -**Scenario: the project's own settings, the print and the file** +**Scenario: the slot colours, the flushing and the project's own settings, the print and the file** From `start(client, filaments=[B, M])` and the printer's plate types turned on (see Starts from): `presets()` is `{printer: "MyKlipper 0.4 nozzle", process: "0.20mm Standard @MyKlipper", filaments: [B, M]}`, `support_multi_bed_types` reads "1" and `slots()` is `0,0`. The cube, its part and the cylinder of the scenario before are added the same way, and the part and the cylinder given filament 2 with `settings_set`: `filaments()` is `cube 1 (1, 2) · cylinder 2`. -Then, with `project_set_settings`, the colours `#111111;#222222`, the matrix `0,777,777,0`, the multiplier 1, the -plate type "Cool Plate" and plate 0's prime tower at (60, 150). The start is checked: `project()` is +Then the colours `#111111;#222222` with `filament_set_colour`, the matrix `0,777,777,0` and the multiplier 1 with +`filament_set_flushing`, and the plate type "Cool Plate" and plate 0's prime tower at (60, 150) with +`project_set_settings`. The start is checked: `project()` is `#111111;#222222 | 1 | 0,777,777,0 | Cool Plate | 60,150`, and `presets().filaments` is `[B, M]`. `project()` is read after every step; a value it gives is written out in full in the table. | # | Step | `project()` after | Also checked | |---|---|---|---| -| 1 | `project_get_settings {keys: [filament_is_mixed, curr_bed_type, prime_volume_mode]}` | `#111111;#222222 \| 1 \| 0,777,777,0 \| Cool Plate \| 60,150` | `filament_is_mixed` "0,0" with `meta.read_only` true; `curr_bed_type`'s `meta.offered` holds "Cool Plate" and "Textured PEI Plate"; `prime_volume_mode` "Default" with `meta.offered` empty: the Klipper printer has no purge mode to choose | -| 2 | `project_set_settings {values: {filament_colour: {index: 0, value: "#ffffff"}}}` | `#FFFFFF;#222222 \| 1 \| 0,<a>,<b>,0 \| Cool Plate \| 60,150` | reply `applied.filament_colour` "#FFFFFF;#222222": stored in upper case. `<a>` and `<b>` are worked out by the app, neither 777, and `<b>` (into white) greater than `<a>` (out of it) | -| 3 | `flush_volumes_matrix: [0, 777, 777, 0]`, then one call with `filament_colour: {index: 1, value: "#000000"}`, `flush_multiplier: 0.7`, `flush_volumes_matrix: {index: 1, value: 400}` and `curr_bed_type: "Textured PEI Plate"` | `#FFFFFF;#000000 \| 0.7 \| 0,400,<c>,0 \| Textured PEI Plate \| 60,150` | `<c>` neither 777 nor 400: the colour went first, its recalculation replaced entry 2, and the entry given replaced entry 1 | -| 4 | `flush_volumes_matrix: [0, 400, 300, 0]` | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 60,150` | | -| 5 | `wipe_tower_x: {index: 0, value: 150}` and `wipe_tower_y: {index: 0, value: 180}` in one call | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 150,180` | reply has no `note`: the tower fits there | +| 1 | `filament_list`, then `project_get_settings {keys: [curr_bed_type]}` | `#111111;#222222 \| 1 \| 0,777,777,0 \| Cool Plate \| 60,150` | both rows `mixed` false; `prime_volume_mode` "Default" and no `prime_volume_modes`: the Klipper printer has no purge mode to choose; `curr_bed_type`'s `meta.offered` holds "Cool Plate" and "Textured PEI Plate" | +| 2 | `filament_set_colour {filament_slot: 1, colour: "#ffffff"}` | `#FFFFFF;#222222 \| 1 \| 0,<a>,<b>,0 \| Cool Plate \| 60,150` | reply `{filament_slot: 1, colour: "#FFFFFF", changed: true}`: stored in upper case. `<a>` and `<b>` are worked out by the app, neither 777, and `<b>` (into white) greater than `<a>` (out of it) | +| 3 | `filament_set_flushing {flush_volumes_matrix: [0, 777, 777, 0]}`, `filament_set_colour {filament_slot: 2, colour: "#000000"}`, `filament_set_flushing {flush_multiplier: 0.7, flush_volumes_matrix: {index: 1, value: 400}}` and `project_set_settings {values: {curr_bed_type: "Textured PEI Plate"}}` | `#FFFFFF;#000000 \| 0.7 \| 0,400,<c>,0 \| Textured PEI Plate \| 60,150` | `<c>` neither 777 nor 400: the colour's recalculation replaced entry 2, and the entry given after it replaced entry 1 | +| 4 | `filament_set_flushing {flush_volumes_matrix: [0, 400, 300, 0]}` | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 60,150` | reply `applied` holds `flush_volumes_matrix` | +| 5 | `project_set_settings` with `wipe_tower_x: {index: 0, value: 150}` and `wipe_tower_y: {index: 0, value: 180}` in one call | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 150,180` | reply has no `note`: the tower fits there | | 6 | `wipe_tower_x: {index: 0, value: 40}` | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 40,180` | | | 7 | `undo` | `#FFFFFF;#000000 \| 0.7 \| 0,400,300,0 \| Textured PEI Plate \| 150,180` | the move was one undo step of its own | -| 8 | `filament_is_mixed: "1"` | as after 7 | refused, "filament_is_mixed is read-only: mixed filaments are made in the sidebar's mixed filament list"; `slots()` `0,0` | -| 9 | `filament_colour: {index: 1, value: "white"}` with `flush_multiplier: 0.5` in one call | as after 7 | refused, "Slot 2's colour "white" is not #RRGGBB"; the multiplier in the same call is not set either | -| 10 | `prime_volume_mode: "Saving"` | as after 7 | refused, "prime_volume_mode: this printer has no purge mode to choose"; `prime_volume_mode` reads "Default" | -| 11 | `flush_volumes_matrix: {index: 0, value: 10}` | as after 7 | refused, "flush_volumes_matrix[0] (nozzle 1, from slot 1 to slot 1) must be 0: no flush from a filament to itself" | -| 12 | `wipe_tower_x: {index: 0, value: 300}` | as after 7 | refused, "The prime tower of plate 0 would be off the plate" | +| 8 | `project_set_settings {values: {flush_multiplier: 0.5}}`, then `project_get_settings {keys: [filament_colour]}` | as after 7 | refused, saying "flush_multiplier" "belongs to the filament list" and naming `filament_set_flushing`; the read gives no item, `unknown_keys` `[filament_colour]` and `type_of` `{filament_colour: "filament_list"}` | +| 9 | `filament_set_flushing {flush_multiplier: 0.5, flush_volumes_matrix: {index: 0, value: 10}}` | as after 7 | refused, "flush_volumes_matrix[0] (nozzle 1, from slot 1 to slot 1) must be 0: no flush from a filament to itself"; the multiplier in the same call is not set either | +| 10 | `filament_set_flushing {prime_volume_mode: "Saving"}` | as after 7 | refused, "prime_volume_mode: this printer has no purge mode to choose"; `prime_volume_mode` reads "Default" | +| 11 | `filament_set_colour {filament_slot: 2, colour: "white"}` | as after 7 | refused, "Slot 2's colour "white" is not #RRGGBB" | +| 12 | `project_set_settings {values: {wipe_tower_x: {index: 0, value: 300}}}` | as after 7 | refused, "The prime tower of plate 0 would be off the plate" | | 13 | `plate_slice` | as after 7 | outcome `ok`; `grams()` each slot's `model_g` and `tower_g` above 0 and `flush_g` 0, and `filament_changes` above 0 | -| 14 | `flush_volumes_matrix: {index: 1, value: 200}`, then `plate_slice` | `#FFFFFF;#000000 \| 0.7 \| 0,200,300,0 \| Textured PEI Plate \| 150,180` | `grams()`: slot 2's `tower_g` lower than after 13; each slot's `model_g`, to 0.01 g, and `filament_changes` as after 13 | -| 15 | `flush_multiplier: 1.4`, then `plate_slice` | `#FFFFFF;#000000 \| 1.4 \| 0,200,300,0 \| Textured PEI Plate \| 150,180` | `grams()`: each slot's `tower_g` higher than after 14 | +| 14 | `filament_set_flushing {flush_volumes_matrix: {index: 1, value: 200}}`, then `plate_slice` | `#FFFFFF;#000000 \| 0.7 \| 0,200,300,0 \| Textured PEI Plate \| 150,180` | `grams()`: slot 2's `tower_g` lower than after 13; each slot's `model_g`, to 0.01 g, and `filament_changes` as after 13 | +| 15 | `filament_set_flushing {flush_multiplier: 1.4}`, then `plate_slice` | `#FFFFFF;#000000 \| 1.4 \| 0,200,300,0 \| Textured PEI Plate \| 150,180` | `grams()`: each slot's `tower_g` higher than after 14 | | 16 | `project_save` to a new file, `project_new {discard_changes: true, preset_changes: "discard"}`, `project_open` of the file | as after 15 | `filaments()` `cube 1 (1, 2) · cylinder 2`; `presets().filaments` `[B, M]`; `slots()` `0,0`; `support_multi_bed_types` "1": the project file keeps them, and the printer's settings with the plate type. The new project drops the printer's edit first, which `project_open` would otherwise ask about in a "Load project: unsaved changes" dialog | **To settle in review:** @@ -385,9 +388,9 @@ after every step; a value it gives is written out in full in the table. gives it 1500 s. **Not checked:** -- Adding and deleting slots, and the mixed filament's rules: `test_plates` (its filament slots scenario). Assigning a - preset to a mixed slot, by the tool and the plugin API: `test_operation_routes`, which checks the code and the - words; the state that refusal leaves is not read there either. +- Adding and deleting slots: `test_plates` (its filament slots scenario). The mixed filaments, adding, changing and + breaking one, and a mixed slot having no preset: `test_mixed_filaments`. Assigning a preset to a mixed slot by the + plugin API: `test_operation_routes`, which checks the code and the words. - The prompt's Save button: saving the edits as a new preset is `test_presets`'s. - Whether an assignment takes an undo step: a preset change is not in the project's undo history (as `settings_set` says of a preset's), and the snapshots can be read only from the app's log. @@ -418,6 +421,154 @@ flushing volumes whole with the state written out here, asserts the prompt, each exactly, checks the volumes the app works out by stated properties, and shows the filaments and the flush settings in the print and in the project file. +## `test_mixed_filaments` +`test_mixed_filaments.py` · Python, 182 checks · in `sweep.json` as `{"path": "test_mixed_filaments.py"}` + +**Tests:** The mixed filaments of the filament list against the sidebar's mixed filament list: reading them with +`filament_list`; adding one with `filament_add_mixed` and changing one with `filament_edit_mixed`, each from its +arguments and through its dialog, where the gradient is set; a mixed slot having no preset or colour of its own (the +preset and settings tools refuse it); and what deleting or merging a filament that a mix mixes does to the mix, as the +sidebar does it: broken, and repaired by an edit. It runs on the Generic Klipper Printer 0.4, whose one extruder takes +several filaments; nothing it checks is a Bambu Lab printer's own. + +**Starts from:** Each scenario starts with `start(client)`, whose `presets()` must be `{printer: "MyKlipper 0.4 +nozzle", process: "0.20mm Standard @MyKlipper", filaments: ["Generic PLA @System"]}`, then `filament_add` twice: +`slots()` is `0,0,0`, and the three physical rows of `filament_list` have `preset` "Generic PLA @System" and `type` +"PLA". `start()` deletes the mixed filaments an earlier test or run left before it sets one slot, so no scenario meets a +mix it did not make. The first scenario also reads slot 1's colour, which the test puts back at its end (Leaves). A +scenario that reads a mix's colour sets slots 2 and 3 to `#FF0000` and `#0000FF` with `filament_set_colour`, and never +slot 1. + +**Leaves:** In the app's presets, the Klipper printer with the slots the last scenario leaves (one physical slot and two +broken mixed filaments, which the sidebar hides beside one physical filament), which the next test's `start()` replaces: +it adds a slot, so that the mixes can be deleted, deletes them, and goes back to one slot; slot 1 keeps its colour, +which this test has put back to the one it found. Two project files in its temporary folder, deleted with it, +at the top of the recent projects. No preset: its refused `preset_save` saves none. + +**Reads:** +- `slots()` as in `test_plates`: the `mixed` of each `filament_list` row, one digit per slot (`0,0,0,1`). +- `mixes()` gives `filament_list`'s mixed rows, each written `slot = components @ ratios`, then `, bottom b top t` and + `, per part` for a gradient, and `, broken` for a broken mix, the rows joined by `·`: `4 = 2,3 @ 50,50` is slot 4 + mixing slots 2 and 3 half and half; `4 = 2,3 @ 50,50, bottom 3 top 2, per part` the same with a gradient from slot 3 + at the bottom to slot 2 at the top, each part on its own; `3 = 0,1 @ 50,50, broken` a mix whose first component was + deleted. A gradient whose `curve` is not `linear` fails every row: no step draws one. +- `on(name)` gives the filament of the object named so, from `object_list`. +- `dialogs()` gives the open dialogs from `app_state.dialogs` as `{title, buttons}`. + +After every step `slots()` and `mixes()` are compared with the row whole. A call held by a dialog replies +`blocked_by_dialog`; the test checks `dialogs()`, answers as the row says, waits for the call's job with `app_wait {for: +"job"}` and checks that the wait was met and `dialogs()` is empty. A refusal is matched by its code. + +**Scenario: adding and reading** + +| # | Step | `slots()` | `mixes()` | Also checked | +|---|---|---|---|---| +| 1 | `filament_add_mixed {components: [2, 3], ratios: [50, 50]}` | `0,0,0,1` | `4 = 2,3 @ 50,50` | reply `{added: true, filament_slot: 4}`; row 4 has a `#RRGGBB` `colour`, no `preset` and no `type`; rows 1 to 3 keep their preset; `flush_volumes_matrix` holds 16 entries, 4 x 4 over every slot | +| 2 | the same call | `0,0,0,1` | as after 1 | reply `{added: false, filament_slot: 4}`: a mix the project has is not added again | +| 3 | `filament_add_mixed {components: [1, 2, 3], ratios: [20, 30, 50]}` | `0,0,0,1,1` | `4 = 2,3 @ 50,50 · 5 = 1,2,3 @ 20,30,50` | reply `{added: true, filament_slot: 5}` | +| 4 | `filament_add_mixed {components: [2, 3]}` | as after 3 | as after 3 | refused, `components_and_ratios` | +| 5 | `filament_add` | `0,0,0,0,1,1` | `5 = 2,3 @ 50,50 · 6 = 1,2,3 @ 20,30,50` | reply `filament_slot` 4: a physical slot goes before the mixes, which move up with their components as they were | +| 6 | a 20 mm cube `kept` added, `project_save` to `W/mixes.3mf`, `filament_delete {filament_slot: 6}`, then `project_open` of the file with `discard_changes` | as after 5 | as after 5 | after the delete `slots()` is `0,0,0,0,1`; the open brings slot 6 back: the project file keeps its mixes; `on("kept")` 1. The cube is there so that the open shows no warning, which the app gives for a project file that holds no object | + +**Scenario: a mixed slot has no preset or colour of its own** + +From the start, `filament_add_mixed {components: [2, 3], ratios: [50, 50]}`: `slots()` `0,0,0,1`, `mixes()` +`4 = 2,3 @ 50,50`. Every step leaves both as they were. + +| # | Step | Also checked | +|---|---|---| +| 1 | `settings_get {type: "filament", filament_slot: 4, keys: ["filament_cost"]}` | refused, `mixed_filament_slot` | +| 2 | `settings_set {type: "filament", filament_slot: 4, values: {filament_cost: 99}}` | refused, `mixed_filament_slot`; `settings_get {type: "filament", filament_slot: 2, compare: ":saved"}` lists nothing: the preset slots 1 to 3 hold has no unsaved change | +| 3 | `settings_list {type: "filament", filament_slot: 4}` | refused, `mixed_filament_slot` | +| 4 | `preset_save {type: "filament", filament_slot: 4, name: "MCP Mixed Slot"}` | refused, `mixed_filament_slot`; `preset_list {type: "filament", source: "user"}` names no "MCP Mixed Slot" | +| 5 | `preset_list {type: "filament", query: "Generic PLA"}` | the "Generic PLA @System" item's `filament_slots` `[1, 2, 3]`: the mixed slot does not use it | +| 6 | `filament_set_colour {filament_slot: 4, colour: "#00FF00"}` | refused, saying "Slot 4 is a mixed filament"; row 4's colour is not `#00FF00` | +| 7 | `filament_set_colour {filament_slot: 4, colour: c}`, `c` row 4's colour in lower case | reply `changed` false: its own colour is taken, in any case | +| 8 | `filament_set_flushing {flush_volumes_matrix: {index: 3, value: 50}}`, entry 3 being from slot 1 to slot 4 | refused, saying it "belongs to a mixed filament, which is never flushed"; entry 3 is not 50 | + +**Scenario: changing a mix** + +From the start, slots 2 and 3 set to `#FF0000` and `#0000FF`, `filament_add_mixed {components: [2, 3], ratios: [50, +50]}`, and a 20 mm cube `on_mix` added with `object_add_primitive` and put on filament 4 with `settings_set {target: +"object", object: 0, values: {extruder: 4}}`: `slots()` `0,0,0,1`, `mixes()` `4 = 2,3 @ 50,50`, `on("on_mix")` 4. +After every step `on("on_mix")` is 4: an edit keeps the objects on the mix. + +| # | Step | `slots()` | `mixes()` | Also checked | +|---|---|---|---|---| +| 1 | `filament_edit_mixed {filament_slot: 4, components: [2, 3], ratios: [70, 30]}` | `0,0,0,1` | `4 = 2,3 @ 70,30` | reply `{filament_slot: 4, changed: true}`; row 4's colour has more red than blue: the blend follows the ratios | +| 2 | the same call | `0,0,0,1` | as after 1 | reply `changed` false | +| 3 | `... {ratios: [30, 70]}` with the same components | `0,0,0,1` | `4 = 2,3 @ 30,70` | row 4's colour has more blue than red | +| 4 | `... {components: [1, 2, 3], ratios: [20, 30, 50]}` | `0,0,0,1` | `4 = 1,2,3 @ 20,30,50` | the slot keeps its number | +| 5 | `filament_edit_mixed {filament_slot: 2, components: [2, 3], ratios: [50, 50]}` | as after 4 | as after 4 | refused, `not_mixed_filament` | +| 6 | `... {filament_slot: 9, ...}` with the same mix | as after 4 | as after 4 | refused, `no_such_slot` | +| 7 | `filament_edit_mixed {filament_slot: 4, components: [2, 3]}` | as after 4 | as after 4 | refused, `components_and_ratios` | +| 8 | `filament_edit_mixed {filament_slot: 4, components: [2, 2], ratios: [50, 50]}` | as after 4 | as after 4 | refused, `duplicate_component` | + +**Scenario: a gradient, through the dialogs** + +From the start, `filament_add_mixed {components: [2, 3], ratios: [50, 50]}`: `slots()` `0,0,0,1`, `mixes()` +`4 = 2,3 @ 50,50`. The dialogs' controls are named by the app (`filament_1` to `filament_3`, `gradient`, +`gradient_direction`, `per_part_gradient`) and set with `widget_set_value {target: {name, within: <the dialog's +title>}}`; OK and Cancel are clicked with `widget_click {target: {label, within}}`. + +| # | Step | `slots()` | `mixes()` | Also checked | +|---|---|---|---|---| +| 1 | `filament_edit_mixed {filament_slot: 4}` | `0,0,0,1` | as at the start | `blocked_by_dialog`; `dialogs()` one, titled Edit Mixed Filament, with OK and Cancel | +| 2 | in it, `gradient` true, `gradient_direction` 1, `per_part_gradient` true, then OK | `0,0,0,1` | `4 = 2,3 @ 50,50, bottom 3 top 2, per part` | the job's reply `{filament_slot: 4, changed: true}`; `gradient_direction`'s item 1 puts the second filament at the bottom | +| 3 | `filament_edit_mixed {filament_slot: 4, components: [3, 2], ratios: [50, 50]}` | `0,0,0,1` | `4 = 3,2 @ 50,50, bottom 2 top 3, per part` | a gradient stays for a mix of two, its direction with it | +| 4 | `... {components: [1, 2, 3], ratios: [20, 30, 50]}` | `0,0,0,1` | `4 = 1,2,3 @ 20,30,50` | a gradient goes for three | +| 5 | `filament_edit_mixed {filament_slot: 4}`, then Cancel | `0,0,0,1` | as after 4 | the job's reply `changed` false | +| 6 | `filament_add_mixed {}` | `0,0,0,1` | as after 4 | `blocked_by_dialog`; `dialogs()` one, titled Add Mixed Filament | +| 7 | in it, `gradient` true, then OK | `0,0,0,1,1` | `4 = 1,2,3 @ 20,30,50 · 5 = 1,2 @ 50,50, bottom 1 top 2` | the job's reply `{added: true, filament_slot: 5}`: the dialog starts from filaments 1 and 2 half and half, and item 0 of the direction, the first filament at the bottom | +| 8 | `filament_add_mixed {}`, then Cancel | `0,0,0,1,1` | as after 7 | the job's reply `{added: false}` | +| 9 | as row 6 of the first scenario, with `W/gradient.3mf` and `filament_delete {filament_slot: 5}` | as after 7 | as after 7 | after the delete `slots()` is `0,0,0,1`; the open brings the gradient back: the project file keeps it; `on("kept")` 1 | + +**Scenario: deleting or merging a filament that a mix mixes** + +From the start, `filament_add_mixed {components: [1, 2], ratios: [50, 50]}` and `{components: [2, 3], ratios: [50, +50]}`, and two 20 mm cubes, `on_one` on filament 1 and `on_mix` on filament 4: `slots()` `0,0,0,1,1`, `mixes()` +`4 = 1,2 @ 50,50 · 5 = 2,3 @ 50,50`. + +| # | Step | `slots()` | `mixes()` | Also checked | +|---|---|---|---|---| +| 1 | `filament_delete {filament_slot: 1, merge_into: 4}`, then `dialog_answer {button: "Cancel"}` | `0,0,0,1,1` | as at the start | `blocked_by_dialog`; `dialogs()` one, titled Warning, with OK and Cancel, its message holding "uses this physical filament"; the job refused, `merge_cancelled`; `on("on_one")` 1 | +| 2 | `filament_delete {filament_slot: 1, merge_into: 4, break_mix: false}` | as at the start | as at the start | refused, `mixed_uses_slot`, with no dialog | +| 3 | `filament_delete {filament_slot: 1, merge_into: 4, break_mix: true}` | `0,0,1,1` | `3 = 0,1 @ 50,50, broken · 4 = 1,2 @ 50,50` | reply `{filament_slot: 1, merged_into: 3, broken_mixed: [3]}`, with no dialog; `on("on_one")` and `on("on_mix")` 3: the objects went into the mix, which lost the filament merged into it | +| 4 | `plate_slice` | as after 3 | as after 3 | plate 0's `outcome` `error`, its `error` "A mixed filament has a deleted or mismatched component": an object prints with a broken mix | +| 5 | `filament_edit_mixed {filament_slot: 3, components: [1, 2], ratios: [50, 50]}` | `0,0,1,1` | `3 = 1,2 @ 50,50 · 4 = 1,2 @ 50,50` | reply `changed` true: an edit repairs a broken mix | +| 6 | `filament_delete {filament_slot: 2}` | `0,1,1` | `2 = 1,0 @ 50,50, broken · 3 = 1,0 @ 50,50, broken` | reply `broken_mixed` `[2, 3]`, with no dialog: the sidebar deletes a filament a mix mixes without asking | +| 7 | `filament_delete {filament_slot: 1}` | as after 6 | as after 6 | refused, `last_filament_slot`: one physical slot stays, whatever mixes there are | +| 8 | `filament_delete {filament_slot: 2}` | as after 6 | as after 6 | refused, `mixed_list_hidden`: with one physical filament the sidebar hides the mixed filament list and deletes nothing (`Sidebar::delete_filament()`) | + +At the end the test sets slot 1 back to the colour the first scenario found, with `filament_set_colour`, and reads it +back with `filament_list`. + +**To settle in review:** +- What `plate_slice` does with an object on a broken mix (row 4), measured: the call is not refused, and the slice + ends in an error on the plate, with the notification "Mixed filament has invalid or mismatched components. Please + re-edit affected entries.", which the row does not read. +- The Add Mixed Filament dialog's start (row 7 of the gradient scenario): filaments 1 and 2 half and half, measured on + this build; the dialog may start from its first recommendation instead on another set of filaments. +- A mix left beside one physical filament (row 8) is hidden in the sidebar and cannot be deleted there, which the tool + follows; a person who deleted down to one filament has no way to see such a mix until they add a slot. That looks + like a gap in the sidebar, open for the maintainer. +- Colours are compared by their channels, not their values: the blend is the app's (`blend_mixed_color()`), and only + which way it moves with the ratios is the tool's behaviour. + +**Not checked:** +- The gradient curve, which is drawn and changed only by a drag: every gradient here is the straight line. +- The dialogs' component selectors and ratio controls: the selectors are named, but each lists "Generic PLA" for every + slot, and components and ratios have the silent form. +- What a mixed filament prints, its components layer by layer: no slice of a mix is read. +- A mix's colour beyond the channel comparison, and whether a component's colour change re-blends it. +- How the sidebar draws a broken mix: its row is not read on screen. +- The undo history: none of these is in it, as in the GUI, and nothing reads it here. +- The mixed filament list's Remove last and Remove all buttons: `test_plates` clicks Remove last mixed filament; Remove + all asks first, and `filament_delete` deletes a mix one at a time. + +**Strength:** Strong — every step's slots and mixes are compared whole, refusals by their codes, and the file is read +back once through a reopen. + ## `test_settings` `test_settings.py` · Python, 72 checks · in `sweep.json` as `{"path": "test_settings.py"}` diff --git a/tools/mcp/test-entries/files.md b/tools/mcp/test-entries/files.md index 54ee8a8b08..00105c7f27 100644 --- a/tools/mcp/test-entries/files.md +++ b/tools/mcp/test-entries/files.md @@ -353,8 +353,8 @@ profile has none, so no send can reach a printer. **Scenario: filament slots merged and mixed** -Objects are read with `meshes()` as their names and `filament`; `colours` is `filament_colour` from -`project_get_settings`. It starts from the one slot `start()` left, which no scenario before it changes. The mixed slot +Objects are read with `meshes()` as their names and `filament`; `colours` is each `filament_list` row's `colour`, +joined by `;`. It starts from the one slot `start()` left, which no scenario before it changes. The mixed slot it makes stays in the data folder (Leaves), until the next test's `start()`, or this test's own on a rerun, deletes it. | # | Step | `slots()` after | Also checked | @@ -362,7 +362,7 @@ it makes stays in the data folder (Leaves), until the next test's `start()`, or | 1 | (the start) | `"0"` | | | 2 | `filament_add` | `"0,0"` | reply `filament_slot` 2, `filament_slots` 2 | | 3 | `filament_add` | `"0,0,0"` | reply `filament_slot` 3, `filament_slots` 3 | -| 4 | `project_set_settings {values: {filament_colour: {index: i, value: c}}}` for slot index 0, 1 and 2 with `#FF0000`, `#00FF00` and `#0000FF` | `"0,0,0"` | `colours` `#FF0000;#00FF00;#0000FF` | +| 4 | `filament_set_colour {filament_slot: n, colour: c}` for slots 1, 2 and 3 with `#FF0000`, `#00FF00` and `#0000FF` | `"0,0,0"` | `colours` `#FF0000;#00FF00;#0000FF` | | 5 | cubes `on_two` 20 at (80, 128) and `on_three` 20 at (176, 128); `settings_set {target: "object", object: 0, values: {extruder: 2}}` and the same for object 1 with 3 | `"0,0,0"` | `on_two` filament 2, `on_three` filament 3 | | 6 | `filament_delete {filament_slot: 2, merge_into: 1}` | `"0,0"` | reply `{filament_slot: 2, merged_into: 1, filament_slots: 2}`; `on_two` filament 1, `on_three` filament 2; `colours` `#FF0000;#0000FF`: the slot after the deleted one moved down, with its objects | | 7 | `filament_add_mixed {components: [1, 2], ratios: [50, 50]}` | `"0,0,1"` | reply `{filament_slot: 3, added: true}`; `app_state.presets.filaments` has 3 entries; `on_two` 1, `on_three` 2 | diff --git a/tools/mcp/test-entries/gizmos.md b/tools/mcp/test-entries/gizmos.md index 39cf0e060f..ff0498d3b8 100644 --- a/tools/mcp/test-entries/gizmos.md +++ b/tools/mcp/test-entries/gizmos.md @@ -49,7 +49,7 @@ settings, and a test whose checks read the settings pages sets the mode it needs - `setting(object, key)` gives `settings_get {target: object}`'s `{value, effective, source}` for one key. - `selection()` gives `app_state.selection.objects`; `rules()` gives `app_state.auto_answer_rules` with their `uses`. - `toolbar(name)` gives a 3D view toolbar item's `{enabled, pressed}` from `widget_list`. -- `slots()` is the reader `test_plates` defines (`filament_is_mixed`, one digit per slot). +- `slots()` is the reader `test_plates` defines (the `mixed` of each `filament_list` row, one digit per slot). Every scenario starts with `project_new {discard_changes: true}` in the Prepare view and checks that `scene()` is empty and `gizmo()` is none. Objects are then added with `object_add_primitive {shape, size, diff --git a/tools/mcp/test-entries/gui_tools.md b/tools/mcp/test-entries/gui_tools.md index 917ebc57c1..b8a0d35011 100644 --- a/tools/mcp/test-entries/gui_tools.md +++ b/tools/mcp/test-entries/gui_tools.md @@ -60,8 +60,8 @@ its name and `type` (`part`, `modifier`, `negative`, ...), and whether its first `app_state.selection` as `{objects, parts}`, or empty. `menu(reply)` gives a reply's `popup_menu` as `{items, checked, disabled}`, an absent list read as `[]`. `rows(target)` parses `widget_list`'s tree into rows, each with its label path, its value, and whether it is selected or checked. `dialogs()` gives the titles of -`app_state.dialogs`, `windows()` the titles `window_list` lists, `colours()` the project's `filament_colour` from -`project_get_settings`, `project_file(path)` the JSON of a saved project's `Metadata/project_settings.config`, and +`app_state.dialogs`, `windows()` the titles `window_list` lists, `colours()` each `filament_list` row's `colour`, +joined by `;`, `project_file(path)` the JSON of a saved project's `Metadata/project_settings.config`, and `canvas_png(name)` the file `window_screenshot {target: "canvas", include_image: false, save_path: OUT/<name>.png}` writes. `OUT` is the test's output folder: the folder `--out` names, else a new temporary folder. Every scenario starts with `project_new {discard_changes: true, preset_changes: "discard"}` in the Prepare view and the @@ -109,7 +109,7 @@ Hell`, then `Add Models` and `Show Labels`. | 15 | `E` with `popup_item: "Show Labels"`, then `canvas_png("labels_off_again")` | as after 9 | `app_state.view.labels` false; `labels_off_again.png` differs from `labels_on.png`: the label is gone again | | 16 | `E` with `popup_item: "Add Primitive>Cylinder"` | as after 9, then `Cylinder: Cylinder part` | `app_state.objects` 2 | | 17 | `widget_click {target: {label: "Add one filament"}}` | as after 16 | `app_state.presets.filaments` has 2 entries | -| 18 | `project_set_settings {values: {filament_colour: "#FF0000;#0000FF"}}` | as after 16 | `colours()` `#FF0000;#0000FF` | +| 18 | `filament_set_colour {filament_slot: 1, colour: "#FF0000"}` and `{filament_slot: 2, colour: "#0000FF"}` | as after 16 | `colours()` `#FF0000;#0000FF` | | 19 | `widget_click` of filament 1's `Click to edit preset` button, by the ref of the first button of that name `widget_list {target: "main"}` lists with a position and a size | as after 16 | items exactly `Edit`, `Merge with>Generic PLA`, `Decompose Color`, `Delete`, `Generic PLA` being the filament of slot 2 as the selector names it (Add one filament copies the last slot's, `PresetBundle::set_num_filaments`); `dialogs()` `[]`; `app_state.tab` `prepare` | | 20 | the same with `popup_item: "Delete"` | as after 16 | reply `ran` `Delete`; `app_state.presets.filaments` has 1 entry and `colours()` is `#0000FF`: the slot whose button was clicked is the one deleted | | 21 | `object_select {all: true}`, then `C` | as after 16 | `selection()` objects `[0, 1]` after the select; the items hold `Assemble`, `Align/Distribute>Align left (-X)` and `Delete`, and not `Add Part>Cube`: the menu is the multi-selection's, not one object's | @@ -175,7 +175,7 @@ It starts with `start(c, filaments=["Bambu PLA Basic @System"])`, compared with KLIPPER_STD, filaments: ["Bambu PLA Basic @System"]}`: the Orca Filament Library's Bambu PLA Basic, which suits any printer. A filament whose name starts with `Bambu` opens Orca's own filament picker (`PresetComboBoxes.cpp`), which finds the library's filament id `OFoiVqVM` under Bambu's `GFA00` (`FilamentColorCodeQuery::GetFilaInfoMap`). Slot 1's -colour is set with `project_set_settings {values: {filament_colour: "#26A69A"}}`. When `preset_list {type: +colour is set with `filament_set_colour {filament_slot: 1, colour: "#26A69A"}`. When `preset_list {type: "printer"}` offers `MyMarlin 0.4 nozzle`, the Generic Marlin Printer whose wizard card step 15 ticks, the scenario takes it out first (`printer_uninstall {models: [{vendor: "Custom", model: "Generic Marlin Printer"}]}`), so that the card starts unticked; no test installs it. The start is checked: `app_state.presets.filaments` is `["Bambu PLA Basic diff --git a/tools/mcp/test-entries/plates.md b/tools/mcp/test-entries/plates.md index 591d6dd16f..240075c41a 100644 --- a/tools/mcp/test-entries/plates.md +++ b/tools/mcp/test-entries/plates.md @@ -4,7 +4,7 @@ The design of this area's sweep tests. The rules every entry follows, the grades in [TESTS.md](../TESTS.md). ## `test_plates` -`test_plates.py` · Python, 221 checks · in `sweep.json` as `{"path": "test_plates.py"}` +`test_plates.py` · Python, 222 checks · in `sweep.json` as `{"path": "test_plates.py"}` **Tests:** The plates of the Prepare view: adding, duplicating, naming, locking, selecting and deleting plates, and undoing that; what a lock keeps Arrange and Auto-Orient from doing; the settings a plate sets for itself; the @@ -28,8 +28,8 @@ temporary folder, which is removed when the test ends. **Reads:** `plates()` gives each plate as `{name, current, locked, objects}` from `plate_list`. `objects()` gives each object as `{name, plate}` from `object_list`, and the objects outside the plates by name. `slots()` gives the -filament slots as `filament_is_mixed` from `project_get_settings`, one digit per slot (`"0,0,1"`: three slots, the -third a mixed filament). +filament slots as the `mixed` of each `filament_list` row, one digit per slot (`"0,0,1"`: three slots, the third a +mixed filament). In the tables a plate is written as its name and its number of objects, with `*` on the current plate and `L` on a locked one, and the plates are listed in order between `·`: `"" 1 *` · `"Copy" 1 L` is an unnamed current plate with @@ -48,7 +48,7 @@ whole. | 6 | `plate_delete {plate: 0}` | `"Left" 0 *` · `"" 0 L` | the plates after it move down; the current plate stays current | | 7 | `undo` | `"" 0` · `"Left" 0 *` · `"" 0 L` | the delete is one undo step | | 8 | `redo` | `"Left" 0 *` · `"" 0 L` | | -| 9 | `project_save` to a new file, `project_new`, `project_open` of the file | `"Left" 0 *` · `"" 0 L` | names and locks are kept in the project file; the open first shows the app's warning "The file does not contain any geometry data.", answered OK | +| 9 | `object_add_primitive {name: "kept", plate: 0}`, a 20 mm cube, then `project_save` to a new file, `project_new`, `project_open` of the file | `"Left" 1 *` · `"" 0 L`, after the add and after the open | names and locks are kept in the project file, and `objects()` gives the cube on plate 0; the cube is there so that the open shows no warning, which the app gives for a project file that holds no object | **Scenario: by index, and on the current plate** diff --git a/tools/mcp/test-entries/slice_preview.md b/tools/mcp/test-entries/slice_preview.md index 9fd91a04cf..222241848b 100644 --- a/tools/mcp/test-entries/slice_preview.md +++ b/tools/mcp/test-entries/slice_preview.md @@ -21,8 +21,8 @@ Lab printer's own behaviour, and its G-code is read as a printer outside the Bam sets `timeout_s` 1500: it slices about thirty times, three of them a Benchy. **Starts from:** `start(client)`, whose `presets()` must be `{printer: "MyKlipper 0.4 nozzle", process: "0.20mm Standard -@MyKlipper", filaments: ["Generic PLA @System"]}`. Then `project_set_settings {values: {filament_colour: {index: 0, -value: "#26A69A"}, flush_multiplier: 0.3}}`, read back with `project_get_settings`: a seeded folder's slot colour and +@MyKlipper", filaments: ["Generic PLA @System"]}`. Then `filament_set_colour {filament_slot: 1, colour: "#26A69A"}` +and `filament_set_flushing {flush_multiplier: 0.3}`, read back with `filament_list`: a seeded folder's slot colour and flush multiplier, since the purge between two slots, and so the depth of the two-colour slices' prime tower, follows both, and the printer keeps them as an earlier test or run left them (To settle); `preferences_set {values: {auto_slice_after_change: false}}`, read back with `preferences_get`, so that a plate is sliced only when a row slices diff --git a/tools/mcp/test_additions_refusals.py b/tools/mcp/test_additions_refusals.py index c9e6f718ed..aded6f0035 100644 --- a/tools/mcp/test_additions_refusals.py +++ b/tools/mcp/test_additions_refusals.py @@ -22,9 +22,9 @@ row's note in widget_list says "has settings", as the icon that resets them show a null leaves the range none, and the list's selection stays as it was. With a G-code file of no settings open, the sidebar is off, and view_set of it is refused. -filament_delete of the only filament slot is refused. With a mixed filament of slots 1 and 2, filament_delete of slot 1 -is refused, the mixed filament mixing it; a merge of slot 1 into the mixed filament is refused with the question Merge -with asks; and a merge of the mixed slot is refused, a mixed filament being deleted but not merged. filament_add once +filament_delete of the only filament slot is refused. With a mixed filament of slots 1 and 2, a merge of slot 1 into +the mixed filament is refused where break_mix answers Merge with's question no ahead; and a merge of the mixed slot is +refused, a mixed filament being deleted but not merged. filament_add once the project holds as many filament slots as it can is refused, and a pick of Add Filament Slot then says so, as its menu item did. The mixed filament is left, as a person would keep it. @@ -217,7 +217,7 @@ def main(): client.call("project_new", discard_changes=True) client.call("view_set", tab="prepare") - # ---- Filament slots: the only one is not deleted, nor a slot a mixed filament mixes, and a mixed one is not merged ---- + # ---- Filament slots: the only one is not deleted, a merge answered no is not made, and a mixed one is not merged ---- check("the project has one filament slot", slots() == 1, slots()) refused("filament_delete of the only filament slot is refused", "filament_delete", {}, "only filament slot", "last_filament_slot") @@ -225,13 +225,12 @@ def main(): client.call("filament_add") mixed = client.call("filament_add_mixed", components=[1, 2], ratios=[50, 50]) check("a mixed filament of slots 1 and 2 is slot 3", mixed.get("filament_slot") == 3, mixed) - refused("filament_delete of slot 1, which the mixed filament mixes, is refused", "filament_delete", {"filament_slot": 1}, - "Filament slot 1 is mixed in the mixed filament of slot 3", "mixed_uses_slot") - refused("filament_delete of slot 1 merged into the mixed filament that mixes it is refused", "filament_delete", - {"filament_slot": 1, "merge_into": 3}, "uses this physical filament", "mixed_uses_slot") + refused("filament_delete of slot 1 merged into the mixed filament that mixes it, answered no, is refused", + "filament_delete", {"filament_slot": 1, "merge_into": 3, "break_mix": False}, + "removes a filament that mixed filament mixes", "mixed_uses_slot") refused("filament_delete of the mixed filament merged into slot 1 is refused", "filament_delete", {"filament_slot": 3, "merge_into": 1}, "can be deleted but not merged", "mixed_filament_slot") - check("and the three leave the three slots", slots() == 3, slots()) + check("and the two leave the three slots", slots() == 3, slots()) # ---- No slot is added past the most a project holds ---- for _ in range(MOST_SLOTS - slots()): diff --git a/tools/mcp/test_filaments.py b/tools/mcp/test_filaments.py index 1d55504e6b..ab6441e0ab 100644 --- a/tools/mcp/test_filaments.py +++ b/tools/mcp/test_filaments.py @@ -8,8 +8,9 @@ tools/mcp/test-entries/filaments_settings.md designs them. Assigning a filament preset to a slot by each route a person or a plugin has (a pick in the slot's selector, the selector's value set, preset_select and the plugin API), with one slot, where the filament tab switches and its unsaved-changes prompt applies, and with three, where the Auto-flush preference decides what happens to the flushing -volumes; then the filaments of objects and parts, and the project's own settings with what reaches the print and what -the project file keeps. After every step the test reads the state back through other tools and compares it with the +volumes; then the filaments of objects and parts, the slot colours and flushing (filament_set_colour, +filament_set_flushing) and the project's own settings (project_set_settings), with what reaches the print and what the +project file keeps. After every step the test reads the state back through other tools and compares it with the state the entry writes out. Every scenario runs on the Generic Klipper Printer 0.4 from a start of its own (checks.start()), the last with the printer's plate types turned on, so it runs on a data folder earlier tests used; it uninstalls the filaments it shows by name first, so that the selectors start without them. It exits 0 when every @@ -22,7 +23,7 @@ import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 -from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, presets, run, start, wait # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, presets, run, slot_colours, slots, start, wait # noqa: E402 B = GENERIC_PLA X = "FilAr PLA Blanco Calido" @@ -146,7 +147,11 @@ class FilamentsTest: return {i["key"]: i["value"] for i in items} def slots(self): - return self.project_values("filament_is_mixed")["filament_is_mixed"] + return slots(self.c) + + def matrix(self): + """filament_list's flush_volumes_matrix, written as the project stores it: `0,777,777,0`.""" + return ",".join(g(x) for x in self.c.call("filament_list")["flush_volumes_matrix"]) def dialogs(self): return [{"title": d.get("title"), "buttons": [b.get("label") for b in d.get("buttons", [])]} @@ -161,9 +166,8 @@ class FilamentsTest: if i.get("selected")] edits = [self.c.call("settings_get", type="filament", filament_slot=n, keys=["slow_down_layer_time"], include_meta=False)["items"][0]["value"] for n in range(1, len(presets) + 1)] - project = self.project_values("filament_colour", "flush_volumes_matrix") - return {"presets": presets, "tab": tab, "edits": edits, "colours": project["filament_colour"], - "matrix": project["flush_volumes_matrix"], "dialogs": [d.get("title") for d in app.get("dialogs", [])]} + return {"presets": presets, "tab": tab, "edits": edits, "colours": slot_colours(self.c), "matrix": self.matrix(), + "dialogs": [d.get("title") for d in app.get("dialogs", [])]} @staticmethod def text(state): @@ -195,14 +199,15 @@ class FilamentsTest: return {k: item[k] for k in ("value", "effective", "source", "parts") if k in item}, reply.get("note") def project(self): - """The project's own settings, `colours | multiplier | matrix | plate type | tower`, with plate_list's plate 0 - added where it disagrees with project_get_settings.""" - v = self.project_values("filament_colour", "flush_multiplier", "flush_volumes_matrix", "curr_bed_type", - "wipe_tower_x", "wipe_tower_y") + """The filament list's and the project's own settings, `colours | multiplier | matrix | plate type | tower`, + with plate_list's plate 0 added where it disagrees with project_get_settings.""" + listed = self.c.call("filament_list") + v = self.project_values("curr_bed_type", "wipe_tower_x", "wipe_tower_y") tower = f"{g(v['wipe_tower_x'].split(',')[0])},{g(v['wipe_tower_y'].split(',')[0])}" plate = self.c.call("plate_list", limit=500)["items"][0] - out = {"colours": v["filament_colour"], "multiplier": g(v["flush_multiplier"]), - "matrix": ",".join(g(x) for x in v["flush_volumes_matrix"].split(",")), + out = {"colours": ";".join(row["colour"] for row in listed["filaments"]), + "multiplier": ",".join(g(x) for x in listed["flush_multiplier"]), + "matrix": ",".join(g(x) for x in listed["flush_volumes_matrix"]), "bed": v["curr_bed_type"], "tower": tower} plate_tower = ",".join(g(x) for x in plate.get("wipe_tower") or []) if (plate.get("curr_bed_type"), plate_tower) != (out["bed"], tower): @@ -338,9 +343,10 @@ class FilamentsTest: self.run("preset_select", type="filament", name=name, filament_slot=slot, preset_changes="discard") self.run("settings_set", type="filament", filament_slot=1, reset_all=True) n = len(presets) - self.run("project_set_settings", values={ - "filament_colour": GREYS[:n], - "flush_volumes_matrix": [0 if i == j else SENTINEL for i in range(n) for j in range(n)]}) + for slot, colour in enumerate(GREYS[:n], 1): + self.run("filament_set_colour", filament_slot=slot, colour=colour) + # After the colours, whose change recalculates the matrix. + self.run("filament_set_flushing", flush_volumes_matrix=[0 if i == j else SENTINEL for i in range(n) for j in range(n)]) if dirty: self.run("settings_set", type="filament", filament_slot=1, values={"slow_down_layer_time": 9}) self.idle() @@ -531,7 +537,7 @@ class FilamentsTest: min(m[1], m[7]) > max(m[3], m[5]), state["matrix"]) label = f"{s} {which}, the colour picker's change" self.arrange(label, [B, B, B], False, start) - self.run("project_set_settings", values={"filament_colour": {"index": 1, "value": "#FFF8E7"}}) + self.run("filament_set_colour", filament_slot=2, colour="#FFF8E7") self.idle() state = self.state_is(label, f"B B B | B | 4,4,4 | cX | {colour_change[which]}") if colour_change[which] == "R2": @@ -778,7 +784,7 @@ class FilamentsTest: self.idle() def project_settings(self): - s = "the project's own settings" + s = "the slot colours, the flushing and the project's own settings" self.start(s, [B, M]) # The plate type selector shows for a printer with several plate types: an unsaved edit of the printer # preset, which the next start() discards. @@ -787,30 +793,28 @@ class FilamentsTest: self.add_objects() self.run("settings_set", target="part", object=0, part=1, values={"extruder": 2}) self.run("settings_set", target="object", object=1, values={"extruder": 2}) - self.run("project_set_settings", values={ - "filament_colour": ["#111111", "#222222"], "flush_volumes_matrix": [0, 777, 777, 0], "flush_multiplier": 1, - "curr_bed_type": "Cool Plate", "wipe_tower_x": {"index": 0, "value": 60}, - "wipe_tower_y": {"index": 0, "value": 150}}) + self.run("filament_set_colour", filament_slot=1, colour="#111111") + self.run("filament_set_colour", filament_slot=2, colour="#222222") + self.run("filament_set_flushing", flush_volumes_matrix=[0, 777, 777, 0], flush_multiplier=1) + self.run("project_set_settings", values={"curr_bed_type": "Cool Plate", "wipe_tower_x": {"index": 0, "value": 60}, + "wipe_tower_y": {"index": 0, "value": 150}}) self.idle() self.t.equal(f"{s}: the start's filaments", self.filaments(), "cube 1 (1, 2) · cylinder 2") self.t.equal(f"{s}: the start's filament presets", presets(self.c)["filaments"], [B, M]) self.project_is(f"{s}: the start", "#111111;#222222", "1", "0,777,777,0", "Cool Plate", "60,150") - items = {i["key"]: i for i in self.c.call("project_get_settings", keys=[ - "filament_is_mixed", "curr_bed_type", "prime_volume_mode"])["items"]} - self.t.equal(f"{s} 1: the mixed slots, read-only", - (items["filament_is_mixed"]["value"], items["filament_is_mixed"]["meta"].get("read_only")), - ("0,0", True)) + listed = self.c.call("filament_list") + self.t.equal(f"{s} 1: no mixed slot", [row["mixed"] for row in listed["filaments"]], [False, False]) + self.t.equal(f"{s} 1: no purge mode to choose", (listed.get("prime_volume_mode"), "prime_volume_modes" in listed), + ("Default", False)) + items = {i["key"]: i for i in self.c.call("project_get_settings", keys=["curr_bed_type"])["items"]} offered = items["curr_bed_type"]["meta"].get("offered", []) self.t.check(f"{s} 1: the plate types offered include Cool Plate and Textured PEI Plate", "Cool Plate" in offered and "Textured PEI Plate" in offered, offered) - self.t.equal(f"{s} 1: no purge mode to choose", (items["prime_volume_mode"]["value"], - items["prime_volume_mode"]["meta"].get("offered")), - ("Default", [])) self.project_is(f"{s} 1", "#111111;#222222", "1", "0,777,777,0", "Cool Plate", "60,150") - reply = self.run("project_set_settings", values={"filament_colour": {"index": 0, "value": "#ffffff"}}) - self.t.equal(f"{s} 2: the reply", reply.get("applied", {}).get("filament_colour"), "#FFFFFF;#222222") + reply = self.run("filament_set_colour", filament_slot=1, colour="#ffffff") + self.t.equal(f"{s} 2: the reply", reply, {"filament_slot": 1, "colour": "#FFFFFF", "changed": True}) def into_white(matrix): m = numbers(matrix) @@ -818,10 +822,10 @@ class FilamentsTest: self.project_is(f"{s} 2", "#FFFFFF;#222222", "1", "0,<a>,<b>,0", "Cool Plate", "60,150", into_white) - self.run("project_set_settings", values={"flush_volumes_matrix": [0, 777, 777, 0]}) - self.run("project_set_settings", values={ - "filament_colour": {"index": 1, "value": "#000000"}, "flush_multiplier": 0.7, - "flush_volumes_matrix": {"index": 1, "value": 400}, "curr_bed_type": "Textured PEI Plate"}) + self.run("filament_set_flushing", flush_volumes_matrix=[0, 777, 777, 0]) + self.run("filament_set_colour", filament_slot=2, colour="#000000") + self.run("filament_set_flushing", flush_multiplier=0.7, flush_volumes_matrix={"index": 1, "value": 400}) + self.run("project_set_settings", values={"curr_bed_type": "Textured PEI Plate"}) def c_worked_out(matrix): m = numbers(matrix) @@ -829,7 +833,8 @@ class FilamentsTest: pei = "Textured PEI Plate" self.project_is(f"{s} 3", "#FFFFFF;#000000", "0.7", "0,400,<c>,0", pei, "60,150", c_worked_out) - self.run("project_set_settings", values={"flush_volumes_matrix": [0, 400, 300, 0]}) + reply = self.run("filament_set_flushing", flush_volumes_matrix=[0, 400, 300, 0]) + self.t.check(f"{s} 4: the reply applied the matrix", "flush_volumes_matrix" in reply.get("applied", {}), reply) self.project_is(f"{s} 4", "#FFFFFF;#000000", "0.7", "0,400,300,0", pei, "60,150") reply = self.run("project_set_settings", values={"wipe_tower_x": {"index": 0, "value": 150}, "wipe_tower_y": {"index": 0, "value": 180}}) @@ -842,22 +847,27 @@ class FilamentsTest: self.project_is(f"{s} 7: the move was one undo step", *after) refusals = [ - (8, {"filament_is_mixed": "1"}, - "filament_is_mixed is read-only: mixed filaments are made in the sidebar's mixed filament list"), - (9, {"filament_colour": {"index": 1, "value": "white"}, "flush_multiplier": 0.5}, - 'Slot 2\'s colour "white" is not #RRGGBB'), - (10, {"prime_volume_mode": "Saving"}, "prime_volume_mode: this printer has no purge mode to choose"), - (11, {"flush_volumes_matrix": {"index": 0, "value": 10}}, + (8, "project_set_settings", {"values": {"flush_multiplier": 0.5}}, "belongs to the filament list"), + (9, "filament_set_flushing", {"flush_multiplier": 0.5, "flush_volumes_matrix": {"index": 0, "value": 10}}, "flush_volumes_matrix[0] (nozzle 1, from slot 1 to slot 1) must be 0: no flush from a filament to itself"), - (12, {"wipe_tower_x": {"index": 0, "value": 300}}, "The prime tower of plate 0 would be off the plate"), + (10, "filament_set_flushing", {"prime_volume_mode": "Saving"}, + "prime_volume_mode: this printer has no purge mode to choose"), + (11, "filament_set_colour", {"filament_slot": 2, "colour": "white"}, 'Slot 2\'s colour "white" is not #RRGGBB'), + (12, "project_set_settings", {"values": {"wipe_tower_x": {"index": 0, "value": 300}}}, + "The prime tower of plate 0 would be off the plate"), ] - for step, values, words in refusals: - self.t.refused(f"{s} {step}: refused", lambda: self.c.call("project_set_settings", values=values), - words=words) + for step, tool, args, words in refusals: + self.t.refused(f"{s} {step}: refused", lambda: self.c.call(tool, **args), words=words) self.project_is(f"{s} {step}", *after) + self.t.refused(f"{s} 8: the refusal names filament_set_flushing", + lambda: self.c.call("project_set_settings", values={"flush_multiplier": 0.5}), + words="filament_set_flushing") + read = self.c.call("project_get_settings", keys=["filament_colour"]) + self.t.equal(f"{s} 8: project_get_settings points filament_colour to filament_list", + (read.get("items"), read.get("unknown_keys"), read.get("type_of")), + ([], ["filament_colour"], {"filament_colour": "filament_list"})) self.t.equal(f"{s} 8: the slots", self.slots(), "0,0") - self.t.equal(f"{s} 10: the purge mode", self.project_values("prime_volume_mode")["prime_volume_mode"], - "Default") + self.t.equal(f"{s} 10: the purge mode", self.c.call("filament_list").get("prime_volume_mode"), "Default") # The Klipper printer purges a filament change into the prime tower, so the purges are in tower_g. grams13, changes13 = self.slice_ok(f"{s} 13") @@ -866,7 +876,7 @@ class FilamentsTest: for slot in (1, 2)) and changes13 > 0, (grams13, changes13)) self.project_is(f"{s} 13", *after) - self.run("project_set_settings", values={"flush_volumes_matrix": {"index": 1, "value": 200}}) + self.run("filament_set_flushing", flush_volumes_matrix={"index": 1, "value": 200}) grams14, changes14 = self.slice_ok(f"{s} 14") self.project_is(f"{s} 14", "#FFFFFF;#000000", "0.7", "0,200,300,0", pei, "150,180") self.t.check(f"{s} 14: slot 2 purges less into the tower", grams14[2][2] < grams13[2][2], (grams14, grams13)) @@ -874,7 +884,7 @@ class FilamentsTest: all(abs(grams14[slot][0] - grams13[slot][0]) <= 0.01 for slot in (1, 2)) and changes14 == changes13, (grams14, changes14, grams13, changes13)) - self.run("project_set_settings", values={"flush_multiplier": 1.4}) + self.run("filament_set_flushing", flush_multiplier=1.4) grams15, _ = self.slice_ok(f"{s} 15") after15 = ("#FFFFFF;#000000", "1.4", "0,200,300,0", pei, "150,180") self.project_is(f"{s} 15", *after15) diff --git a/tools/mcp/test_files.py b/tools/mcp/test_files.py index 67adf8f1f0..b4aef2ea05 100644 --- a/tools/mcp/test_files.py +++ b/tools/mcp/test_files.py @@ -29,7 +29,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 from checks import (GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, answer_all, dialogs, gcode, layer_gcode, # noqa: E402 meshes, normal, obj_facts, plates, presets, project, recent, reimport, run, sliced, sliced_flags, - slots, start, undo_steps, unsaved, values, wait) + slot_colours, slots, start, undo_steps, unsaved, values, wait) HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.dirname(os.path.dirname(HERE)) @@ -210,7 +210,7 @@ class FilesTest: else "no file") def colours(self): - return self.c.call("project_get_settings", keys=["filament_colour"])["items"][0]["value"] + return slot_colours(self.c) def rule_uses(self, match): for rule in self.c.call("app_state").get("auto_answer_rules", []): @@ -1072,8 +1072,8 @@ class FilesTest: self.t.equal(f"{s} {step}: the reply", (reply.get("filament_slot"), reply.get("filament_slots")), (slot, slot)) self.t.equal(f"{s} {step}", slots(self.c), ",".join(["0"] * slot)) - for i, colour in enumerate(("#FF0000", "#00FF00", "#0000FF")): - self.run("project_set_settings", values={"filament_colour": {"index": i, "value": colour}}) + for slot, colour in enumerate(("#FF0000", "#00FF00", "#0000FF"), 1): + self.run("filament_set_colour", filament_slot=slot, colour=colour) self.t.equal(f"{s} 4", slots(self.c), "0,0,0") self.t.equal(f"{s} 4: the colours", self.colours(), "#FF0000;#00FF00;#0000FF") self.cube("on_two", 20, 80, 128) diff --git a/tools/mcp/test_gizmos.py b/tools/mcp/test_gizmos.py index 0d0daad3b8..f61e86f825 100644 --- a/tools/mcp/test_gizmos.py +++ b/tools/mcp/test_gizmos.py @@ -23,7 +23,7 @@ import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 -from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, run, start, wait # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, run, slots, start, wait # noqa: E402 FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tests", "fixtures") STAR = os.path.join(FIXTURES, "star.svg") @@ -235,7 +235,7 @@ class GizmosTest: return None def slots(self): - return self.c.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"] + return slots(self.c) def process(self): """(the selected process preset, its wall_loops).""" diff --git a/tools/mcp/test_gui_tools.py b/tools/mcp/test_gui_tools.py index a9d1aba239..1256d966cb 100644 --- a/tools/mcp/test_gui_tools.py +++ b/tools/mcp/test_gui_tools.py @@ -24,7 +24,7 @@ import zipfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 -from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, plates, refusal, run, start, wait # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, plates, refusal, run, slot_colours, start, wait # noqa: E402 ADD_CUBE = "orca_command:add_primitive_cube:orca" UNDO = "orca_command:undo:orca" @@ -167,7 +167,7 @@ class GuiToolsTest: return "\n".join(texts) def colours(self): - return self.c.call("project_get_settings", keys=["filament_colour"])["items"][0]["value"] + return slot_colours(self.c) def bed_type(self): return self.c.call("project_get_settings", keys=["curr_bed_type"])["items"][0]["value"] @@ -354,7 +354,8 @@ class GuiToolsTest: self.idle() self.t.equal(f"{s} 17: two filament slots", len(self.filaments()), 2) self.objects_are(f"{s} 17", *both) - self.run("project_set_settings", values={"filament_colour": "#FF0000;#0000FF"}) + self.run("filament_set_colour", filament_slot=1, colour="#FF0000") + self.run("filament_set_colour", filament_slot=2, colour="#0000FF") self.t.equal(f"{s} 18: the colours", self.colours(), "#FF0000;#0000FF") self.objects_are(f"{s} 18", *both) button = self.filament_button() @@ -678,7 +679,7 @@ class GuiToolsTest: # The wizard card step 15 ticks starts unticked only while its printer is not installed. if MARLIN in self.printers(): self.run("printer_uninstall", models=[{"vendor": "Custom", "model": "Generic Marlin Printer"}]) - self.run("project_set_settings", values={"filament_colour": "#26A69A"}) + self.run("filament_set_colour", filament_slot=1, colour="#26A69A") self.t.equal(f"{s}: the start: the filaments", self.filaments(), [PLA]) self.t.equal(f"{s}: the start: the colour", self.colours(), "#26A69A") self.t.equal(f"{s}: the start: no region", self.region(), "") diff --git a/tools/mcp/test_mixed_filaments.py b/tools/mcp/test_mixed_filaments.py new file mode 100644 index 0000000000..28ca762d3e --- /dev/null +++ b/tools/mcp/test_mixed_filaments.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""The mixed filaments of the filament list, as the test_mixed_filaments entry of +tools/mcp/test-entries/filaments_settings.md designs them. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_mixed_filaments.py + +Reading the mixed filaments with filament_list; adding one with filament_add_mixed and changing one with +filament_edit_mixed, each from its arguments and through its dialog, where the gradient is set; a mixed slot having no +preset or colour of its own; and what deleting or merging a filament that a mix mixes does to the mix: broken, as the +sidebar leaves it, and repaired by an edit. After every step the test reads the slots and the mixes back with +filament_list and compares them, whole, with the state the entry writes out. Every scenario runs on the Generic +Klipper Printer 0.4 from a start of its own (checks.start()) with three physical slots, and the test puts slot 1's +colour back at its end. It exits 0 when every check passes. +""" + +import os +import re +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, filament_rows, run, slots, start, wait # noqa: E402 + +START = {"printer": KLIPPER, "process": KLIPPER_STD, "filaments": [GENERIC_PLA]} +RED, BLUE = "#FF0000", "#0000FF" +HEX = re.compile(r"^#[0-9A-F]{6}$") +EDIT, ADD = "Edit Mixed Filament", "Add Mixed Filament" + + +class MixedFilamentsTest: + def __init__(self, client, folder): + self.c = client + self.t = Checks() + self.folder = folder + self.slot1_colour = None + + # ---- Calls and reads ---- + + def run(self, tool, **args): + return run(self.c, tool, **args) + + def rows(self): + return filament_rows(self.c) + + def row(self, slot): + return self.rows()[slot - 1] + + def mixes(self): + """The mixed rows as the entry writes them: `4 = 2,3 @ 50,50, bottom 3 top 2, per part`, joined by `·`.""" + out = [] + for row in self.rows(): + if not row["mixed"]: + continue + text = f"{row['filament_slot']} = {','.join(map(str, row['components']))} @ {','.join(map(str, row['ratios']))}" + gradient = row.get("gradient") + if gradient: + text += f", bottom {gradient['bottom']} top {gradient['top']}" + if gradient.get("per_part"): + text += ", per part" + if gradient.get("curve") != "linear": + text += f", curve {gradient.get('curve')}" + if row.get("broken"): + text += ", broken" + out.append(text) + return " · ".join(out) + + def state_is(self, label, want_slots, want_mixes): + self.t.equal(f"{label}: the slots", slots(self.c), want_slots) + self.t.equal(f"{label}: the mixes", self.mixes(), want_mixes) + + def dialogs(self): + return [{"title": d.get("title"), "buttons": [b.get("label") for b in d.get("buttons", [])], + "message": d.get("message", "")} for d in self.c.call("app_state").get("dialogs", [])] + + def on(self, name): + """The filament of the object named `name`, from object_list.""" + listing = self.c.call("object_list", limit=500) + found = [o for p in listing["plates"] for o in p["objects"] if o["name"] == name] + found += [o for o in listing.get("outside", []) if o["name"] == name] + return found[0]["filament"] if len(found) == 1 else found + + def held(self, label, reply, title): + """A call the dialog titled `title` holds: the reply waits on it, and it is the one dialog open, with OK and + Cancel.""" + self.t.equal(f"{label}: the call waits on a dialog", reply.get("status"), "blocked_by_dialog") + shown = self.dialogs() + self.t.equal(f"{label}: the dialog", [d["title"] for d in shown], [title]) + self.t.check(f"{label}: with OK and Cancel", bool(shown) and {"OK", "Cancel"} <= set(shown[0]["buttons"]), shown) + return shown + + def finish(self, label, reply): + """The job of a call a dialog held, once the dialog is answered, and no dialog left open.""" + result = self.c.await_job(reply, timeout=60) + self.t.equal(f"{label}: no dialog is left open", self.dialogs(), []) + return result + + def set_in_dialog(self, title, **values): + for name, value in values.items(): + self.c.call("widget_set_value", target={"name": name, "within": title}, value=value) + + def click(self, title, label): + self.c.call("widget_click", target={"label": label, "within": title}) + + def cube(self, name, x): + self.run("object_add_primitive", shape="cube", size=[20, 20, 20], name=name, position=[x, 100, 0]) + + def save_delete_open(self, label, name, slot, want_slots): + """Adds a cube, saves the project to `name`, deletes mixed filament `slot`, and opens the file again. The cube is + there so that the open shows no warning, which the app gives for a project file that holds no object.""" + self.cube("kept", 100) + path = os.path.join(self.folder, name) + self.run("project_save", path=path, overwrite=True) + self.run("filament_delete", filament_slot=slot) + self.t.equal(f"{label}: after the delete", slots(self.c), want_slots) + self.run("project_open", path=path, discard_changes=True) + wait(self.c, "idle") + self.t.equal(f"{label}: the cube is back", self.on("kept"), 1) + + def begin(self, label, colours=False): + """The scenarios' start: three physical slots of Generic PLA, slots 2 and 3 red and blue with `colours`.""" + self.t.equal(f"{label}: the start's presets", start(self.c), START) + if self.slot1_colour is None: + self.slot1_colour = self.row(1)["colour"] + for _ in range(2): + self.run("filament_add") + self.t.equal(f"{label}: three physical slots", slots(self.c), "0,0,0") + self.t.equal(f"{label}: of Generic PLA", [(r.get("preset"), r.get("type")) for r in self.rows()], + [(GENERIC_PLA, "PLA")] * 3) + if colours: + self.run("filament_set_colour", filament_slot=2, colour=RED) + self.run("filament_set_colour", filament_slot=3, colour=BLUE) + self.t.equal(f"{label}: slots 2 and 3 red and blue", [r["colour"] for r in self.rows()[1:]], [RED, BLUE]) + + @staticmethod + def red_blue(colour): + return int(colour[1:3], 16), int(colour[5:7], 16) + + # ---- Scenarios ---- + + def adding(self): + s = "adding and reading" + self.begin(s) + reply = self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + self.t.equal(f"{s} 1: the reply", reply, {"added": True, "filament_slot": 4}) + self.state_is(f"{s} 1", "0,0,0,1", "4 = 2,3 @ 50,50") + row = self.row(4) + self.t.check(f"{s} 1: the mix has a colour and no preset or type of its own", + bool(HEX.match(row.get("colour", ""))) and "preset" not in row and "type" not in row, row) + self.t.equal(f"{s} 1: the physical slots keep their preset", [r.get("preset") for r in self.rows()[:3]], + [GENERIC_PLA] * 3) + self.t.equal(f"{s} 1: the matrix is 4 x 4", len(self.c.call("filament_list")["flush_volumes_matrix"]), 16) + + reply = self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + self.t.equal(f"{s} 2: a mix the project has is not added again", reply, {"added": False, "filament_slot": 4}) + self.state_is(f"{s} 2", "0,0,0,1", "4 = 2,3 @ 50,50") + + reply = self.run("filament_add_mixed", components=[1, 2, 3], ratios=[20, 30, 50]) + self.t.equal(f"{s} 3: the reply", reply, {"added": True, "filament_slot": 5}) + after3 = ("0,0,0,1,1", "4 = 2,3 @ 50,50 · 5 = 1,2,3 @ 20,30,50") + self.state_is(f"{s} 3", *after3) + + self.t.refused(f"{s} 4: components without ratios are refused", + lambda: self.c.call("filament_add_mixed", components=[2, 3]), code="components_and_ratios") + self.state_is(f"{s} 4", *after3) + + reply = self.run("filament_add") + self.t.equal(f"{s} 5: a physical slot goes before the mixes", reply.get("filament_slot"), 4) + after5 = ("0,0,0,0,1,1", "5 = 2,3 @ 50,50 · 6 = 1,2,3 @ 20,30,50") + self.state_is(f"{s} 5", *after5) + + self.save_delete_open(f"{s} 6", "mixes.3mf", 6, "0,0,0,0,1") + self.state_is(f"{s} 6: the project file keeps its mixes", *after5) + + def no_preset(self): + s = "a mixed slot has no preset or colour of its own" + self.begin(s) + self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + unchanged = ("0,0,0,1", "4 = 2,3 @ 50,50") + self.state_is(f"{s}: the start", *unchanged) + code = "mixed_filament_slot" + + self.t.refused(f"{s} 1: settings_get", lambda: self.c.call( + "settings_get", type="filament", filament_slot=4, keys=["filament_cost"]), code=code) + self.state_is(f"{s} 1", *unchanged) + self.t.refused(f"{s} 2: settings_set", lambda: self.c.call( + "settings_set", type="filament", filament_slot=4, values={"filament_cost": 99}), code=code) + saved = self.c.call("settings_get", type="filament", filament_slot=2, compare=":saved") + self.t.equal(f"{s} 2: the preset slots 1 to 3 hold has no unsaved change", saved.get("items"), []) + self.state_is(f"{s} 2", *unchanged) + self.t.refused(f"{s} 3: settings_list", lambda: self.c.call( + "settings_list", type="filament", filament_slot=4), code=code) + self.state_is(f"{s} 3", *unchanged) + self.t.refused(f"{s} 4: preset_save", lambda: self.c.call( + "preset_save", type="filament", filament_slot=4, name="MCP Mixed Slot"), code=code) + users = [p.get("name") for p in self.c.call("preset_list", type="filament", source="user", limit=500)["items"]] + self.t.check(f"{s} 4: no preset was saved", "MCP Mixed Slot" not in users, users) + self.state_is(f"{s} 4", *unchanged) + + items = self.c.call("preset_list", type="filament", query="Generic PLA", limit=500)["items"] + used = [i.get("filament_slots") for i in items if i.get("name") == GENERIC_PLA] + self.t.equal(f"{s} 5: the mixed slot does not use its first component's preset", used, [[1, 2, 3]]) + self.state_is(f"{s} 5", *unchanged) + + self.t.refused(f"{s} 6: another colour", lambda: self.c.call( + "filament_set_colour", filament_slot=4, colour="#00FF00"), words="Slot 4 is a mixed filament") + own = self.row(4)["colour"] + self.t.check(f"{s} 6: the mix's colour is not set", own != "#00FF00", own) + self.state_is(f"{s} 6", *unchanged) + reply = self.run("filament_set_colour", filament_slot=4, colour=own.lower()) + self.t.equal(f"{s} 7: its own colour, in any case, changes nothing", reply.get("changed"), False) + self.state_is(f"{s} 7", *unchanged) + + self.t.refused(f"{s} 8: a mixed filament's flushing volume", lambda: self.c.call( + "filament_set_flushing", flush_volumes_matrix={"index": 3, "value": 50}), + words="belongs to a mixed filament, which is never flushed") + entry = self.c.call("filament_list")["flush_volumes_matrix"][3] + self.t.check(f"{s} 8: entry 3 is not set", entry != 50, entry) + self.state_is(f"{s} 8", *unchanged) + + def changing(self): + s = "changing a mix" + self.begin(s, colours=True) + self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + self.cube("on_mix", 100) + self.run("settings_set", target="object", object=0, values={"extruder": 4}) + self.state_is(f"{s}: the start", "0,0,0,1", "4 = 2,3 @ 50,50") + self.t.equal(f"{s}: the start: the cube on the mix", self.on("on_mix"), 4) + + def edit(**args): + return self.run("filament_edit_mixed", filament_slot=4, **args) + + reply = edit(components=[2, 3], ratios=[70, 30]) + self.t.equal(f"{s} 1: the reply", reply, {"filament_slot": 4, "changed": True}) + self.state_is(f"{s} 1", "0,0,0,1", "4 = 2,3 @ 70,30") + red, blue = self.red_blue(self.row(4)["colour"]) + self.t.check(f"{s} 1: the blend has more red than blue", red > blue, self.row(4)["colour"]) + self.t.equal(f"{s} 1: the cube stays on the mix", self.on("on_mix"), 4) + + reply = edit(components=[2, 3], ratios=[70, 30]) + self.t.equal(f"{s} 2: the same mix changes nothing", reply.get("changed"), False) + self.state_is(f"{s} 2", "0,0,0,1", "4 = 2,3 @ 70,30") + + edit(components=[2, 3], ratios=[30, 70]) + self.state_is(f"{s} 3", "0,0,0,1", "4 = 2,3 @ 30,70") + red, blue = self.red_blue(self.row(4)["colour"]) + self.t.check(f"{s} 3: the blend has more blue than red", blue > red, self.row(4)["colour"]) + self.t.equal(f"{s} 3: the cube stays on the mix", self.on("on_mix"), 4) + + edit(components=[1, 2, 3], ratios=[20, 30, 50]) + after4 = ("0,0,0,1", "4 = 1,2,3 @ 20,30,50") + self.state_is(f"{s} 4: the slot keeps its number", *after4) + self.t.equal(f"{s} 4: the cube stays on the mix", self.on("on_mix"), 4) + + for step, args, code in [ + (5, {"filament_slot": 2, "components": [2, 3], "ratios": [50, 50]}, "not_mixed_filament"), + (6, {"filament_slot": 9, "components": [1, 2, 3], "ratios": [20, 30, 50]}, "no_such_slot"), + (7, {"filament_slot": 4, "components": [2, 3]}, "components_and_ratios"), + (8, {"filament_slot": 4, "components": [2, 2], "ratios": [50, 50]}, "duplicate_component")]: + self.t.refused(f"{s} {step}: refused", lambda: self.c.call("filament_edit_mixed", **args), code=code) + self.state_is(f"{s} {step}", *after4) + self.t.equal(f"{s} {step}: the cube stays on the mix", self.on("on_mix"), 4) + + def gradient(self): + s = "a gradient, through the dialogs" + self.begin(s) + self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + self.state_is(f"{s}: the start", "0,0,0,1", "4 = 2,3 @ 50,50") + + reply = self.c.call("filament_edit_mixed", filament_slot=4) + self.held(f"{s} 1", reply, EDIT) + self.state_is(f"{s} 1", "0,0,0,1", "4 = 2,3 @ 50,50") + + self.set_in_dialog(EDIT, gradient=True, gradient_direction=1, per_part_gradient=True) + self.click(EDIT, "OK") + self.t.equal(f"{s} 2: the job's reply", self.finish(f"{s} 2", reply), {"filament_slot": 4, "changed": True}) + self.state_is(f"{s} 2", "0,0,0,1", "4 = 2,3 @ 50,50, bottom 3 top 2, per part") + + self.run("filament_edit_mixed", filament_slot=4, components=[3, 2], ratios=[50, 50]) + self.state_is(f"{s} 3: a gradient stays for two", "0,0,0,1", "4 = 3,2 @ 50,50, bottom 2 top 3, per part") + + self.run("filament_edit_mixed", filament_slot=4, components=[1, 2, 3], ratios=[20, 30, 50]) + after4 = ("0,0,0,1", "4 = 1,2,3 @ 20,30,50") + self.state_is(f"{s} 4: a gradient goes for three", *after4) + + reply = self.c.call("filament_edit_mixed", filament_slot=4) + self.held(f"{s} 5", reply, EDIT) + self.click(EDIT, "Cancel") + self.t.equal(f"{s} 5: the job's reply", self.finish(f"{s} 5", reply), {"filament_slot": 4, "changed": False}) + self.state_is(f"{s} 5", *after4) + + reply = self.c.call("filament_add_mixed") + self.held(f"{s} 6", reply, ADD) + self.state_is(f"{s} 6", *after4) + self.set_in_dialog(ADD, gradient=True) + self.click(ADD, "OK") + self.t.equal(f"{s} 7: the job's reply", self.finish(f"{s} 7", reply), {"added": True, "filament_slot": 5}) + after7 = ("0,0,0,1,1", "4 = 1,2,3 @ 20,30,50 · 5 = 1,2 @ 50,50, bottom 1 top 2") + self.state_is(f"{s} 7", *after7) + + reply = self.c.call("filament_add_mixed") + self.held(f"{s} 8", reply, ADD) + self.click(ADD, "Cancel") + self.t.equal(f"{s} 8: the job's reply", self.finish(f"{s} 8", reply), {"added": False}) + self.state_is(f"{s} 8", *after7) + + self.save_delete_open(f"{s} 9", "gradient.3mf", 5, "0,0,0,1") + self.state_is(f"{s} 9: the project file keeps the gradient", *after7) + + def deleting(self): + s = "deleting or merging a filament that a mix mixes" + self.begin(s) + self.run("filament_add_mixed", components=[1, 2], ratios=[50, 50]) + self.run("filament_add_mixed", components=[2, 3], ratios=[50, 50]) + self.cube("on_one", 70) + self.cube("on_mix", 130) + self.run("settings_set", target="object", object=1, values={"extruder": 4}) + start_state = ("0,0,0,1,1", "4 = 1,2 @ 50,50 · 5 = 2,3 @ 50,50") + self.state_is(f"{s}: the start", *start_state) + self.t.equal(f"{s}: the start: the cubes' filaments", (self.on("on_one"), self.on("on_mix")), (1, 4)) + + reply = self.c.call("filament_delete", filament_slot=1, merge_into=4) + shown = self.held(f"{s} 1", reply, "Warning") + self.t.check(f"{s} 1: the question says the mix uses the filament", + bool(shown) and "uses this physical filament" in shown[0]["message"], shown) + self.c.call("dialog_answer", button="Cancel") + self.t.refused(f"{s} 1: the job", lambda: self.c.await_job(reply, timeout=60), code="merge_cancelled") + self.t.equal(f"{s} 1: no dialog is left open", self.dialogs(), []) + self.state_is(f"{s} 1", *start_state) + self.t.equal(f"{s} 1: the cube stays on filament 1", self.on("on_one"), 1) + + self.t.refused(f"{s} 2: the merge answered no ahead", lambda: self.c.call( + "filament_delete", filament_slot=1, merge_into=4, break_mix=False), code="mixed_uses_slot") + self.t.equal(f"{s} 2: no dialog opened", self.dialogs(), []) + self.state_is(f"{s} 2", *start_state) + + reply = self.run("filament_delete", filament_slot=1, merge_into=4, break_mix=True) + self.t.equal(f"{s} 3: the reply", {k: reply.get(k) for k in ("filament_slot", "merged_into", "broken_mixed")}, + {"filament_slot": 1, "merged_into": 3, "broken_mixed": [3]}) + self.t.equal(f"{s} 3: no dialog opened", self.dialogs(), []) + after3 = ("0,0,1,1", "3 = 0,1 @ 50,50, broken · 4 = 1,2 @ 50,50") + self.state_is(f"{s} 3", *after3) + self.t.equal(f"{s} 3: the cubes are on the mix", (self.on("on_one"), self.on("on_mix")), (3, 3)) + + reply = self.c.call("plate_slice") + self.t.equal(f"{s} 4: the slice of an object on a broken mix ends in an error", + [(p.get("index"), p.get("outcome"), p.get("error")) for p in reply.get("plates", [])], + [(0, "error", "A mixed filament has a deleted or mismatched component")]) + self.state_is(f"{s} 4", *after3) + + reply = self.run("filament_edit_mixed", filament_slot=3, components=[1, 2], ratios=[50, 50]) + self.t.equal(f"{s} 5: an edit repairs it", reply.get("changed"), True) + self.state_is(f"{s} 5", "0,0,1,1", "3 = 1,2 @ 50,50 · 4 = 1,2 @ 50,50") + + reply = self.run("filament_delete", filament_slot=2) + self.t.equal(f"{s} 6: the reply names the broken mixes", reply.get("broken_mixed"), [2, 3]) + self.t.equal(f"{s} 6: no dialog opened", self.dialogs(), []) + after6 = ("0,1,1", "2 = 1,0 @ 50,50, broken · 3 = 1,0 @ 50,50, broken") + self.state_is(f"{s} 6", *after6) + + self.t.refused(f"{s} 7: the last physical slot", lambda: self.c.call("filament_delete", filament_slot=1), + code="last_filament_slot") + self.state_is(f"{s} 7", *after6) + + self.t.refused(f"{s} 8: a mix beside one physical slot", lambda: self.c.call("filament_delete", filament_slot=2), + code="mixed_list_hidden") + self.state_is(f"{s} 8", *after6) + + def run_all(self): + for name, scenario in [("adding and reading", self.adding), ("no preset of its own", self.no_preset), + ("changing a mix", self.changing), ("a gradient", self.gradient), + ("deleting or merging", self.deleting)]: + self.t.scenario(name, scenario) + if self.slot1_colour is not None: + self.run("filament_set_colour", filament_slot=1, colour=self.slot1_colour) + self.t.equal("slot 1's colour is put back", self.row(1)["colour"], self.slot1_colour) + self.run("project_new", discard_changes=True, preset_changes="discard") + return self.t.exit_code() + + +def main(): + client, _ = orca_mcp.session_client() + with tempfile.TemporaryDirectory(prefix="orca-mixed-") as folder: + return MixedFilamentsTest(client, folder).run_all() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_operation_routes.py b/tools/mcp/test_operation_routes.py index c1d2720646..ef8398039e 100644 --- a/tools/mcp/test_operation_routes.py +++ b/tools/mcp/test_operation_routes.py @@ -138,7 +138,7 @@ def main(): if blocked.get("status") == "blocked_by_dialog": client.call("dialog_answer", button="OK") client.await_job(blocked) - flags = client.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"].split(",") + flags = shared.slots(client).split(",") check("a mixed filament was added", "1" in flags, flags) if "1" in flags: slot = flags.index("1") + 1 diff --git a/tools/mcp/test_plates.py b/tools/mcp/test_plates.py index 4083632053..d44680264b 100644 --- a/tools/mcp/test_plates.py +++ b/tools/mcp/test_plates.py @@ -20,7 +20,7 @@ import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 -from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, objects, plates, run, start, wait # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, objects, plates, run, slots, start, wait # noqa: E402 ROW = re.compile(r'^"(.*)" (\d+)( \*)?( L)?$') CUBE = {"shape": "cube", "size": [20, 20, 20]} @@ -102,27 +102,18 @@ class PlatesTest: (x, y), (w, d) = item["origin"], item["size"] return x, y, x + w, y + d - def save_and_reopen(self, label, name, empty=False, preset_changes="keep"): + def save_and_reopen(self, name, preset_changes="keep"): """Saves the project to a new file, starts a new one, keeping or discarding the presets' unsaved changes as - `preset_changes` says, and opens the file. A project with no objects opens after the app's warning that the - file holds no geometry, which is answered OK.""" + `preset_changes` says, and opens the file. The project holds an object, as a project file that holds none + opens after the app's warning that it holds no geometry.""" path = os.path.join(self.folder, name) self.run("project_save", path=path, overwrite=True) self.run("project_new", discard_changes=True, preset_changes=preset_changes) - if not empty: - self.run("project_open", path=path) - else: - job = self.c.call("project_open", path=path) - wait(self.c, "dialog") - messages = [d.get("message") for d in self.c.call("app_state").get("dialogs", [])] - self.t.equal(f"{label}: the open warns that the file holds no geometry", messages, - ["The file does not contain any geometry data."]) - self.run("dialog_answer", button="OK") - self.c.await_job(job) + self.run("project_open", path=path) wait(self.c, "idle") def slots(self): - return self.c.call("project_get_settings", keys=["filament_is_mixed"])["items"][0]["value"] + return slots(self.c) def rule_uses(self, match): for rule in self.c.call("app_state").get("auto_answer_rules", []): @@ -177,8 +168,12 @@ class PlatesTest: self.plates_are(f"{s} 7", *after5) self.redo() self.plates_are(f"{s} 8", *after6) - self.save_and_reopen(f"{s} 9", "life.3mf", empty=True) - self.plates_are(f"{s} 9: the project file keeps the names and locks", *after6) + self.run("object_add_primitive", name="kept", plate=0, **CUBE) + after9 = ('"Left" 1 *', '"" 0 L') + self.plates_are(f"{s} 9: the cube on plate 0", *after9) + self.save_and_reopen("life.3mf") + self.plates_are(f"{s} 9: the project file keeps the names and locks", *after9) + self.objects_are(f"{s} 9: and the cube on plate 0", [(0, "kept")]) def by_index(self): s = "by index" @@ -444,7 +439,7 @@ class PlatesTest: self.t.equal(f"{s} 14: plate 1 has no layer G-code", items[1]["layer_gcode"], []) settings_are(f"{s} 14", S(), after4) # The new project drops the printer's edit, so that the open asks nothing about it; the project brings it back. - self.save_and_reopen(f"{s} 15", "settings.3mf", preset_changes="discard") + self.save_and_reopen("settings.3mf", preset_changes="discard") settings_are(f"{s} 15: the project file keeps a plate's own settings", S(), after4) edited = [i["key"] for i in self.c.call("settings_get", type="printer", compare=":saved", limit=50)["items"]] self.t.equal(f"{s} 15: the project brings back the printer's support_multi_bed_types", edited, diff --git a/tools/mcp/test_slice_preview.py b/tools/mcp/test_slice_preview.py index 2709d590d9..edb9be0750 100644 --- a/tools/mcp/test_slice_preview.py +++ b/tools/mcp/test_slice_preview.py @@ -26,7 +26,7 @@ import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 -from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, run, start, wait # noqa: E402 +from checks import GENERIC_PLA, KLIPPER, KLIPPER_STD, Checks, run, slot_colours, start, wait # noqa: E402 ROW = re.compile(r'^"(.*)" (\d+)( \*)?( L)?( S)?$') CUBE = {"shape": "cube", "size": [20, 20, 20]} @@ -44,7 +44,7 @@ TRAVEL_SPEED = 350 # The purge of the two-colour slices, and so the depth of their prime tower, follows the slots' colours and the flush # multiplier, which the printer keeps as an earlier test or run left them: a seeded folder's slot colour and # multiplier. -SLOT_COLOUR, FLUSH_MULTIPLIER = "#26A69A", "0.3" +SLOT_COLOUR, FLUSH_MULTIPLIER = "#26A69A", 0.3 # The view the view switches start from, the app's defaults, which Starts from sets after the default layout. VIEW = {"labels": False, "overhangs": False, "outline": False, "wireframe": False, "gridlines": True, "axes": True, "navigator": True, "gcode_window": True, "projection": "perspective", "section": {"on": False}, @@ -1015,7 +1015,7 @@ class SlicePreviewTest: after12 = [C(26, "pause", 5.2), C(51, "custom", 10.2, "M104 S220"), C(76, "change_filament", 15.2, filament=2)] reply = lg(add=[{"layer": 26, "type": "pause"}, {"layer": 76, "type": "change_filament", "filament": 2}]) got = self.codes(f"{s} 12", after12, reply=reply) - colours = self.c.call("project_get_settings", keys=["filament_colour"])["items"][0]["value"].split(";") + colours = slot_colours(self.c).split(";") change = [c for c in got if c.get("type") == "change_filament"] self.t.equal(f"{s} 12: the filament change's colour is slot 2's", change[0].get("color") if change else None, colours[1] if len(colours) > 1 else colours) @@ -1326,11 +1326,11 @@ class SlicePreviewTest: s = "the start" self.t.equal(f"{s}: the presets", start(self.c), {"printer": KLIPPER, "process": KLIPPER_STD, "filaments": [GENERIC_PLA]}) - self.run("project_set_settings", values={"filament_colour": {"index": 0, "value": SLOT_COLOUR}, - "flush_multiplier": float(FLUSH_MULTIPLIER)}) - items = self.c.call("project_get_settings", keys=["filament_colour", "flush_multiplier"])["items"] - self.t.equal(f"{s}: the slot's colour and the flush multiplier", {i["key"]: i["value"] for i in items}, - {"filament_colour": SLOT_COLOUR, "flush_multiplier": FLUSH_MULTIPLIER}) + self.run("filament_set_colour", filament_slot=1, colour=SLOT_COLOUR) + self.run("filament_set_flushing", flush_multiplier=FLUSH_MULTIPLIER) + listed = self.c.call("filament_list") + self.t.equal(f"{s}: the slot's colour and the flush multiplier", + (listed["filaments"][0]["colour"], listed["flush_multiplier"]), (SLOT_COLOUR, [FLUSH_MULTIPLIER])) self.run("preferences_set", values={"auto_slice_after_change": False}) items = self.c.call("preferences_get", keys=["auto_slice_after_change"])["items"] self.t.equal(f"{s}: no slice after a change", {i["key"]: i["value"] for i in items},