mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-26 23:29:14 +00:00
Official OrcaSlicer MCP support (#17819)
Some checks are pending
Build all / Linux x86_64 (push) Blocked by required conditions
Build all / Look for build script changes (push) Waiting to run
Build all / Windows build script tests (push) Blocked by required conditions
Build all / build_linux (push) Waiting to run
Build all / Build Windows (push) Blocked by required conditions
Build all / build_macos_arch (push) Waiting to run
Build all / Build macOS Universal (push) Blocked by required conditions
Build all / Linux aarch64 (push) Blocked by required conditions
Build all / Windows x64 (push) Blocked by required conditions
Build all / Windows arm64 (push) Blocked by required conditions
Build all / macOS arm64 (push) Blocked by required conditions
Build all / Slice check (Linux aarch64) (push) Blocked by required conditions
Build all / Publish Test Results (push) Blocked by required conditions
Build all / Flatpak (push) Waiting to run
Check CAD offer table / Check CAD offer table (push) Waiting to run
Post-merge profiles / Publish profile caches (push) Waiting to run
Shellcheck / Shellcheck (push) Waiting to run
Some checks are pending
Build all / Linux x86_64 (push) Blocked by required conditions
Build all / Look for build script changes (push) Waiting to run
Build all / Windows build script tests (push) Blocked by required conditions
Build all / build_linux (push) Waiting to run
Build all / Build Windows (push) Blocked by required conditions
Build all / build_macos_arch (push) Waiting to run
Build all / Build macOS Universal (push) Blocked by required conditions
Build all / Linux aarch64 (push) Blocked by required conditions
Build all / Windows x64 (push) Blocked by required conditions
Build all / Windows arm64 (push) Blocked by required conditions
Build all / macOS arm64 (push) Blocked by required conditions
Build all / Slice check (Linux aarch64) (push) Blocked by required conditions
Build all / Publish Test Results (push) Blocked by required conditions
Build all / Flatpak (push) Waiting to run
Check CAD offer table / Check CAD offer table (push) Waiting to run
Post-merge profiles / Publish profile caches (push) Waiting to run
Shellcheck / Shellcheck (push) Waiting to run
* Give the MCP server its own AI features group in Preferences
The group shows whether agents can connect and at which address, and copies a
ready-made setup for Claude Code, Codex, opencode, DeepSeek Harness or other
apps. A second OrcaSlicer window on the same configuration folder says another
window is serving agents and takes the server over when that window closes.
* Let users choose HTTP or stdio when adding OrcaSlicer to an agent
* Refuse Design tab reads while a rebuild owns the document
* Let MCP clients drive every gizmo
Also fixes a crash when a script answers the primitive size dialog, the Simplify ratio box being
ignored, a Measure crash after a reload, and Mesh Boolean showing a bare "tool" label.
* Let MCP clients do the OrcaSlicer tasks the agent benchmark found missing
* Point agents at the MCP harness instead of an in-repo skill
* Add explain_settings so agents can look up what settings do
It returns each setting's full tooltip, its page and group, and its wiki link, maps every setting
by page and group, and finds settings by the words of their help text. get_settings no longer
includes tooltips in its metadata.
* set window size to 1920x1200 for MCP scripts
* Add a Run Script dialog for running MCP scripts in the app
* update git ignore
* Add app recording and screenshots for MCP agents and the Help menu
Agents can record OrcaSlicer to video, captioned with the current tool call, and encode it to MP4.
People get Take Screenshot and Start/Stop Recording in the Speed Dial and the Help menu, with a
dialog for the recording and encoding settings.
* Stop the app flickering while a recording runs on Windows
* Make recording overlays opt-in, with pointer and caption switches in Start Recording
* Let agents ask for an MP4 when starting a recording
* Show a REC pill in the tab bar while a recording runs
* Make the MCP tools easier for agents to use
get_settings now gives each setting's description and settings page and finds settings by what
they do, replacing explain_settings. set_view orbits the camera by degrees, the same on every
install, and a painting stroke that would miss the object is refused with the pixel to start it
at instead of turning the camera. Tools accept the argument names and forms agents commonly use,
save_project refuses a .gcode.3mf path, and select range-checks part and instance indices.
* Keep the Run Script dialog in front after its file picker closes on macOS
* Add a script editor with suggestions and saving to the Run Script dialog
* Show the recording and screenshot icons in the Speed Dial at full size
* Keep the Run Script dialog in sight while a script runs on macOS
* Let MCP agents read and drive web dialogs and plugin pages
Agents can also answer a native message box that is already open (Windows and Linux), and URLs in
replies hide credential values.
* Fix MCP canvas captures failing right after a tab switch on Wayland
* Add missing includes in the MCP sources and the recording dialog
* Make the MCP harness and its test scripts executable
* Stop the MCP stdio bridge leaving a quit OrcaSlicer as a zombie process
* Report frames that failed to encode in stop_recording's result
* Tell MCP agents when a call fails because the display is off
* Name the open dialog when a script step times out waiting for its job
* Make canvas screenshots taken right after a layer or view type change show the change
* Add Python scripts and plugin tools to the MCP server
The MCP tools are listed in core, API and UI lanes. With Python scripts turned on in Preferences, agents
and people can run Python against the open app; plugins holding the tools permission can call the tools,
and plugins can offer operations of their own to agents. Calls can pin object and volume ids so a stale
index is refused, and run_script takes a script as JSON text as well as an object.
* Run Python scripts like python file.py, with the whole plugin API
* Document the whole orca Python API and search every catalog from api_describe
* Tell agents which scope a setting belongs to when they name the wrong one or none
* Ask for approval only on MCP calls that delete without undo, and mark the tools that reach outside the app
* Let agents select hidden filaments and printers by name
* Show agents the selection, the Python setting and the Design tab in get_state
* Tell agents what list_objects ids are for and how paged replies continue
* Make the MCP tool descriptions shorter and consistent, with the UI locators described once
* Explain in the MCP design doc why tools have no output schema
* Let the MCP harness call api_call, whose argument is named tool
* Read a modal dialog's controls and values into its MCP message
* Let install_local_plugin take a plugin file's path
* Report why a local plugin install failed
* Show Speed Dial plugin refreshes and installs in an open Plugins dialog
* Show a reloaded local plugin's new version in the Plugins dialog
* Give python_api's static methods their own documentation
* Give register_operation a signature Python can declare
* Correct the MCP web fixture's comments on its thread command
* Start OrcaSlicer from the stdio bridge only when a tool is called
* Show dialogs in Wayland recordings and stop blank Wayland window captures
* Show popups, context menus and tooltips in Wayland recordings and screenshots
* Show popups in Windows and macOS recordings and screenshots
* Keep MCP canvas clicks working when OrcaSlicer is in the background
* Show context menus, dialogs and web views in macOS screenshots and recordings
Recording frames are also spaced as documented when capture is slow, and a drop-down that has left the screen is no longer drawn into macOS frames.
* Fix Windows popup capture and MCP stalls in native menus and dialogs
* Move the MCP server only when its port is edited in Preferences
* Vendor Ace 1.45.2 for the script editors
* Split Run Script into Action Replay and a docked Python Run Script panel
* Add an MCP tool that lists open windows with refs for screenshots and input
* Give MCP tools plain names and call recorded tool lists replays
* Keep the call_cad_tool registration with the Design tab's MCP code
* Move the Design tab's MCP code next to the MCP server
* Reach the Design tab only through the MCP server
* Give every CAD tool a one-line summary and details
* Add list_cad_tools and describe_cad_tool and call CAD tools by tool and args
* Attach orca_mcp.py to a running app and call CAD tools from Python
* Give the CAD read and sketch tools runnable examples
* Give the CAD solid, dress-up and datum tools runnable examples
* Give every CAD tool runnable examples
* Bound the MCP journal by the size of its calls' arguments
* Run the CAD sketch checks against the app's MCP server
* Remove the Design tab's Docker test setup and check its offer table in CI
* Correct CAD docs and comments that disagree with the code
* Pin the journal's byte accounting and the CAD table's id notes in tests
* Find a portable OrcaSlicer through a symlinked binary in orca_mcp.py
* Correct when the Design tab is created and why sketch_set_value exists
* Describe orca_mcp.py's macOS datadir lookup as the stdio bridge's
* Keep the MCP journal's trim linear and its lock short
* End the journal entry of a job that never runs
* Clarify the CAD tool descriptions and examples
* Tidy orca_mcp.py's CAD helper and its tests
* Describe CAD checks and sketch code as they are, not as they were
* Finish describing the CAD sources and checks as they are
* Describe thicken_surface's capped and simple paths as they are
* Say which sheets thicken_surface refuses
* Report sketch loop areas as positive whichever way the loop runs
* Report degrees of freedom instead of -1 for sketches with no constraints
* Keep constraints among entities a sketch transform moves together
* Build revolve's default rectangle beside the axis instead of across it
* Report every bad example reference and describe the sketch code as it is
* Move the Design-tab GUI checks into the MCP tests
* Fix four Design-tab sketch bugs the GUI tests found
A sketch with thousands of constraints no longer freezes the app, the first value field after launch
takes typed digits, an array's spacing and copy count can both be typed, and cancelling a new Text
removes it.
* Let auto-answer rules answer file and folder pickers with a path
* Run the Design-tab GUI tests through MCP on every platform
* Refuse MCP clicks on main menu items the app would show greyed
* Report the selected sketch constraint over MCP and test badge selection in the Design GUI tests
* Add set_window and set_view camera target and zoom over MCP
* Mention set_window in the MCP server instructions and keep them under 4096 characters
* Load the flow ratio calibration models without the 3MF import dialog
* Make set_window work on Wayland and on an X server without a window manager
Also keeps a polygon drawn near an axis regular in the Design tab, and lets the Design GUI tests run on Linux.
* Launch MCP harness instances on a private headless desktop on Linux, falling back to Xvfb
* Point MCP name misses at the right catalog and give each argument one name
A tool, Speed Dial action or CAD tool called through the wrong tool is told
where it runs, search_actions ranks a query's words as search_tools does, and
every list replies with items.
Renamed arguments: set_view's target and view are look_at and canvas,
list_widgets' root is target, mouse_gesture's path is waypoints, the presets'
changes is preset_changes, set_height_ranges' layer_config_ranges is ranges,
and the main window is "main" for screenshot and start_recording.
The harness's launch takes --python-scripts to allow Python scripts in the
instance it starts.
* List objects by plate over MCP and call a part "part" in every tool
list_objects replies as the Objects panel is laid out: each plate with the
objects on it, then the objects on no plate. list_plates gives how many
objects a plate has, and every tool refuses a plate the project lacks in the
same words.
* Drop the old MCP names the server still read and the text that still used them
set_view's view, the print scope and window for the main window are refused
like any unknown name.
* Reduce script permissions to a single "run unrestricted" switch
Python scripts always run and follow the plugin permission checks; the switch in Preferences lets
them bypass the checks. Plugins call the tools and offer operations without a separate permission.
* Fix macOS issues found driving the app over MCP
set_window brings a window minimized while zoomed back to normal, and its documentation covers
raising windows and native dialogs. A right-click in the Design tab picks what it points at on
Retina displays, where the Design tab GUI tests now run too, and the Text dialog opens in a plain
font. The app no longer hangs when dialogs open and close with the display asleep, and no longer
crashes when a new project or a delete removes an object that has parts.
* Run commands, tools and the plugin API through one operations layer
A Speed Dial command, the MCP tool that does the same thing and the plugin
API's preset calls now run one shared operation, so every route accepts and
refuses the same states, with one wording and a code for each refusal. An
import by a command or a tool is one undo step, and import_file adds geometry
only.
The cases where two routes behaved differently now behave the same: a project
is not saved under a .gcode.3mf name, an empty project exports as .3mf but not
as STL, arrange runs from any view and with a gizmo open, a mixed-colour
filament slot is refused as one, a hidden preset is shown before it is
selected, and a layer is refused while the Preview has none.
* Hold Speed Dial commands, MCP tools and Design tools in one command catalog
Every command takes JSON arguments and has one function for a person and for
automation: with no arguments it does what a person's pick does, and with
arguments it runs silently. The Design tab's CAD tools are commands that
call_tool runs, and they show as Speed Dial tiles on the Design tab.
* Correct what command descriptions and the skill reference tell agents
A Design tile's command says it follows its right-click menu row and may
decline, export_config says how its rows are named, and the generated skill
reference says which commands are the person's own and how the Design tab is
turned on.
* Fix the sketching test's undo check and a missing include found on Linux
* Open the Speed Dial with Space right after a tab switch, without a KWin title bar on Wayland
* Fix MCP menu paths, CAD-off replies, test-instance sign-in, Preview focus and clang-tidy on macOS
* Make the MCP harness and page tests pass reliably on a loaded machine and on macOS
* Make the automation runtime its own subsystem, with MCP as one front end
Everything that drives OrcaSlicer by command (the dispatch of the command
catalog, jobs, the journal, replays, Python scripts, recordings) lived
inside the MCP server's service class. So Action Replay, the Run Script
panel, a plugin's tool call, a person's recording and a run from the
command line each had to start "the MCP service", with all of its GUI
hooks, although none of them needs a server or an agent.
The automation runtime is now a subsystem of its own. It starts the first
time a front end asks for it and knows none of them. The MCP endpoint
(HTTP, the protocol, the token, the discovery file, the takeover of a port
another window holds) is one front end beside the others, opened and
closed without stopping what the others run. The widget inspector, menu
capture and ImGui item recording are turned on only by a front end that
drives the GUI, so a person's recording or long command does not carry
them.
The part of the runtime that needs no GUI is the library
libslic3r_automation, built without wxWidgets and tested by its own suite,
automation_tests. A wx dependency in it fails to build, and its tests no
longer link the GUI library or the embedded Python.
The command line has one option set for this: --run FILE runs a replay or
a Python script once the GUI is ready, with --outputdir for its files, and
--unrestricted-scripts and --cad turn their settings on for one run
without saving them. --mcp-run, --mcp-run-out and --mcp-token are gone;
the scripts setting is python_scripts_unrestricted and a session's output
folder is <datadir>/automation/out. get_app_state reports ready and
version at the top level, and its mcp block describes the endpoint only.
No change to slicing output.
* Keep only the MP4 of an encoded recording unless asked to keep the raw video file
* Expect keep_raw_video_file among the start_recording command's arguments
* revert localization/i18n/OrcaSlicer.pot
* Let a plugin file be named script.py or mcp.py
* Leave a Speed Dial command's unexpected exception to the app's handler
* Keep the Speed Dial's Undo and Redo to where the Edit menu allows them
* Keep menu update handlers away from a freed context menu's items
* Turn the automation's GUI instruments off when nothing drives the GUI
* Cut the MCP test sweep's run time without losing coverage
* Keep the Design toolbar at its own height when the Design tab first opens
* Open every MCP test instance at 1600x900 in the top left of the screen
* Rename the completion and result enums clear of Xlib's macros
* Run the MCP sweep on the desktop, and answer the certificate prompt
* Click a partly shown list row, and let a refusal keep its result.json
* Make the MCP test sweep pass on Windows
Windows now keeps one window per data folder, as macOS and Linux do.
* Name the Design tab's commands in the search_tools description
* Keep layer G-code when New Project's prompt is cancelled or saves the project
* Report a project save that wrote nothing as not saved
* Make the MCP tool descriptions say what the tools do, and rename four misleading names
* Rename and regroup the Design tab's MCP commands, and add the missing ones
The Design commands follow Fusion 360's names and grouping: one command per
job, with a `type` argument for its variants, so 133 commands become 88. An
old name or argument is refused. What the tab could do and no command
reached now has one: re-opening a committed sketch, selecting geometry,
confirming or cancelling an open tool, placing a body, sketch patterns and
dimensions, and text, SVG art and projected edges from arguments.
Ten defects in the Design tab's cards and sketch tools found on the way are
fixed. For a person: the Mirror tool binds a mirrored line or arc to its
source, Commit to Plate and Export STEP stop when the open card's Confirm
fails, and the Speed Dial keeps a query typed before its list arrives.
* Give replay files a semver format version
* Document the Design tab's command set
* Regroup the slicer's MCP commands and let each run from its arguments
Outside the Design tab an agent had 175 commands, 50 of them in the tool
list. There are now 118, named by what they act on (`object_`, `plate_`,
`preset_`, `filament_`, `plugin_` and so on), and 115 are listed. Each takes
its target and values in the call, acts on the selection when it names no
target and says what it acted on; an old name is refused. Printers and
system filaments install and uninstall, preferences read and write, plugins
enable, reload, uninstall and refresh, and objects reorder, with no dialog
to drive.
The Speed Dial keeps its 129 tiles under the same ids. Eight defects in the
rows these commands share with the menus are fixed. For a person: an object
row that cannot run says why instead of "Select an object first.", rows
that failed no longer claim success, Duplicate Plate can be undone, and
Refresh Plugins picked while a refresh runs now runs after it instead of
beside it.
* Document every MCP command in one reference, the Design tab's in a section of its own
The commands outside the Design tab now have a reference like the Design tab's: what each does and
takes, which menu rows call it, which calls ask in a dialog and the call that does not. Both live in
docs/HLSD/mcp-tools.md, OrcaSlicer's commands first and the Design tab's at the end.
* Say menu item, not menu row, in the MCP commands and docs
The MCP command descriptions, docs and code called an entry of the app's
menus a "row", the word they also use for the rows of the object list and
the app's other lists. They now say "menu item", so a row is only ever a row
of a list or table. Command names, arguments and Speed Dial tile ids are
unchanged.
* Say action and Speed Dial, not tile and palette, in the MCP commands and docs
The MCP commands, their catalog and the docs called a command's Speed Dial entry a "tile" and the Speed
Dial itself "the palette", words the app already uses for an entry's icon and for sets of colours. They now
say "action" and "Speed Dial", as action_search and action_run do, and the catalog's tiles, tile_group and
in_palette fields are now actions, action_group and has_own_action. Speed Dial ids, and the pins people
stored under them, are unchanged.
* Catalog the MCP sweep tests and design their Python replacements
Every sweep test now has an entry, by area under tools/mcp/test-entries/, saying what it checks, how it decides pass
or fail and what it leaves unchecked, and TESTS.md holds the rules a new test is designed by before it is written.
The entries also design the Python tests that take the place of the replays, which leave the sweep as those land;
the fifteen operation replays that could not fail are removed now.
* Check the plates in the MCP sweep with a Python test that reads every step back
test_plates.py takes the place of the plate replays: after each add, duplicate, rename, lock, select or delete it
reads the plate list back and compares it with the state its entry writes out, and it checks what a lock keeps
Arrange and Auto-Orient from doing, a plate's own settings, the filament slots and the plate icons. Arranging a
locked plate is refused with advice that names plate_lock with the plate, instead of a needless plate_select.
* Check every area of the MCP sweep with Python tests that read each step back
The sweep's objects, presets, filaments, settings, project files, slicing, gizmos and GUI tools are tested by Python
tests that compare the app's state after every step with the values their entries write out, in place of the
replays, and the existing tests' checks that could not fail now can. The calls these tests found wrong now behave
as described: moving one instance no longer sinks the others, a toolpath export writes the layers shown, an
auto-answered dialog no longer reports its call blocked, and a web dialog that has just opened takes requests.
* Design the sweep tests for the gizmo and printing commands
The sweep's entries now describe the tests for the commands that open a gizmo or a print dialog on a target and,
where they can, do its job from arguments: what each step must leave behind and how every refusal is told apart.
They also take every sweep call that would open a Bambu printer's Print or storage dialog off the scratch datadir,
so no test run messages a real printer.
* Check that a refused gizmo opening leaves the selection as it was
The gizmo commands' test design now also checks a refused opening made while another gizmo is open, and says which
refusals put back the selection the call had changed and which come before it changes anything.
* Let MCP clients open the painting, Measure, Simplify and Mesh Boolean gizmos on a named object
object_paint, object_measure, object_simplify and part_boolean open their gizmo on the object, instance or part a
client names, where before a client had to know the gizmo existed and click its icon after selecting. A refused
opening says why in the gizmo's own terms, such as Mesh Boolean needing two parts, and leaves the selection and the
undo history as they were.
* Let MCP clients cut an object along a plane with object_cut
object_cut cuts an object at a height or along any plane, keeping either piece or both, laid where the Cut gizmo would
lay them or kept as two parts of one object, in one undo step, as the gizmo's Perform cut does. Named with only its
object it opens the Cut gizmo on it, for connectors, the dovetail and cuts along a contour. A plane that misses the
object, or an object with connectors, is refused with the model left as it was.
* Let MCP clients lay an object on a face, set its brim ears, and add text or an SVG to a named object
object_lay_on_face turns an instance so that the face a direction names lies on the bed, as a click in the Lay on Face
gizmo does, and object_set_brim_ears places brim ears at bed positions, or clears them, as the Brim Ears gizmo stores
them; called with only their object, both open their gizmo. object_add_text and object_add_svg can name the object the
part joins and make it a negative part or a modifier. The Brim Ears gizmo shows ears set this way when it next opens,
rather than writing back the ones it held.
* Let MCP clients start a print, send to a Bambu printer, and test the print host
print_start opens the dialog the Print button opens for the selected printer, for one plate or all of them, and is
refused where the button would be disabled, such as for a plate not sliced. printer_send, and the Send G-code Speed
Dial action with it, open the dialog that sends to a Bambu printer's storage where they used to refuse such a printer,
and take the plate to send. printer_test_host checks that the printer's print host answers, as the Test button of its
connection dialog does.
* Let MCP clients read the connected printer's status and pause, resume or stop its print
printer_status reads what the Device tab shows of the printer it is connected to: its state, progress, layer, the
file printing and the temperatures, with no serial number and nothing sent to the printer. print_pause, print_resume
and print_stop do what the tab's buttons do, and are refused, saying why, where the printer's state does not allow
them or a job can be resumed only at the printer.
* Let MCP clients see and close the Action Replay window
The Action Replay window was hidden from every GUI tool, so an agent or a test that opened it could not close it,
and it stayed on screen for the rest of the run. It is now listed with a ref, its page can be read, and Escape sent
to it closes it. Its file pickers and confirmation prompts stay the person's alone.
* Document the gizmo and printing commands for MCP clients and developers
The command reference now describes the 13 gizmo and printing commands: which gizmo or dialog each opens, the
arguments that do the job without it, the Print button's routes for each kind of printer, and what is left to the
dialog. The server design says how the commands reach the gizmos, the print dialogs and the printer, and the test
notes name what no test reaches: the Bambu print dialogs and a physical printer.
* Fix object_cut on planes just off straight down, and text added with several objects selected
An object_cut plane tilted less than a degree from straight down was cut level, and object_add_text or
object_add_svg given only a part type, with several objects selected, made a new ordinary object. The cut now keeps
the plane's tilt, the add is refused one_object_only, and the sweep also checks lay on face's refusals, clearing
brim ears with the gizmo open, and print calls that name a plate.
* Add a typed text or SVG to an object when only its negative part or modifier is selected
object_add_text or object_add_svg given only a part type, with nothing but a negative part or modifier of an object
selected, made a new ordinary object. It now selects that object whole and adds the part to it, as a right click on
the object's row does before its Add Part, Add Negative Part and Add Modifier menus.
* Keep the flush multiplier when viewing a G-code file
Viewing a G-code file set the project's flush multiplier to 1 whatever the file was sliced with, and
the 1 stayed through a new project, a preset switch and a restart, so every later multi-colour slice
purged several times as much. The project now keeps the file's own multiplier, and the preview still
shows the purge volumes the file was sliced with.
* Delete mixed filament slots and export sliced files of unsliced plates over MCP
An agent could not remove a mixed filament slot, so a project that had one never got back to a single slot, and
deleting a physical slot a mix used left the mix broken. filament_delete now removes a mixed slot as the sidebar's
list does and refuses to delete a slot a mix needs. Exporting a sliced file to a given path no longer fails on the
file name template when the plate is not sliced, as it did on the Generic Klipper Printer.
* Keep MCP calls reliable on a busy machine
When the computer was busy, agents saw calls fail that work on a quiet one. A right click's context menu could open
on screen instead of reaching the call, a click could find a button still disabled, a call could report it was
blocked by a dialog an auto-answer rule had already answered, the first call through the stdio bridge could be
refused while the app it started was still loading, and a replay could fail waiting on a step that had finished.
Each of these now waits for the app to catch up instead.
* Run the MCP sweep on shared data folders with the Generic Klipper Printer
The sweep made a fresh data folder for every test, copying all of Bambu Lab's profiles each time, left tens of
gigabytes of run folders behind, and failed outright on a test that only failed while other tests loaded the
machine. Each job now keeps one data folder for all its tests, seeded with the Generic Klipper Printer as a person's
folder carries over from day to day; a test that fails beside others runs again alone and is remembered as one to run
alone; and a passing test's folder is deleted as soon as it passes.
* Thread bores reliably wherever the part sits on the bed
In the Design tab, threading a bore could fail with "thread removed no material" depending only on
where the part sat: an M5 standoff at the centre of a 250 x 250 mm bed could not be tapped, while the
same part a few millimetres away could, and some blind holes could not be tapped anywhere. Threads now
cut into through and blind holes alike, at any position.
* Fix the MCP sweep's files and preferences tests failing on the DRC depth
Both tests still set the DRC depth to 0, a value the Preferences dialog does not take, so they failed. The files test
now checks that the depth is the app's lossless default and fails by name on a data folder set to a lossy one, and the
preferences test no longer checks a value outside the dialog's range.
* Say what the slice preview test leaves now that viewing G-code keeps the flush multiplier
The test's entry still said a viewed G-code file leaves the flush multiplier at 1. It now says the test leaves the 0.3
its start sets, and why that start still sets it: the filaments test leaves the same printer at 1.4.
* Say which slot colours and flush multiplier the filaments test leaves
A developer reading the filaments test's entry could not tell that it leaves white and black slots and a flush
multiplier of 1.4 on the shared data folder, which the next test meets and a two-colour slice purges more for.
* Edit mixed filaments and their gradients over MCP as the sidebar does
Agents can now read the whole filament list with filament_list, change a mixed filament with filament_edit_mixed,
and set a gradient by driving the Add or Edit Mixed Filament dialog. The slot colours and the flushing settings move
from the project tools to filament_set_colour and filament_set_flushing, beside the rest of the filament list.
Deleting or merging a filament that a mix uses now behaves as it does in the sidebar, and the settings tools no
longer edit a physical filament's preset through a mixed slot.
* Keep sf-plan design and planning files out of the repository
* Make the full MCP sweep finish in about 11 minutes
A full sweep on six jobs took 17 to 19 minutes, too long to run often. Its 66 tests are
now 40 that cover the same areas with each scenario run once, and the sweep finishes in
about 11 minutes. The Speed Dial test checks a handful of commands no other test reaches,
and the sweep runs only test_*.py files; smoke_test.json and the Design replays are
played by the tests that use them.
* Let agents answer the mixed-filament merge warning on macOS
Merging a filament into a mixed filament that uses it asks for confirmation first. On
macOS that question was a native alert, which held the app so an agent driving it over
MCP could neither see nor answer it. It now opens in Orca's own dialog, as the app's
other warnings do, with the same text and buttons.
* Fix crash when a web window is closed as soon as it opens
On macOS, opening the Action Replay window and closing it straight away with Escape
crashed OrcaSlicer a moment later. Web windows can now be closed the moment they open.
* Make the MCP sweep's tests pass on macOS
Several sweep tests failed on every macOS run while passing on Windows: the Run Script
panel and plugin command checks, the auto-orient placement check, and the Design tab's
edge re-pick checks. They now pass on both.
* Fix renaming in the Design tab ending as soon as it starts on Linux
* Make test_cad_commands pass when another app takes the focus on Linux
* Stop testing that the early MCP command-line options are refused
The command-line test checked that four MCP options from before their rename are refused. They never shipped in a release, so the check guarded nothing a user could rely on, and on Windows it printed the app's full usage text into the sweep's console four times.
* Make MCP sweep tests pass in any order, one app per job
A test's verdict depended on which test had run before it on the shared data folder, and fixed pauses failed tests
on a busy machine. Each job now runs its tests in one app, every test starts from the same baseline whatever ran
before, and tests wait for the state they expect rather than for a set time; --shuffle runs the sweep in a random
order to show any test that still leans on another. The command-line test is gone, as it checked options outside
the MCP server.
* Clear every sweep test's serial mark at once with --forget all
* Let MCP path rules answer folder pickers on Linux
A dialog_auto_answer rule with a path cancelled every folder picker on Linux, such as the Preferences
download folder's Browse and the recording dialog's Change..., so a script couldn't pick a folder there and
the sweep's Preferences and Speed Dial tests failed. Folder pickers now take the path as on Windows and
macOS; file pickers still cancel on Linux.
* Let MCP path rules answer file pickers on Linux
A dialog_auto_answer rule with a path still cancelled every open and save file picker on Linux, so a script
couldn't save or open a project through the File menu or insert an SVG in the Design tab there, and the sweep
skipped those steps. File pickers now take the path as on Windows and macOS. This needs the updated
wxWidgets, so rebuild the deps.
* Bring the checked-in command reference up to date with the Linux picker rules
The reference still said a path rule cancels a file picker on Linux and that a save picker needs a new
file, so the reference test failed.
* Let MCP calibration tests print with any physical filament
calibration_generate_test always printed with filament slot 1, so an agent could not calibrate another filament of
the project or, on a multi-extruder printer, the nozzle that prints it. It now takes filament_slot, as the
Calibration dialogs' filament list offers, prints on the extruder the filament map gives that filament, and says in
its reply which extruder that is.
* Start Action Replay with a replay that slices the Orca Cube on a new plate
The Action Replay window now opens with a replay that adds a plate, puts the Orca Cube on it, slices that
plate and saves a screenshot of the preview. It checks that the new plate really sliced, so it fails
instead of passing on an empty plate.
* Write replay results to the temp folder unless an output folder is given
Replays that name no output folder, whether run from Action Replay, by an agent or with --run, left a
<name>.out folder beside the replay file or filled the data folder. They now write to a new
orca_action_replay/replay-<time> folder in the temp folder, or inside --outputdir when a --run launch names one.
* Fix --run crashing at exit when a dialog is still open
A --run launch that ended with a dialog open, such as the prompt to restore an unsaved project left by an
earlier session, crashed while closing and returned a crash code instead of the replay's result. It now
closes the dialog first and exits with the replay's code, and it no longer asks about or discards a
person's unsaved project, which their next normal launch still offers to restore.
* Refuse misspelt Design arguments and tell agents how to fix refused calls
A misspelt argument to most Design commands was ignored, so the command ran with
its default, such as a helix built with the default pitch. Every Design command now
refuses it and names the arguments it takes. Refusals of a missing object or part,
an unknown setting key, an invalid setting value or a preset that is not installed
now say the valid range, the similar keys, what the setting takes or the command
to use, and plate_add and object_add_handy_model say what they added.
* Say in a word why an MCP call was refused, and how to get past it
Design commands were refused with numbers such as -32002 or with no code at all; they now say design_busy,
precondition, invalid_argument, rebuild_failed and the like, so an agent can tell a wrong argument from a design
that is not ready, on every route that takes arguments. Refusals worded for a person, such as an open gizmo or a
selected object, carry a hint naming the call that gets past them, and an index too large for the app or written
as 2.0 is no longer misread as another object, plate or instance.
* Show what each command does when tool_search lists a group
Agents listing the Design tab's commands, or any other group, got bare names and had to look each one up to
choose. tool_search {group} now gives each command's first sentence and, in Design, its heading, in the order
the description's index uses. action_search names the Speed Dial's sections section rather than group, so they
are no longer mistaken for tool_search's groups, and a wrong section is refused with the sections there are
instead of returning nothing.
* Give agents a manual for any MCP command with tool_describe
An agent could read a command's arguments only as raw JSON Schema, with its conditional rules left to decode and
no word on where an object index or a face id comes from. tool_describe now gives any command's manual, listed or
not: every parameter at every depth with its allowed values, ranges and defaults, the schema's rules as sentences,
the Speed Dial items that run it with their arguments, its examples, and which tool lists a value the schema can't.
* List the commands tools/list leaves out with tool_list, in place of tool_search
tool_search matched words, so an agent that asked for a goal such as "add a brim" or "round the edges"
got unrelated commands. Agents now read tool_list, which lists the Design tab's commands, the menu items
that take no arguments and the plugins' operations with what each does, and a call refused for its
arguments names the tool_describe call that gives that command's parameters.
* Document how agents find and read commands with tool_list and tool_describe
* List the Speed Dial's actions with action_list, in place of action_search
action_search ranked actions by matching an agent's words, so an action named differently from the request
was missed. action_list lists them by section and title for the agent to choose from, as tool_list does
for commands.
* Browse the Python API a module at a time with script_list_api and script_describe_api
script_search_api ranked the API by an agent's words, so a goal phrased in other words found the wrong entries.
Agents now list what a module or class holds with script_list_api and read one entry's whole documentation
with script_describe_api.
* Browse settings by page with settings_list_pages, and read them by key
settings_get and preferences_get matched an agent's words, so a goal such as "add a brim" found the wrong
settings. Agents now list a settings tab's pages and groups with settings_list_pages, read a page's settings
and what each does with settings_list, and read named settings with settings_get and preferences by tab
with preferences_get.
* Pass clang-tidy on the MCP list tools and drop the docs' last search wording
* Point tool_describe's manuals to more values' sources, and keep plugin rules
An agent reading a manual now learns where a filament's purge mode, a calibration's shaper type, a
hole's point, printer_install's models and dialog_answer's dialog come from, and sees that a plugin
operation can reach outside the app. What a plugin's schema says that the manual can't show, such as a
required argument with no property, now comes with the raw schema, and a schema that takes any argument
says so instead of looking like one that takes none.
* Say in tool_describe's manuals which objects take keys they don't list
Every object in a manual now says whether it takes keys besides its properties, at any depth, as the top
level already did. A plugin schema whose properties can't be read now comes with the raw schema instead of
looking like one that takes no arguments.
* Keep tool_describe from calling an object open when a plugin schema may close it
A plugin schema can close an object through a keyword the manual keeps raw, such as allOf. The manual
then no longer says the object, or the call, takes other keys, and leaves the attached schema to say
what it accepts.
* Say in the MCP design doc exactly what a manual leaves out for a raw schema
* Say where tool_describe keeps a schema part it cannot show
* Tell agents in the server instructions how to find what to call
An agent connecting to the MCP server now reads, right after the workflow, how each catalog is found
by listing: commands place by place and the rest through tool_list, a command's manual before calling
it through tool_call, settings by page, Speed Dial actions by section and the Python API by module.
* Tell agents which catalog filters are optional and that values_from may name several tools
* Say in the server instructions that values_from belongs to a parameter
* Keep MCP replies short and free of float noise
Agents now read an object's position as 60.001 rather than 60.001007080078125, and a Design
command's zero as 0 rather than 4.4e-16, without the wrapper and ok flag that said nothing; a
client that computes with the numbers can still ask for them whole. object_list gives a short row
per object unless asked for detail, so a plate of a hundred objects fits a client's reply limit,
and app_log returns 50 lines by default.
* Shrink the MCP tool list
Agents load less text before their first call: the object and part id guards are explained once
in the server instructions instead of in every schema that takes one, and each tool's title is
sent once.
* Mark names as code in the MCP tool descriptions
Agents can tell an argument or a reply field from an English word in every tool description. The
server instructions say what the Speed Dial is, a call held by a dialog says how to run it without
asking next time, and object_add_text and object_add_svg say what they reply.
* Shorten the longest MCP tool descriptions
The ten largest definitions in the tool list repeated much of what their parameters already say. They now
say it once, taking about 4.9 KB off the tool list an agent reads at the start of every session, with
nothing they described left out.
* Let MCP commands name objects, parts and instances by id
An agent that read an object's id in object_list could only pass it as a guard beside the index, and the index moves
whenever objects are deleted, split or reordered; an id passed as an index was refused without saying what it was.
Every command that names an object, a part or an instance now takes its index or its id, both together still a
guard, and object_list gives each instance's id too. An id given as an index is refused with what that id names, and
recorded replays keep naming targets by index, so they still run in a new session.
* Fix the CI failures from the first build and test run of the MCP branch
The Flatpak build failed to compile the MCP bridge, clang-tidy flagged four missing
includes, and several new tests failed only on CI: plugin and script tests on Windows
runners with a non-UTF-8 code page, and two tests that raced on slower machines.
* Give a polygon drawn on the axes the same constraints on every platform
A square drawn on the axes through sketch_draw was locked level on x64 but could be
left free to rotate on arm64, so its constraints and degrees of freedom depended on
the CPU, and the test of them failed on macOS arm64 and Windows arm64. A polygon's
side that lies on an axis is now pinned Horizontal or Vertical on every platform, as
the Polygon tool pins it, so such a square has all four sides pinned.
* Fix two unit tests that failed at random on CI
The plugin-unload test of the automation suite and the in-flight tool call
test of the Python script runner each failed now and then on a busy runner,
macOS arm64 and Linux aarch64 in the last run, with nothing wrong in the app.
Both pass however the runner schedules their threads.
* Fix the Flatpak unit-test jobs failing on the page agent test
Both Flatpak unit-test jobs failed one test, which reads the MCP server's
page agent script, because the script was missing from the test bundle those
jobs run from. The bundle carries it, so the jobs run that test as the other
platforms' jobs do.
* Warn in Action Replay when a step can run a program
A replay someone sends you can hold a Python script or set a post-processing
script, and either runs a program on your computer when the replay plays. The
window listed those steps with no warning. They carry a "Can run a program"
tag, as a step that writes a file or sends to a printer carries its own, and a
step that makes its call through tool_call shows the tags of that call.
* Stop a calibration when its save prompt is cancelled
Choosing Cancel when a calibration asked to save the open project still
created the calibration on top of that project, so the project's pauses and
color changes ended up in the calibration's G-code. Only the flow rate tests
stopped. Cancel leaves the project as it was for every calibration.
* Warn in Action Replay when a step replaces a post-processing script
A replay could swap one of your post-processing scripts for its own by
setting a single entry of the list, and the step showed no warning. It now
carries the "Can run a program" tag, as setting the whole list does.
* Add the Agent Activity pane
A new pane, opened from View > Agent Activity or the Speed Dial, lists live what an AI agent and other
automation (Action Replay, Run Script, the command line, plugins) do in OrcaSlicer while it is open: each
call with its source, what it changed, failures with their reason, the steps of a run and the dialogs a
rule answered. Opening a call shows its request and response with passwords, keys and typed text masked,
so a person can watch and check what an agent is doing to their project.
* Fix the clang-tidy check failing on the Agent Activity test
* Fix sweep tests failing with a current_path error in a shared app
When the test that launched a job's app passed, the sweep deleted that test's folder while the app was still
running in it. Later tests in that app then failed on the first preset reload with "boost::filesystem::current_path:
No such file or directory", as test_printers, test_settings and test_speed_dial_open did. The job's app now runs in
a folder of the job's own.
The settings reads now place a printer's extruder settings on its Extruder page on every printer. After a printer
with several extruders, they could put a setting on a page such as "Extruder 3" that the selected printer does not
have, and leave it out of the page it is on, which made test_presets fail when it ran after test_printers.
The sweep can also run every app on a private Xvfb display with --xvfb, for a machine without a desktop, and with
--headless or --xvfb the tests that start their own apps stay off the desktop too. Where Openbox is installed, Xvfb
runs it as the window manager, so drop-down lists and popups stay open as on a desktop and the whole sweep passes
there. Apps launched side by side each get a display of their own, and test_slice_preview no longer fails where the
3D view draws slowly, as on Xvfb.
A test that fails beside the others and then passes alone no longer runs alone in every later sweep: each sweep
runs it among the others again, so a failure that returns is seen, and --forget, which undid that, is gone. Only
the tests sweep.json marks exclusive run alone from the start.
* Stop the Speed Dial offering settings of extruders the printer lacks
After a printer with several extruders, selecting one with fewer left the extra extruders' settings in the Speed
Dial and the settings search, such as Retraction Length under Extruder 3 on a single-extruder printer. They now
list only the extruders the selected printer has.
* Report a dialog closed when an answer ends it on a busy machine
On a busy machine, dialog_answer could reply without closed: true for a dialog its answer ended, such as a web
dialog cancelled while its page was still busy, although the dialog closed a moment later. An agent was then told
the dialog was still open. The reply now says closed for every dialog an answer ends, message boxes included,
however busy the app is.
* Organize the MCP tool code by place and the Design commands by heading
Each place an agent finds commands under (Objects, Plates, View and windows and so on) now has one source file
under Mcp/Tools/, and the Design tab's commands have one file per Design heading, so a developer finds a command
where tool_list lists it and adds a new one beside its neighbours. A unit test fails when a command is added in
another place's file. No change to what agents or people see: the command catalog is byte-identical.
* Run the MCP sweep in CI on the Linux AppImage
Every Build all run now drives the x86_64 Linux AppImage it built through
all the MCP sweep tests on Xvfb with Openbox. When a test fails, its logs are
uploaded with the run.
* Fix the MCP sweep tests that fail on a CI runner
test_run_sweep failed on a machine with no X display, and test_gizmos failed
where the desktop's UI font is as wide as Ubuntu's default, DejaVu Sans. The CI
job summary also lists every failed run of a test, its run alone included.
* Name the Design commands by their place, like the other MCP tools
Thirty-four Design commands were bare verbs (extrude, fillet, measure), so an
agent could not tell from a name where a command acts or find a place's
commands together. Every Design command now starts with its place: design_,
sketch_, solid_, surface_, construct_, body_ or feature_. Replacing objects when
committing a design to the plate deletes them as Prepare's Delete does, and the
guide to making a feature reachable covers Design commands.
* Fix the Speed Dial and other web pages sometimes freezing on Windows
Opening the Speed Dial occasionally left it, the Home page and every other
web page in OrcaSlicer unresponsive, with one CPU core kept busy, until the
app was restarted. The Flushing volumes dialog and the printer camera view
no longer risk the same freeze. The Speed Dial's search field still takes
the keyboard focus on every open, and the Flushing volumes dialog still
falls back to English text when a translation cannot be shown.
* Show the app's message when a Speed Dial pick in the MCP sweep gets no answer
A sweep test whose Speed Dial pick got no answer from the dial's page failed with only
"last seen None". It now fails with the app's own message, such as "The page did not
answer within 30 s".
* List long widget labels whole and keep each MCP fact in one place
widget_list cut a widget's label at 120 bytes, so a long path or tooltip came back truncated, and a test that
read it back failed on a machine with a longer folder; labels now come back whole. Adding or renaming a command
or a sweep test no longer means updating hand-kept lists, copied test helpers or the same text in several docs,
and the runner's own test now fails when a sweep test has no entry in the index.
* Make the MCP server doc an architecture overview
The server doc walked through every command, repeating what the tool reference and each command's own description already say. It now covers the components, how they fit together and the design rules every command follows, and points to the tool reference for what each command does. Caller-facing facts that only the server doc held are now in the tool reference.
* Make calls say whether they ask, and show Prepare after an agent's new project
Calls into the plater, object list and tabs now say in words whether they ask a
person or run without prompts, instead of passing bare true/false flags. An
agent's project_new now does what New Project does: it shows the Prepare tab and
tells plugins about the new project.
* Ask before a plugin calls OrcaSlicer's tools
Any plugin could call OrcaSlicer's tools through orca.host.tools without a permission, so it could change your project, run post-processing scripts and answer permission prompts. It now needs the OrcaSlicer tools permission or full access, which it can declare as it loads or is asked for the first time it calls, like its other permissions. The Plugins dialog's Permissions tab has a switch for it, and turning it off ends what the plugin's calls left in force.
* fix test_cad_commands
* Fix the camera view teardown test crashing
The Web media controller teardown test crashed because running a page script read the app's
settings before checking for a page. Running a script on a web view with no page now does
nothing on every platform.
This commit is contained in:
commit
04603d6ccd
565 changed files with 186167 additions and 14671 deletions
10
.clang-tidy
10
.clang-tidy
|
|
@ -18,7 +18,8 @@ CheckOptions:
|
|||
# Headers that declare a symbol but are not the one to include: per-platform
|
||||
# implementations of wxWidgets and Boost.Thread (a Linux run would suggest the
|
||||
# GTK or pthread one), library internals and forward declarations (MSVC's STL
|
||||
# __msvc_* and the Windows UCRT's corecrt_* included), CPython's headers behind
|
||||
# __msvc_*, the Windows UCRT's corecrt_*, libc++'s __*/ directories and the
|
||||
# macOS SDK's _*.h behind its C headers included), CPython's headers behind
|
||||
# Python.h (python3.x/ on Linux and macOS, libpython/include/ on Windows),
|
||||
# curl's behind curl.h, oneTBB's behind tbb/, and
|
||||
# admesh's stl.h, which the include path also exposes without its directory.
|
||||
|
|
@ -31,7 +32,8 @@ CheckOptions:
|
|||
# The boost/process headers are only included through Utils/BoostProcessCompat.hpp.
|
||||
# FFmpeg's C headers are left alone because they are only included inside
|
||||
# extern "C", which an inserted include would miss. OS-specific headers (GLib,
|
||||
# GTK, D-Bus, POSIX, the Windows SDK) are only used inside platform #if blocks,
|
||||
# GTK, D-Bus, POSIX, the Windows SDK, the macOS SDK's frameworks and MacTypes.h)
|
||||
# are only used inside platform #if blocks,
|
||||
# and an include added at the top of the file would break the other platforms'
|
||||
# builds. A symbol these provide is not reported missing.
|
||||
# Write every / as [/\\] so the patterns also match Windows paths.
|
||||
|
|
@ -46,6 +48,8 @@ CheckOptions:
|
|||
bits[/\\].*;
|
||||
corecrt_.*\.h;
|
||||
__msvc_.*\.hpp;
|
||||
__[a-z0-9_]+[/\\].*;
|
||||
[/\\]_[A-Za-z0-9_]+\.h;
|
||||
boost[/\\]multiprecision[/\\]fwd\.hpp;
|
||||
imconfig\.h;
|
||||
expat_external\.h;
|
||||
|
|
@ -68,6 +72,8 @@ CheckOptions:
|
|||
termios\.h;
|
||||
[/\\](um|shared)[/\\].*;
|
||||
sal\.h;
|
||||
\.framework[/\\].*;
|
||||
MacTypes\.h;
|
||||
tchar\.h;
|
||||
clipper[/\\]clipper\.hpp;
|
||||
png(lib)?conf\.h;
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
# DELEGATION SPECIFICATION: HARNESS-DRIVEN VALIDATION LOOP
|
||||
slug: sketch-focus-arbiter · repo: /home/tommaso/projects/apps/orca_cad · branch: cad-mainline
|
||||
|
||||
## 1. TARGET GOAL
|
||||
|
||||
**Functional Objective.** Keyboard input in the Design tab is routed by WHAT THE KEY IS, not by
|
||||
which widget the window manager decided to focus. Adopted from FreeCAD's
|
||||
`DrawSketchKeyboardManager::detectKeyboardEventHandlingMode`
|
||||
(src/Mod/Sketcher/Gui/DrawSketchKeyboardManager.cpp), which never queries focus at all:
|
||||
|
||||
- digit, `-`, `.`, `,` -> the open value field
|
||||
- Backspace / Delete -> the open value field (when one is open)
|
||||
- Enter / Return / Tab -> commit the field, control returns to the view
|
||||
- a letter -> the sketch-tool shortcut map, as today
|
||||
- Esc -> the existing CadLevel LIFO (DesignInteraction.hpp), unchanged
|
||||
- anything else -> sticky: whoever had it keeps it
|
||||
|
||||
Observable postcondition: for EVERY sketch tool that opens a value field, a value typed
|
||||
immediately after the field appears — with NO click into the field — is the value committed.
|
||||
Today the prefill is committed instead whenever the WM withholds focus.
|
||||
|
||||
**Target Files / Scope (writable).**
|
||||
src/slic3r/GUI/CAD/DesignPanel.cpp (the arbiter lives in the existing wxEVT_CHAR_HOOK)
|
||||
src/slic3r/GUI/CAD/DesignCanvas.cpp/.hpp (forwarding entry points only)
|
||||
src/slic3r/GUI/CAD/SketchInlineEditor.cpp/.hpp (accept a programmatically delivered character)
|
||||
scripts/CAD/check-gui-click-edit.py (F2P oracle — authoring exception, see §4)
|
||||
Everything else read-only. No dependency additions, no reformatting.
|
||||
|
||||
**Open Bindings.**
|
||||
- The in-canvas ImGui field on wip/in-canvas-value-field is NOT in scope. Default: the arbiter
|
||||
is implemented against the CURRENT wxFrame field on cad-mainline, because content-based
|
||||
routing makes the window's focus irrelevant either way. If it later moves in-canvas the
|
||||
arbiter is unchanged.
|
||||
- Tools whose field is opened by a toolbar button rather than a gesture (Constrain path) are
|
||||
covered by the same arbiter but are not in the F2P tool list. Default: assert them in P2P only.
|
||||
|
||||
## 2. HARNESS ENVIRONMENT & GROUND TRUTH
|
||||
|
||||
The rig container `orcacad-gui` on nativedev IS the harness. Xvfb `:11` + openbox, the app under
|
||||
test, `xdotool` for synthetic input, and an MCP socket at `/tmp/mcp.sock` that reports sketch
|
||||
state as JSON. It is a closed loop: drive input, read geometry back, assert. No window manager
|
||||
politics, no human.
|
||||
|
||||
Harness interface (ordered; each slot one invocation, one exit code):
|
||||
S1 sync docker cp <file> orcacad-gui:/OrcaSlicer/<path>
|
||||
S2 build docker exec orcacad-gui ninja -C /OrcaSlicer/build orca-slicer
|
||||
S3 restart docker exec orcacad-gui /OrcaSlicer/scripts/CAD/start-headless-gui.sh
|
||||
S4 F2P docker exec -e DISPLAY=:11 orcacad-gui python3 /tmp/check-gui-click-edit.py --attach
|
||||
S5 P2P docker exec -e DISPLAY=:11 orcacad-gui python3 /tmp/check-gui-sketching.py
|
||||
|
||||
**F2P.** `scripts/CAD/check-gui-click-edit.py`. For each of Line, Rectangle, Circle, Slot,
|
||||
Polygon, Ellipse and Rounded rectangle: arm the tool, draw it, and type a value that differs
|
||||
from the prefill WITHOUT clicking the field. Assert the committed value equals the typed value.
|
||||
The ladder must FAIL against unmodified cad-mainline — that is what proves it asserts something.
|
||||
|
||||
**P2P.** `scripts/CAD/check-gui-sketching.py`, the existing gesture ladder, minus anything red at
|
||||
baseline. NOTE: it calls `focus_field()` — one click into the field before typing — which is the
|
||||
workaround this whole task removes. It stays green as a regression guard; it is NOT evidence.
|
||||
|
||||
**Test Integrity Constraint.** `focus_field()` in check-gui-sketching.py must NOT be deleted to
|
||||
make things pass, and check-gui-click-edit.py must NOT be weakened. Either invalidates the run.
|
||||
|
||||
## 3. VERIFICATION COMMANDS
|
||||
1. Static: `docker exec orcacad-gui ninja -C /OrcaSlicer/build orca-slicer` (warnings delta only;
|
||||
this repo configures no linter — the compiler is the static gate. Absolute-zero is NOT the gate.)
|
||||
2. Harness: `docker exec -e DISPLAY=:11 orcacad-gui python3 /tmp/check-gui-click-edit.py --attach`
|
||||
3. Regression: `docker exec -e DISPLAY=:11 orcacad-gui python3 /tmp/check-gui-sketching.py`
|
||||
|
||||
## 4. CONVERGENCE LOOP — ceiling 8 iterations
|
||||
EDIT (scoped) -> EXECUTE S1..S5 -> PARSE the ladder's per-tool assertions and the [UX]/[KEYTRACE]
|
||||
lines -> PATCH from the parsed cause. On ceiling without convergence: stop, report the last diff
|
||||
and the unresolved failure set. Do not report success.
|
||||
|
||||
F2P authoring exception: check-gui-click-edit.py is writable, and must be shown RED against
|
||||
unmodified source before any source edit counts.
|
||||
|
||||
## 5. TERMINATION CRITERIA
|
||||
- [ ] S2 exits 0, and introduces no compiler warning absent from the baseline.
|
||||
- [ ] S4 ALL_PASSED — every tool commits the typed value, no click into the field.
|
||||
- [ ] S5 shows zero regressions against its recorded baseline pass count.
|
||||
- [ ] F2P proven red without the fix (source stashed, ladder re-run, must FAIL).
|
||||
|
||||
## 6. GUARDRAILS
|
||||
Zero-assumption: no completion claim without captured stdout and exit codes. Oracle supremacy:
|
||||
the ladder's verdict overrides my judgement. Blast radius: §1 files only. Baseline obligation:
|
||||
run §3 once before the first edit and record it.
|
||||
|
|
@ -796,7 +796,12 @@ append_shortcut_item(export_menu, Shortcut::ExportSlicedFile, true, _L("Export p
|
|||
NULL" (`:3438-3445`). `wxEVT_CHILD_FOCUS` derives from `wxCommandEvent` and propagates, and its
|
||||
window is the *direct* child (`:3453-3491`).
|
||||
- `wxPanel::SetFocus` focuses the first child if "the control has at least one child";
|
||||
`SetFocusIgnoringChildren()` focuses the panel itself (`interface/wx/panel.h:125-142`).
|
||||
`SetFocusIgnoringChildren()` focuses the panel itself (`interface/wx/panel.h:125-142`). **[source]**
|
||||
Not while the focus is on the panel or inside it: `wxControlContainerBase::DoSetFocus()` returns at
|
||||
once when `FindFocus()` or one of its parents below the top-level window is the panel, so a panel that
|
||||
holds the focus itself keeps it (`src/common/containr.cpp:110-149`). Otherwise it focuses the child
|
||||
that had the focus last, if it is still shown, else the first child that `CanAcceptFocusFromKeyboard()`
|
||||
(`:605-700`).
|
||||
- `wxGetActiveWindow()` "always returns NULL in the other ports", i.e. on everything but MSW and GTK
|
||||
(`interface/wx/window.h:4545-4551`).
|
||||
|
||||
|
|
@ -811,6 +816,10 @@ append_shortcut_item(export_menu, Shortcut::ExportSlicedFile, true, _L("Export p
|
|||
`MSWEnableHWND`). Any `WM_SETFOCUS`, `WM_KILLFOCUS` or button-down in a window outside
|
||||
`wxCurrentPopupWindow` dismisses a transient popup that lacks `wxPU_CONTAINS_CONTROLS`
|
||||
(`src/msw/window.cpp:3018-3033` → `MSWDismissUnfocusedPopup`, `src/msw/popupwin.cpp:218-229`).
|
||||
- **macOS:** hiding a window that holds the focus moves it to the next view AppKit can focus, which can
|
||||
be a `wxPanel` just shown beside it rather than that panel's control; a `SetFocus()` on that panel then
|
||||
leaves the focus on the panel (see Contract). Seen in `Plater::priv::set_current_panel` on a switch from
|
||||
Prepare to Preview.
|
||||
- **Modeless windows:** focus requested right after `Show()` can be dropped while activation is still
|
||||
in flight (Orca comment in `SpeedDialWebDialog`'s ctor). Set it from `CallAfter` or on
|
||||
`wxEVT_ACTIVATE` (`SpeedDialWebDialog`'s activate handler, see `references/popups-menus.md`); the
|
||||
|
|
@ -846,6 +855,14 @@ append_shortcut_item(export_menu, Shortcut::ExportSlicedFile, true, _L("Export p
|
|||
e.Skip(); });
|
||||
```
|
||||
Cite: `GLCanvas3D::on_mouse`.
|
||||
- **Rule:** To give a view the keyboard, focus its control, not the panel that holds it.
|
||||
**Why:** a panel that holds the focus itself keeps it, and on macOS that is where hiding a focused
|
||||
sibling leaves it, so the view's keys wait until the pointer enters it.
|
||||
```cpp
|
||||
// Wrong: current_panel->SetFocusFromKbd();
|
||||
// Right: get_current_canvas3D()->force_set_focus(); // the shown view's canvas
|
||||
```
|
||||
Cite: `Plater::priv::set_current_panel`.
|
||||
- **Rule:** Defer focus changes out of `wxEVT_KILL_FOCUS`, and always `Skip()` focus events.
|
||||
```cpp
|
||||
// Wrong: ctrl->Bind(wxEVT_KILL_FOCUS, [=](wxFocusEvent&) { other->SetFocus(); });
|
||||
|
|
|
|||
|
|
@ -1242,6 +1242,10 @@ macOS. On MSW it breaks `wxTopLevelWindowMSW::OnActivate`'s focus restore in the
|
|||
- `append_shortcut_item` records the item in `m_shortcut_menu_items`, and `update_shortcut_labels()` rewrites the
|
||||
labels with `SetItemLabel` after the user rebinds a key. Menu text for a registry shortcut always goes through
|
||||
these helpers, never through a hard-coded `"\tCtrl+X"`.
|
||||
- `GetItemLabelText()` drops a key after `"\t"` but keeps one after `" - "`, so on macOS it returns the label with
|
||||
the key text. `MainFrame::menu_item_label()` gives a menu bar item's label without it, from the label the item was
|
||||
made with: the MCP server names menu items by it, so a menu path is the same on every platform. A menu bar item
|
||||
that writes a fixed key after `sep` itself, outside these helpers, records its plain label in `m_key_text_items`.
|
||||
|
||||
**`Plater::PopupMenu(menu, pos)`** (`Plater.cpp`).
|
||||
- It calls `wxGetApp().mainframe->PopupMenu(menu, pos)`. The invoking window is MainFrame, so **`pos` is in
|
||||
|
|
@ -1296,7 +1300,9 @@ wxMenuItem* append_menu_check_item(wxMenu*, int id, const wxString&, const wxStr
|
|||
pass `nullptr`.
|
||||
- A non-null `parent` binds a `wxEVT_UPDATE_UI` handler for that id on `parent` that is never unbound. It calls
|
||||
`enable_menu_item` (`evt.Enable(cb_condition())`), which on macOS also re-applies the icon, grayscale when
|
||||
disabled, on every validation (§14). `append_menu_check_item` binds `Enable` + `Check` the same way.
|
||||
disabled, on every validation (§14). It finds the item by the event's id in the menu that sent the event and
|
||||
keeps no pointer to it: the handler outlives a menu that is destroyed and an item that is removed.
|
||||
`append_menu_check_item` binds `Enable` + `Check` the same way.
|
||||
`append_menu_radio_item` takes no conditions.
|
||||
- Without `parent`, `cb_condition` is ignored: no enable callback is wired.
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ Contents: [Rules](#rules) · [1 Creating and parenting](#1-creating-and-parentin
|
|||
8. A `wxEVT_DESTROY` handler on a parent fires for every descendant: compare `GetEventObject()` and `Skip()`. For a top-level window it runs after the derived destructor — do derived cleanup in the destructor. §3
|
||||
9. Accessors reachable from teardown-time events return `nullptr` instead of dereferencing a pimpl or child; the real fix is still to stop the events first. §3
|
||||
10. Bring a top-level window forward with `if (!w->IsShown()) w->Show(); w->Raise();` — `Raise()` never shows, and a redundant `Show()` is not inert on GTK3. §4
|
||||
11. On macOS, after a native modal (file/dir dialog, native message box) or a generic progress dialog opened from a secondary top-level window, re-raise that window with a deferred, liveness-guarded `Raise()`. §4
|
||||
11. On macOS, after a native modal (file/dir dialog, native message box) or a generic progress dialog opened from a secondary top-level window, re-raise that window with a deferred, liveness-guarded `Raise()`. A dialog that raises the main window itself and must stay in sight meanwhile is a Cocoa child window of it for that span (`keep_window_above`). §4
|
||||
12. Remove style bits with `& ~flag`, never `!flag`. §5
|
||||
13. Always pass the style to a `DPIDialog`: the `DPIAware` default is `wxDEFAULT_FRAME_STYLE` (resizable, min/max boxes). §5, §7
|
||||
14. A `wxFRAME_FLOAT_ON_PARENT` frame takes a non-null top-level parent (parent to `mainframe`, not to a panel). §5
|
||||
|
|
@ -498,16 +498,30 @@ Linux on `wxEVT_SHOW` + `CallAfter`, macOS on `wxEVT_SHOW`.
|
|||
through `EndModal`. The `Raise()` is deferred to run after the modal has fully torn down, and guarded
|
||||
because the dialog may be destroyed while queued.
|
||||
```cpp
|
||||
void PluginsDialog::restore_z_order()
|
||||
void WebViewHostDialog::restore_z_order()
|
||||
{
|
||||
wxGetApp().CallAfter([this, alive = m_alive]() {
|
||||
if (alive->load(std::memory_order_acquire) && IsShown())
|
||||
wxGetApp().CallAfter([this, alive = m_host_alive] {
|
||||
if (alive->load() && IsShown())
|
||||
Raise();
|
||||
});
|
||||
}
|
||||
```
|
||||
Cite: 0a0d59b76b (`PluginsDialog::restore_z_order`; also passed as the `restore` callback of
|
||||
`detail::run_off_thread_with_progress`).
|
||||
A `WebViewHostDialog` subclass calls the inherited `restore_z_order()` after each such modal, on every
|
||||
outcome including Cancel.
|
||||
Cite: 0a0d59b76b (`PluginsDialog`: also passed as the `restore` callback of
|
||||
`detail::run_off_thread_with_progress`); `ActionReplayDialog::open_file`.
|
||||
- **Rule:** On macOS, when a secondary dialog raises the main window on purpose (to give it the keyboard
|
||||
focus for work that acts on it) and must stay in sight meanwhile, attach it as a Cocoa child window of the
|
||||
main window for that span — `keep_window_above(GetHandle(), mainframe->GetHandle(), true)`
|
||||
(`slic3r/Utils/MacDarkMode.hpp`) — and detach it with `false` when the work ends.
|
||||
**Why:** the raised main window becomes key and front and buries the dialog, which wx never attaches to
|
||||
its parent on macOS (§5), while an MSW owner or a GTK `transient_for` parent keeps it above by itself. A
|
||||
child window stays directly above its parent without becoming key, so the main window keeps the focus;
|
||||
it also moves with its parent, so attach it only for the span. wx detaches it on `Hide()` and in the
|
||||
window's destructor (`src/osx/cocoa/nonownedwnd.mm:767-768, 990-991`), so closing the dialog midway
|
||||
needs no extra step.
|
||||
Cite: `ActionReplayDialog::run` (a run's progress and Stop button; the dialog takes the focus back with
|
||||
`restore_z_order()` when the run finishes).
|
||||
- **Rule:** Never position windows by absolute coordinates on Wayland, and never expect `SetIcon` to show on
|
||||
macOS or Wayland.
|
||||
|
||||
|
|
|
|||
10
.github/workflows/build_all.yml
vendored
10
.github/workflows/build_all.yml
vendored
|
|
@ -16,6 +16,7 @@ on:
|
|||
- 'resources/**'
|
||||
- ".github/workflows/build_*.yml"
|
||||
- ".github/workflows/unit_tests*.yml"
|
||||
- ".github/workflows/mcp_sweep.yml"
|
||||
- 'build_linux.sh'
|
||||
- 'build_win.bat'
|
||||
- 'scripts/test_build_win.ps1'
|
||||
|
|
@ -44,6 +45,7 @@ on:
|
|||
- 'version.inc'
|
||||
- ".github/workflows/build_*.yml"
|
||||
- ".github/workflows/unit_tests*.yml"
|
||||
- ".github/workflows/mcp_sweep.yml"
|
||||
- 'build_linux.sh'
|
||||
- 'build_win.bat'
|
||||
- 'scripts/test_build_win.ps1'
|
||||
|
|
@ -252,6 +254,14 @@ jobs:
|
|||
os: ${{ vars.SELF_HOSTED && 'orca-macos-arm64' || 'macos-15' }}
|
||||
artifact: ${{ github.sha }}-tests-macos-arm64
|
||||
test-dir: build/arm64/tests
|
||||
# Drive the x86_64 AppImage's GUI through every MCP sweep test on Xvfb.
|
||||
# GitHub-hosted only, as the job installs Xvfb, Openbox and the AppImage's
|
||||
# host libraries with apt.
|
||||
mcp_sweep_linux_x86_64:
|
||||
name: Linux x86_64
|
||||
needs: build_linux
|
||||
if: ${{ !cancelled() && success() && !inputs.build-deps-only && !vars.SELF_HOSTED }}
|
||||
uses: ./.github/workflows/mcp_sweep.yml
|
||||
# Slice a two-colour cube through every shipped printer, and through every
|
||||
# system process/filament whose templates no printer's own slice reaches, so
|
||||
# every custom g-code and filename_format shipped is expanded (names in {if}
|
||||
|
|
|
|||
8
.github/workflows/build_flatpak.yml
vendored
8
.github/workflows/build_flatpak.yml
vendored
|
|
@ -224,11 +224,13 @@ jobs:
|
|||
# the bounds checks are compiled in, so a stripped exe still catches them.
|
||||
find "$d/build_flatpak/tests" -type f -perm -u+x -exec strip --strip-unneeded {} + 2>/dev/null || true
|
||||
# At runtime the tests read tests/ (TEST_DATA_DIR), scripts/, and under
|
||||
# resources/ the shipped profiles (PROFILES_DIR), the printers/ maps, and
|
||||
# the icon SVGs (NativeCommands icon names are checked against them).
|
||||
# resources/ the shipped profiles (PROFILES_DIR), the printers/ maps,
|
||||
# the icon SVGs (NativeCommands icon names are checked against them), and
|
||||
# the MCP server's page agent (web/mcp).
|
||||
find "$d" -mindepth 1 -maxdepth 1 -type d \
|
||||
! -name tests ! -name build_flatpak ! -name scripts ! -name resources -exec rm -rf {} +
|
||||
find "$d/resources" -mindepth 1 -maxdepth 1 ! -name profiles ! -name printers ! -name images -exec rm -rf {} +
|
||||
find "$d/resources" -mindepth 1 -maxdepth 1 ! -name profiles ! -name printers ! -name images ! -name web -exec rm -rf {} +
|
||||
find "$d/resources/web" -mindepth 1 -maxdepth 1 ! -name mcp -exec rm -rf {} +
|
||||
# Only the SVGs are read; the png/ico/icns/gif assets are ~35MB of dead weight.
|
||||
find "$d/resources/images" -mindepth 1 -maxdepth 1 ! -name '*.svg' -exec rm -rf {} + 2>/dev/null || true
|
||||
tar -cf flatpak-test-asset.tar flatpak_app "$d"
|
||||
|
|
|
|||
1
.github/workflows/build_optional.yml
vendored
1
.github/workflows/build_optional.yml
vendored
|
|
@ -44,6 +44,7 @@ on:
|
|||
- 'version.inc'
|
||||
- ".github/workflows/build_*.yml"
|
||||
- ".github/workflows/unit_tests*.yml"
|
||||
- ".github/workflows/mcp_sweep.yml"
|
||||
- 'build_linux.sh'
|
||||
- 'build_win.bat'
|
||||
- 'scripts/test_build_win.ps1'
|
||||
|
|
|
|||
37
.github/workflows/check_cad_offer_table.yml
vendored
Normal file
37
.github/workflows/check_cad_offer_table.yml
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
name: Check CAD offer table
|
||||
|
||||
# src/slic3r/GUI/CAD/DesignOffer.hpp is generated from scripts/CAD/tool_atlas.json and must never be
|
||||
# edited by hand. This fails when the checked-in header is not what the generator makes of the atlas, and
|
||||
# when the generator's checks of an atlas (scripts/CAD/test_gen_offer_table.py) miss a fault.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'scripts/CAD/tool_atlas.json'
|
||||
- 'scripts/CAD/gen_offer_table.py'
|
||||
- 'scripts/CAD/test_gen_offer_table.py'
|
||||
- 'src/slic3r/GUI/CAD/DesignOffer.hpp'
|
||||
- '.github/workflows/check_cad_offer_table.yml'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'scripts/CAD/tool_atlas.json'
|
||||
- 'scripts/CAD/gen_offer_table.py'
|
||||
- 'scripts/CAD/test_gen_offer_table.py'
|
||||
- 'src/slic3r/GUI/CAD/DesignOffer.hpp'
|
||||
- '.github/workflows/check_cad_offer_table.yml'
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
check_cad_offer_table:
|
||||
name: Check CAD offer table
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Check the offer table against the atlas
|
||||
run: python3 scripts/CAD/gen_offer_table.py --check
|
||||
|
||||
- name: Test the generator's checks of the atlas
|
||||
run: python3 scripts/CAD/test_gen_offer_table.py
|
||||
107
.github/workflows/mcp_sweep.yml
vendored
Normal file
107
.github/workflows/mcp_sweep.yml
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
name: MCP Sweep
|
||||
|
||||
# Run the MCP sweep (tools/mcp/run_sweep.py) against the x86_64 Linux AppImage
|
||||
# the calling build_all.yml run built, each job's app on a private Xvfb display
|
||||
# with Openbox as its window manager. Called once from build_all.yml.
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
mcp_sweep:
|
||||
# Static "MCP Sweep"; the caller's job name adds the arch, as for the unit tests.
|
||||
name: MCP Sweep
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 150
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
# The app comes from the AppImage. The tests read tools/mcp, the test
|
||||
# data in tests/, the handy models and profiles in resources/, and
|
||||
# scripts/CAD.
|
||||
sparse-checkout: |
|
||||
tools
|
||||
tests
|
||||
resources
|
||||
scripts
|
||||
|
||||
- name: Download the AppImage
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
# <ver> is V<version> or PR-<number>, so this leaves out the aarch64
|
||||
# build's OrcaSlicer_Linux_ubuntu_2404_aarch64_<ver>.
|
||||
pattern: OrcaSlicer_Linux_ubuntu_2404_{V,PR-}*
|
||||
path: ${{ runner.temp }}/appimage
|
||||
|
||||
- name: Extract the AppImage
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mapfile -t found < <(find appimage -name '*.AppImage')
|
||||
[ ${#found[@]} -eq 1 ] || { echo "expected one x86_64 AppImage, found: ${found[*]:-none}" >&2; exit 1; }
|
||||
chmod +x "${found[0]}"
|
||||
"${found[0]}" --appimage-extract > /dev/null
|
||||
# The bare binary cannot find the AppImage's bundled libraries; AppRun
|
||||
# sets them up and execs it, so the pid, exit codes and signals the
|
||||
# sweep reads are the app's own.
|
||||
[ -x squashfs-root/AppRun ] || { echo "no AppRun in the AppImage" >&2; exit 1; }
|
||||
echo "ORCA_BIN=$PWD/squashfs-root/AppRun" >> "$GITHUB_ENV"
|
||||
|
||||
# Openbox keeps popup lists open under Xvfb, which test_gui_tools.py and
|
||||
# test_filaments.py need; ffmpeg lets test_recording.py encode. The rest
|
||||
# are the host libraries the AppImage leaves out (scripts/appimage_lib_policy.sh),
|
||||
# with Mesa's software OpenGL for Xvfb.
|
||||
- name: Install Xvfb, Openbox and the AppImage's host runtime
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
xvfb openbox ffmpeg dbus \
|
||||
libopengl0 libgl1 libegl1 libgl1-mesa-dri libwebkit2gtk-4.1-0
|
||||
|
||||
# WebKitGTK runs its web processes in a bubblewrap sandbox, which needs
|
||||
# unprivileged user namespaces, and Ubuntu 24.04's AppArmor denies them.
|
||||
# The runner is discarded after the job.
|
||||
- name: Allow unprivileged user namespaces
|
||||
run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
|
||||
- name: Run the sweep
|
||||
id: sweep
|
||||
# Short of the job's limit, so the steps after it still run.
|
||||
timeout-minutes: 120
|
||||
run: |
|
||||
set -o pipefail
|
||||
# One session bus for the run's apps, as a desktop session gives them.
|
||||
# -j defaults to half the cores: 2 on this 4-vCPU runner, which also
|
||||
# draws every app's OpenGL in software.
|
||||
dbus-run-session -- python3 tools/mcp/run_sweep.py --xvfb --bin "$ORCA_BIN" \
|
||||
--out "$RUNNER_TEMP/mcp-sweep" \
|
||||
2>&1 | tee "$RUNNER_TEMP/mcp-sweep.log"
|
||||
|
||||
- name: Publish job summary
|
||||
if: ${{ !cancelled() && steps.sweep.outcome != 'skipped' }}
|
||||
run: |
|
||||
{
|
||||
echo "## MCP sweep"
|
||||
echo '```'
|
||||
# Each failed run, beside the others and then alone, the failures'
|
||||
# logs, any crash report, and the closing count
|
||||
grep -E "^[^ ]+ +(FAIL \(|passed alone)|^FAIL |^crash report: | passed \(.* alone\)" \
|
||||
"$RUNNER_TEMP/mcp-sweep.log" || echo "no result lines, see the log"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# A failed run keeps each failed test's folder (test.log and a copy of the
|
||||
# app's log), the data folders of the jobs it failed on, and results.jsonl.
|
||||
- name: Upload the failed runs
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: mcp-sweep-linux-x86_64
|
||||
path: |
|
||||
${{ runner.temp }}/mcp-sweep
|
||||
${{ runner.temp }}/mcp-sweep.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -55,3 +55,5 @@ __pycache__/
|
|||
/.test/
|
||||
docs/superpowers/
|
||||
ctest_results.xml
|
||||
.superpowers/
|
||||
docs/sf-plan/
|
||||
|
|
|
|||
|
|
@ -27,6 +27,10 @@ ctest --test-dir ./tests/libslic3r -C Release # individual suite
|
|||
ctest --test-dir ./tests/fff_print -C Release
|
||||
```
|
||||
|
||||
To run the app and see or drive it (reproduce an issue, capture before/after screenshots, script GUI steps), use its MCP server: [tools/mcp/README.md](tools/mcp/README.md) launches it and drives it from a shell, Python or a replayable script, and the design is in [docs/HLSD/mcp-server.md](docs/HLSD/mcp-server.md).
|
||||
|
||||
The MCP sweep's tests (`tools/mcp/run_sweep.py`) are designed top down: [tools/mcp/TESTS.md](tools/mcp/TESTS.md) holds the rules and the index, and each area's entries are in `tools/mcp/test-entries/`. Before writing or changing a test, add or update its entry (what it tests, the checks that decide it, what it leaves out) and have the entry reviewed. Keep the entry in step with the test.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Docs live in `docs/`; the high-level design of a subsystem goes in `docs/HLSD/<subsystem>.md`.
|
||||
|
|
|
|||
2
deps/wxWidgets/wxWidgets.cmake
vendored
2
deps/wxWidgets/wxWidgets.cmake
vendored
|
|
@ -44,7 +44,7 @@ endif ()
|
|||
orcaslicer_add_cmake_project(
|
||||
wxWidgets
|
||||
GIT_REPOSITORY "https://github.com/OrcaSlicer/Orca-deps-wxWidgets"
|
||||
GIT_TAG b44c39c100975a0ac0e46f937aa3f3eae5e18631
|
||||
GIT_TAG 89844cb1f80b17a5916d5274cd88317cac3e2a3c
|
||||
# A shallow clone fetches only the branch head, so checking out a pinned commit fails once the
|
||||
# branch moves past it.
|
||||
GIT_SHALLOW OFF
|
||||
|
|
|
|||
|
|
@ -14,6 +14,10 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
// OrcaSlicer: let automation (the MCP server) record items through the test-engine hooks, which
|
||||
// ImGuiWrapper implements. ImGui calls them only while ImGuiContext::TestEngineHookItems is set.
|
||||
#define IMGUI_ENABLE_TEST_ENGINE
|
||||
|
||||
//---- Define assertion handler. Defaults to calling assert().
|
||||
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
|
||||
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
|
||||
|
|
|
|||
|
|
@ -759,7 +759,8 @@ enum ImGuiItemStatusFlags_
|
|||
ImGuiItemStatusFlags_Openable = 1 << 20, //
|
||||
ImGuiItemStatusFlags_Opened = 1 << 21, //
|
||||
ImGuiItemStatusFlags_Checkable = 1 << 22, //
|
||||
ImGuiItemStatusFlags_Checked = 1 << 23 //
|
||||
ImGuiItemStatusFlags_Checked = 1 << 23, //
|
||||
ImGuiItemStatusFlags_Inputable = 1 << 24 // [OrcaSlicer, as upstream] Takes typed input (a slider or drag without ImGuiSliderFlags_NoInput, an input field)
|
||||
#endif
|
||||
};
|
||||
|
||||
|
|
@ -2666,17 +2667,25 @@ extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id,
|
|||
extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id);
|
||||
extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id, const void* data_id_end);
|
||||
extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...);
|
||||
// OrcaSlicer: what a field shows and what kind of widget it is ("slider", "drag", "input", "multiline", "combo"), and the
|
||||
// text TextEx() draws, for automation; upstream's test engine reads these by other means.
|
||||
extern void ImGuiTestEngineHook_ItemValue(ImGuiContext* ctx, ImGuiID id, const char* kind, const char* value, ImGuiItemStatusFlags flags);
|
||||
extern void ImGuiTestEngineHook_Text(ImGuiContext* ctx, const ImRect& bb, const char* text, const char* text_end);
|
||||
#define IMGUI_TEST_ENGINE_ITEM_VALUE(_ID,_KIND,_VALUE,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemValue(&g, _ID, _KIND, _VALUE, _FLAGS)
|
||||
#define IMGUI_TEST_ENGINE_TEXT(_BB,_TEXT,_TEXT_END) if (g.TestEngineHookItems) ImGuiTestEngineHook_Text(&g, _BB, _TEXT, _TEXT_END)
|
||||
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box
|
||||
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional)
|
||||
#define IMGUI_TEST_ENGINE_LOG(_FMT,...) if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log
|
||||
#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA));
|
||||
#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2));
|
||||
#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookItems || g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2));
|
||||
#else
|
||||
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_LOG(_FMT,...) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_ITEM_VALUE(_ID,_KIND,_VALUE,_FLAGS) do { } while (0)
|
||||
#define IMGUI_TEST_ENGINE_TEXT(_BB,_TEXT,_TEXT_END) do { } while (0)
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -234,6 +234,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
|
|||
|
||||
ImRect bb(text_pos, text_pos + text_size);
|
||||
ItemSize(text_size, 0.0f);
|
||||
IMGUI_TEST_ENGINE_TEXT(bb, text_begin, text_end);
|
||||
ItemAdd(bb, 0);
|
||||
}
|
||||
else
|
||||
|
|
@ -243,6 +244,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
|
|||
|
||||
ImRect bb(text_pos, text_pos + text_size);
|
||||
ItemSize(text_size, 0.0f);
|
||||
IMGUI_TEST_ENGINE_TEXT(bb, text_begin, text_end);
|
||||
if (!ItemAdd(bb, 0))
|
||||
return;
|
||||
|
||||
|
|
@ -837,6 +839,10 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiBut
|
|||
bool hovered, held;
|
||||
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
|
||||
|
||||
#ifdef IMGUI_ENABLE_TEST_ENGINE
|
||||
ImGuiContext& g = *GImGui;
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, window->DC.LastItemStatusFlags);
|
||||
#endif
|
||||
return pressed;
|
||||
}
|
||||
|
||||
|
|
@ -1329,6 +1335,7 @@ bool ImGui::ImageTextButton(const ImVec2& button_size, const char* text, ImTextu
|
|||
|
||||
bool hovered, held;
|
||||
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, text, window->DC.LastItemStatusFlags);
|
||||
|
||||
// Render
|
||||
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
|
||||
|
|
@ -1556,7 +1563,8 @@ bool ImGui::RadioButton(const char* label, bool active)
|
|||
if (label_size.x > 0.0f)
|
||||
RenderText(label_pos, label);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Checkable | (active ? ImGuiItemStatusFlags_Checked : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "radio", "", 0);
|
||||
return pressed;
|
||||
}
|
||||
|
||||
|
|
@ -1603,7 +1611,8 @@ bool ImGui::BBLRadioButton(const char *label, bool active)
|
|||
if (g.LogEnabled) LogRenderedText(&label_pos, active ? "(x)" : "( )");
|
||||
if (label_size.x > 0.0f) RenderText(label_pos, label);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Checkable | (active ? ImGuiItemStatusFlags_Checked : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "radio", "", 0);
|
||||
return pressed;
|
||||
}
|
||||
|
||||
|
|
@ -2052,6 +2061,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF
|
|||
popup_open = true;
|
||||
}
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Openable | (popup_open ? ImGuiItemStatusFlags_Opened : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "combo", preview_value, 0);
|
||||
if (!popup_open)
|
||||
return false;
|
||||
|
||||
|
|
@ -2168,6 +2179,8 @@ bool ImGui::BBLBeginCombo(const char *label, const char *preview_value, ImGuiCom
|
|||
popup_open = true;
|
||||
}
|
||||
if (push_color_count > 0) { ImGui::PopStyleColor(push_color_count); }
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | ImGuiItemStatusFlags_Openable | (popup_open ? ImGuiItemStatusFlags_Opened : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "combo", preview_value, 0);
|
||||
if (!popup_open) return false;
|
||||
|
||||
if (has_window_size_constraint) {
|
||||
|
|
@ -2933,7 +2946,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data,
|
|||
if (label_size.x > 0.0f)
|
||||
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "drag", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0);
|
||||
return value_changed;
|
||||
}
|
||||
|
||||
|
|
@ -3019,7 +3033,8 @@ bool ImGui::BBLDragScalar(const char *label, ImGuiDataType data_type, void *p_da
|
|||
if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
|
||||
if (push_color_count) { ImGui::PopStyleColor(1); }
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "drag", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0);
|
||||
return value_changed;
|
||||
}
|
||||
|
||||
|
|
@ -3643,7 +3658,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
|
|||
if (label_size.x > 0.0f)
|
||||
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0);
|
||||
return value_changed;
|
||||
}
|
||||
|
||||
|
|
@ -3719,7 +3735,8 @@ bool ImGui::BBLSliderScalarIn(const char *label, ImGuiDataType data_type, void *
|
|||
float value_size = CalcTextSize(value_buf).x;
|
||||
RenderTextClipped(ImVec2(frame_bb.Min.x + end_x,frame_bb.Min.y),ImVec2(frame_bb.Max.x + value_size,frame_bb.Max.y), value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0);
|
||||
return value_changed;
|
||||
}
|
||||
|
||||
|
|
@ -3833,7 +3850,15 @@ bool ImGui::BBLSliderScalar(const char *label, ImGuiDataType data_type, void *p_
|
|||
|
||||
if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
|
||||
#ifdef IMGUI_ENABLE_TEST_ENGINE
|
||||
if (g.TestEngineHookItems)
|
||||
{
|
||||
char value_buf[64];
|
||||
DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, "slider", value_buf, temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0);
|
||||
}
|
||||
#endif
|
||||
return value_changed;
|
||||
}
|
||||
|
||||
|
|
@ -5564,7 +5589,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_
|
|||
if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited))
|
||||
MarkItemEdited(id);
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags | (is_readonly ? 0 : ImGuiItemStatusFlags_Inputable));
|
||||
IMGUI_TEST_ENGINE_ITEM_VALUE(id, is_multiline ? "multiline" : "input", is_password ? "" : buf, is_readonly ? 0 : ImGuiItemStatusFlags_Inputable);
|
||||
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
|
||||
return enter_pressed;
|
||||
else
|
||||
|
|
@ -7219,7 +7245,7 @@ bool ImGui::BBLImageSelectable(ImTextureID user_texture_id, const ImVec2& size_a
|
|||
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(g.CurrentItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
|
||||
CloseCurrentPopup();
|
||||
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
|
||||
IMGUI_TEST_ENGINE_ITEM_INFO(id, NULL, window->DC.LastItemStatusFlags);
|
||||
|
||||
return pressed;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -300,14 +300,14 @@ failure; so is a tool that eats the press and silently kills orbit.
|
|||
A tool that mutates nothing, has no commit, and cannot fail — and therefore has no home in this
|
||||
codebase. Current state, verified:
|
||||
|
||||
- Offer row `{"measure", "Measure", 6, …}` (`DesignOffer.hpp:120`) has `action == nullptr` and
|
||||
- Offer row `{"design_measure", "Measure", 6, …}` (`DesignOffer.hpp:120`) has `action == nullptr` and
|
||||
`refusal == nullptr`. The table's own contract (`DesignOffer.hpp:43-48`) is *"nullptr → kernel
|
||||
support exists, no GUI path yet (row shows disabled)"*, so the row renders as
|
||||
**"Measure (no GUI route)"** and is permanently disabled (`DesignPanel.cpp:6519`). With no
|
||||
refusal in the row, it contributes nothing to the family's "why" line either.
|
||||
- The maths exists, for MCP callers only: `resolve_ref` + `measure` (`McpControl.cpp:522`, `:546`)
|
||||
— refs `{face|edge|point}`, distance = `|pa - pb|` of **representative points** (face centroid,
|
||||
edge mid-sample), angle = `acos(da·db)` when both refs carry a direction.
|
||||
- The maths exists, for MCP callers only: the `design_measure` CAD tool (`cad_measure` in
|
||||
`Mcp/Tools/DesignInspectTools.cpp`) — refs `{face|edge|point}`, distance = `|pa - pb|` of **representative
|
||||
points** (face centroid, edge mid-sample), angle = `acos(da·db)` when both refs carry a direction.
|
||||
- The correct OCCT primitive is already linked and already used: `BRepExtrema_DistShapeShape`
|
||||
(`GeometryEngine.cpp:31`, `:457`).
|
||||
- The Prepare tab ships a full measure gizmo — `GLGizmoMeasure` (`src/slic3r/GUI/Gizmos/`) over
|
||||
|
|
@ -383,7 +383,7 @@ the same label primitive the dimension chain already draws (`render_dimensioning
|
|||
| `Esc` | `TwoRefs→OneRef→Exit` | ladder routes it | — | the ladder already handles "tool armed" |
|
||||
| any key | — | swallowed while the field is open | — | a query tool must not steal letters: no tool keys while Measure is armed |
|
||||
| `MiddleDrag`/`RightDrag` | — | — | orbit/pan | a 3D measurement is unreadable from one angle; the camera must stay live *inside* the tool, exactly like Select |
|
||||
| MCP `measure` | same engine | — | — | the RPC becomes one caller of `measure_refs`, so the agent surface and the GUI cannot disagree |
|
||||
| MCP `design_measure` | same engine | — | — | the RPC becomes one caller of `measure_refs`, so the agent surface and the GUI cannot disagree |
|
||||
|
||||
### 9.10 Measure — three friction points, and how the architecture prevents them
|
||||
|
||||
|
|
@ -409,7 +409,7 @@ lambda happened to be built rather than by anything the user can see.
|
|||
|
||||
### 10.1 The architectural claim: there are two Dimension tools, and they disagree
|
||||
|
||||
| | click-to-place (`Mode::Dimension`) | selection-based (the `sk_dimension` row) |
|
||||
| | click-to-place (`Mode::Dimension`) | selection-based (the `sketch_dimension` row) |
|
||||
|---|---|---|
|
||||
| entry | arm the tool, pick in the viewport (`:10651`) | select first, then apply (`DesignCanvas.cpp:1417-1430`) |
|
||||
| kinds it can make | Length, Diameter, Radius, Distance, DistanceToLine | **also Angle between two lines** |
|
||||
|
|
@ -437,14 +437,17 @@ cleared anyway (`:10689-10699`); abort a value field and the placed dimension **
|
|||
its measured value (`cancel_dimension_value`, `:2174` — deliberate, but it means a cancelled
|
||||
gesture has already added a constraint, and nothing says so).
|
||||
|
||||
**`apply_dimension` records a poison value.** Its per-case thresholds move nothing for
|
||||
`v <= 0` (Length/Diameter/Radius, `:611-613`) or `v < 0` (Distance/DistanceToLine, `:622`, `:639`) —
|
||||
and then `record_dimension_constraint(v)` runs **unconditionally** (`:659`). The file's own sibling
|
||||
says it best, at the socket boundary: *"a negative/zero/NaN value that moved nothing would still be
|
||||
pushed to the solver as a constraint it must satisfy and cannot, silently corrupting the sketch
|
||||
rather than failing. (`apply_dimension` has the same flaw for any other caller; this guard protects
|
||||
the socket, not the tool.)"* (`McpControl.cpp:1572-1577`). So the agent surface validates and the GUI
|
||||
does not — the GUI is the less safe caller of its own function.
|
||||
**`apply_dimension` refuses an out-of-range value before it records anything.** Its per-case
|
||||
thresholds move nothing for `v <= 0` (Length/Diameter/Radius, `:611-613`) or `v < 0`
|
||||
(Distance/DistanceToLine, `:622`, `:639`), and `record_dimension_constraint(v)` after them runs
|
||||
**unconditionally** (`:659`): a negative, zero or NaN value that moved nothing would be pushed to the
|
||||
solver as a constraint it must satisfy and cannot, silently corrupting the sketch. So a guard at the
|
||||
top of `apply_dimension` refuses a value that is not finite, not above zero for a length, radius or
|
||||
diameter, or negative for a distance, and says why on the status line, before it moves or records
|
||||
anything. The `sketch_set_value` CAD tool (`Mcp/Tools/DesignSketchTools.cpp`) checks the same rule, and refuses a
|
||||
selection with nothing to dimension, before it calls `apply_dimension`, so that its call fails with
|
||||
the reason rather than reporting a value the sketch tool refused only on its status line. The GUI
|
||||
and the agent surface are equally safe callers of the function.
|
||||
|
||||
**`record_dimension_constraint` never dedupes at all.** It `push_back`s unconditionally
|
||||
(`:674`, `:684`, `:691`, `:700`), so applying the selection-path dimension twice leaves **two**
|
||||
|
|
@ -523,11 +526,12 @@ Three rules the type enforces, each closing a defect above:
|
|||
contradiction you can see. `drive == Reference` renders `measured` only, and the palette is the
|
||||
one already in the tab (green quote = measured, driving colour = driven).
|
||||
2. **`apply(value)` returns a `WriteOutcome`** (`Ok | ClampedTo | Refused`, the base-operator type
|
||||
from §0.2) — the same type for the solver path, the geometric path and the socket. The socket
|
||||
guard already written in `McpControl.cpp:1572-1577` moves *into* `apply`, so the GUI cannot be the
|
||||
unsafe caller of its own function any more. `Refused` keeps the field open with the typed text
|
||||
and the reason, which is also what makes the `Coincident`-flip reversible: the dimension keeps
|
||||
its `type` and only its value changes.
|
||||
from §0.2) — the same type for the solver path, the geometric path and the MCP server. The
|
||||
range guard `apply_dimension` runs becomes `apply`'s `Refused`, so every caller learns of a
|
||||
refusal from the result rather than from the status line, and `sketch_set_value` in
|
||||
`Mcp/Tools/DesignSketchTools.cpp` keeps no copy of the check. `Refused` keeps the field open with the typed
|
||||
text and the reason, which is also what makes the `Coincident`-flip reversible: the dimension
|
||||
keeps its `type` and only its value changes.
|
||||
3. **One dimension per (type, operand pair) lives in one `std::vector<Dimension>`**, and the
|
||||
constraint slot is a *projection* of it (`upsert` semantics from `:1074-1130`, kept). The click
|
||||
path and the selection path both become thin callers of one `Dimension` builder, so the operand
|
||||
|
|
@ -611,7 +615,7 @@ Constrain session on a *committed* sketch reports "sketching", and the panel has
|
|||
property of a sketch; the mode is a way of editing one.
|
||||
|
||||
Constraints are also the last large block of verbs living outside the offer. The offer has 92 rows
|
||||
(`DesignOffer.hpp`) and the whole constraint vocabulary is **one** of them (`sk_constrain`, `:168`);
|
||||
(`DesignOffer.hpp`) and the whole constraint vocabulary is **one** of them (`sketch_constrain`);
|
||||
the other 20 are toolbar buttons (`DesignPanel.cpp:1516-1539`). Five enum members have no button at
|
||||
all: `Distance` comes from the Dimension tool, `LockX`/`LockY` have solver bindings
|
||||
(`SketchSolver.cpp:191`, `:240`, `:245`) and only a label (`DesignPanel.cpp:8051`), `PointOnLine` is produced only as
|
||||
|
|
@ -1018,18 +1022,27 @@ corner drag solves the offset so that the *opposite* corner stays put (`:7690-77
|
|||
### 14.2 Verified current behaviour: the constraint table, read in the right direction
|
||||
|
||||
`confirm_transform` (`:8342-8445`) `remove_if`s — **returning true means REMOVED** — over every
|
||||
constraint that touches a target (`is_target` checks `ea`, `eb` and `ec`):
|
||||
constraint that touches a target (`is_target` checks `ea`, `eb` and `ec`).
|
||||
|
||||
A constraint whose every operand is a target moved with them under the one map, so it is kept unless
|
||||
it measures against the sketch's fixed frame or, under Scale, a size: `Fix`, `LockX`, `LockY` and
|
||||
`SymmetricAboutX/Y` are removed by every map, Horizontal and Vertical by Rotate, `DistanceX/Y` by
|
||||
Rotate and Scale, `Distance`, Radius and Diameter by Scale, and a `PointOnLine` with an offset by
|
||||
Scale. A rectangle moved, turned or scaled whole keeps its corners joined.
|
||||
|
||||
A constraint that reaches past the targets — to an entity left where it was, or to the origin or an
|
||||
axis — is judged by its class:
|
||||
|
||||
| Mode | Removed | Kept |
|
||||
|---|---|---|
|
||||
| Move | Coincident, PointOnLine, PointOnObject, Concentric, Symmetric, Midpoint, **Fix, LockX, LockY**, cross-entity `Distance` | Horizontal, Vertical, Parallel, Perpendicular, Angle, EqualLength, Radius, Diameter, Collinear, **self**-`Distance` |
|
||||
| Rotate | everything else — Coincident, Concentric, Tangent, Parallel, Perpendicular, Midpoint, Symmetric, PointOnLine/Object, Horizontal, Vertical, Angle, Fix, Lock | EqualLength, Radius, Diameter, self-`Distance` |
|
||||
| Move | Coincident, PointOnLine, PointOnObject, Concentric, Symmetric, Midpoint, **Fix, LockX, LockY**, `Distance` | Horizontal, Vertical, Parallel, Perpendicular, Angle, EqualLength, Radius, Diameter, Collinear |
|
||||
| Rotate | everything else — Coincident, Concentric, Tangent, Parallel, Perpendicular, Midpoint, Symmetric, PointOnLine/Object, Horizontal, Vertical, Angle, `Distance`, Fix, Lock | EqualLength, Radius, Diameter |
|
||||
| Scale | everything except the five orientation types | Horizontal, Vertical, Parallel, Perpendicular, Angle |
|
||||
| Array / PolarArray | additive: copies are appended and bound to their source through a ladder — lines get Parallel+EqualLength (linear) or EqualLength alone (polar), arcs/circles a per-copy Radius plus Concentric when the polar pivot *is* the source's centre | the originals are untouched |
|
||||
|
||||
Then `resolve_live()`. The rationale in the comment is real — *"Surviving classes are satisfied by
|
||||
construction; the re-solve folds in the new placement"* — and the array ladder is the same
|
||||
degrade-and-keep-the-first-set pattern as Batch 13's fillet, which is the right instinct.
|
||||
Then `resolve_live()`. What is kept holds by construction, so the re-solve moves nothing, and the
|
||||
array ladder is the same degrade-and-keep-the-first-set pattern as Batch 13's fillet, which is the
|
||||
right instinct.
|
||||
|
||||
### 14.3 The defects
|
||||
|
||||
|
|
@ -1039,15 +1052,10 @@ degrade-and-keep-the-first-set pattern as Batch 13's fillet, which is the right
|
|||
`reset_tf(); // drop any in-progress transform gizmo` (`:295`). So arming Line with a pending
|
||||
fillet keeps the fillet, and arming Line with a pending rotation **throws the rotation away** —
|
||||
targets picked, value dialled or typed, ghost visible. Same gesture, opposite outcome, no message.
|
||||
2. **The keep/drop table over-removes, silently.** For every mode there are constraint types the map
|
||||
provably preserves that are removed anyway: Move removes Coincident/PointOnLine/PointOnObject even
|
||||
when *all* their operands are targets (a rigid translation of a whole loop preserves them); Rotate
|
||||
removes Coincident, Concentric, Tangent, Parallel, Perpendicular, Midpoint, Symmetric and
|
||||
PointOnObject although a rotation preserves all of them; Scale removes Coincident, Tangent,
|
||||
Midpoint, Symmetric, PointOnLine, PointOnObject and EqualLength although a uniform scale preserves
|
||||
them (and it keeps Horizontal/Vertical, which only a *non-uniform* scale would break — Scale here
|
||||
is uniform, so that half is right). The user sees badges vanish and the DoF readout climb, while the
|
||||
geometry — which *is* correctly mapped — looks fine, so the loss stays invisible until a later edit.
|
||||
2. **The class table keeps some relations a move breaks.** For a constraint reaching past the
|
||||
targets, Move keeps Tangent, Collinear, `DistanceX/Y` and `SymmetricAboutX/Y`, although translating one end
|
||||
of them carries it away from the other; the re-solve then pulls the moved geometry back toward
|
||||
the relation, undoing part of the move.
|
||||
3. **Move releases an explicit anchor.** `Fix`, `LockX` and `LockY` are removed by a translation. A
|
||||
point the user pinned to protect it can be moved, and the protection silently disappears. Either the
|
||||
map should obey the anchor (refuse, or carry it) or the release must be reported.
|
||||
|
|
@ -1135,10 +1143,10 @@ degrade-and-keep-the-first-set pattern as Batch 13's fillet, which is the right
|
|||
none of them these), so the family is reachable only from the offer. Either assign keys from the free
|
||||
letters (G I J K N Q U V W Y Z — K is already Constrain) or state that the family is deliberately
|
||||
offer-only: `snaporca-fqwu` counts 47 of 86 verbs with no shortcut, and this is a sixth of them.
|
||||
- **Batch 14 — derive the keep/drop table, do not maintain it.** `confirm_transform :8357-8387` is a
|
||||
hand-written per-type switch that over-removes in all three mutating modes; for each `(type, map)`
|
||||
pair the answer is a property of the map (does it preserve the relation?), with the genuine
|
||||
exceptions (`Fix`/`Lock`, an absolute `Angle`) named as exceptions.
|
||||
- **Batch 14 — derive the keep/drop table, do not maintain it.** For a constraint reaching past the
|
||||
targets, `confirm_transform` is a hand-written per-type switch, and its Move column keeps relations
|
||||
a translation breaks (14.3, 2); whether one end moving away from the other breaks a relation is a
|
||||
property of the map, with the genuine exceptions (`Fix`/`Lock`) named as exceptions.
|
||||
- **Phase 2 (3D) needs its batch list written before it starts** — otherwise it will be designed by
|
||||
whoever opens the file first.
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ Its coupling to the rest of the application is deliberately narrow. It adds no s
|
|||
slicing pipeline and touches neither the preset system nor `Tab`. It reaches the rest of Orca
|
||||
in two places: **Commit to Plate**, which hands finished solids to Prepare as ordinary model
|
||||
objects (by default one assembly object with a part per body, which keeps the bodies' relative
|
||||
placement, or one object per body), and one optional 3MF archive entry that carries the recipe.
|
||||
placement, or one object per body) in one Prepare undo step, named after the bodies the user
|
||||
named, and one optional 3MF archive entry that carries the recipe.
|
||||
Everything else is contained in `src/libslic3r/CAD/` and `src/slic3r/GUI/CAD/`.
|
||||
|
||||
The user-facing manual lives in the wiki
|
||||
|
|
@ -123,6 +124,13 @@ A Text feature follows the same rule: it stores the outlines it was vectorised i
|
|||
its string, font and height, so the project opens identically on a machine that lacks the font;
|
||||
the three parameters are only what an edit reopens the dialog with.
|
||||
|
||||
The recipe is copied into `Model::cad_recipe` after every document change
|
||||
(`DesignPanel::sync_recipe_to_model()`), so every save path writes it. A change marks the project
|
||||
modified the way other project data outside Prepare's undo stack does, with the backup's change
|
||||
mark and the plater's dirty flag, so the title, autosave and the unsaved-changes prompt of New
|
||||
Project and Open all see it. A project that holds only a design loads no objects; it still opens
|
||||
under its file's name, since `Plater::load_project()` counts a loaded recipe as a loaded project.
|
||||
|
||||
## The interaction contract
|
||||
|
||||
Three inputs carry the whole modelling loop — left click, right click and `Esc` — and the
|
||||
|
|
@ -162,7 +170,8 @@ rather than to its end points: a press that wandered past the budget at any mome
|
|||
navigation, even if it comes back to where it started, which is what stops a slow, careful
|
||||
orbit from ending in a menu. There is no time budget — a gesture that means something different
|
||||
when it is slow is exactly what the interaction charter rules out. The raycast uses the press
|
||||
position, not the release. The sketch tool sees a right press only once the release has shown it
|
||||
position, not the release, scaled to the canvas's GL pixels as every mouse event the canvas passes
|
||||
on is (two per logical pixel on a Retina display). The sketch tool sees a right press only once the release has shown it
|
||||
was a click: the press itself goes to the camera, which may pan or orbit with that button, and the
|
||||
canvas replays it to the tool on a stationary release. A tool that uses the click (to terminate a
|
||||
chain, say) keeps the menu closed. Past either budget the event is navigation, and navigation
|
||||
|
|
@ -320,10 +329,14 @@ The tab is a page of Orca's main window and answers to the same settings as Prep
|
|||
isometric from the front-right corner that Home returns to, not Prepare's front-left one.
|
||||
- **Viewport text.** The status line and the active tool's values are drawn by the canvas in
|
||||
its ImGui pass, so they go with the canvas: a top-level window over GL does not follow its
|
||||
frame and was left floating over other applications.
|
||||
frame and would be left floating over other applications.
|
||||
- **Undo.** The tab keeps its own history (the recipe is not part of Prepare's snapshots), but
|
||||
it has no Undo/Redo of its own: the top bar, `Ctrl+Z` and Edit drive it while the tab is
|
||||
shown, greyed to what an undo would actually do.
|
||||
shown, greyed to what an undo would actually do. Every change to the recipe is one step, a
|
||||
feature rename included, and an edit the kernel refuses leaves none and keeps what was
|
||||
redoable. A body's name and colour are saved with the recipe but are not in the history, and
|
||||
its visibility is view state. The history is not saved with the project, so a project opens
|
||||
with nothing to undo in the tab.
|
||||
- **Docking.** The sidebar docks like Prepare's — either side, floating, resized, or collapsed
|
||||
with the canvas's collapse button or `Shift+Tab` — through its own AUI manager under the
|
||||
toolbar, because Prepare's manages the Plater and the Plater is not on this page. The button is
|
||||
|
|
@ -345,24 +358,168 @@ most: its verbs are items of their own at the top of the menu rather than a fami
|
|||
is appended after the eight, so it moved no existing index, and it reads the same from the
|
||||
viewport and from a row of the Bodies list.
|
||||
|
||||
An invariant across 93 verbs and 20 selection kinds does not survive by review, so the map
|
||||
An invariant across 92 verbs and 20 selection kinds does not survive by review, so the map
|
||||
exists once, as data: `scripts/CAD/tool_atlas.json` carries every verb with its row, key, icon,
|
||||
accepted selections, preconditions and refusal string, and `scripts/CAD/gen_offer_table.py`
|
||||
emits `src/slic3r/GUI/CAD/DesignOffer.hpp` from it. The header is checked in and never
|
||||
hand-edited; `scripts/CAD/run-all-checks.sh` runs the generator with `--check` as its first
|
||||
rung, which is what makes "GENERATED — DO NOT EDIT" a fact rather than a request. The generator
|
||||
also refuses an atlas with a duplicate verb id, since `mcp_run_verb` resolves a verb by id and
|
||||
would make the second one unreachable.
|
||||
hand-edited; the `check_cad_offer_table.yml` workflow runs the generator with `--check` on every
|
||||
push and pull request that touches the atlas, the generator or the header, which is what makes
|
||||
"GENERATED — DO NOT EDIT" a fact rather than a request. The generator also refuses an atlas with a
|
||||
duplicate verb id, since a verb is resolved by id (`mcp_run_verb`, a command's key) and the second
|
||||
one would be unreachable, and a table in which an entry's name is not marked for translation in the
|
||||
`Design` context (`L_CONTEXT`): every name is a command's title, which a person sees translated, and
|
||||
the mark compiles to the bare string, so nothing at run time could tell it is missing.
|
||||
|
||||
The same table is the Design tab's Speed Dial actions and its automation commands, so the three cannot drift
|
||||
apart. The header's `kDesignTools` holds 127 entries: the 92 verbs with a menu item, and 35 commands with no
|
||||
menu item (`row` -1), such as `design_describe`, `sketch_draw` or `design_commit_to_plate`. An entry with a handler
|
||||
(`action`, the code its menu item runs) or a `tool` block is a command of the catalog, whose key is the entry's
|
||||
id and whose title is its name, unless it is a folded item: 88 commands. An entry with a handler does what its
|
||||
menu item does when it is called with no arguments, and has an action of its own in the Speed Dial. An entry
|
||||
with a `tool` block also runs silently, with arguments: the block is that form's access, params, examples and
|
||||
whether it reports a rejected rebuild in its reply, which the header carries as JSON text (`doc`) beside the
|
||||
entry's `access` and `ok_false`. An item
|
||||
whose tool is a variant of a command is folded into it (`"fold": {"into", "args"}`): it is no command, keeps its
|
||||
id, its place in the menu, its key and its Speed Dial action, and the command opens its tool when called with
|
||||
exactly the item's arguments, as Polar array is `sketch_pattern {type: "circular"}` and the Corner rectangle
|
||||
`sketch_draw {type: "rectangle_2_point"}`. 37 items fold into eight commands, the 24 shape items into
|
||||
`sketch_draw` among them. An entry with a handler and a block may name the arguments that choose its own item
|
||||
(`args`), as Boolean's Join item is `solid_boolean {operation: "join"}`, so that each of a command's variants opens
|
||||
the same way. Two items have neither a handler nor a block, Pattern on Curve and Align to, and are shown greyed:
|
||||
they are no command. Every command has a `section`, its heading in the names index the MCP server's
|
||||
`tool_list` gives, and `feature_row` marks the four items whose handler works on the Feature tree's selected
|
||||
row (Edit, Rename, Delete and Constrain sketch). `operations` names what a command that changes Prepare's model
|
||||
reaches of `GUI/Operations` (`design_commit_to_plate`'s `delete_objects`). `modal` marks the three entries whose handler opens a dialog
|
||||
that waits for an answer: a modal one for SVG (a file picker) and Color, which holds the call that opened it
|
||||
until it is answered, and the Design tab's own modeless dialog for Text, which does not.
|
||||
`kDesignSelectionIds` names the selection kinds in `OfferSel`'s order, the ids the verbs' `accepts` use.
|
||||
|
||||
The atlas and its generator sit in `scripts/CAD/` rather than in `docs/`: they are build inputs
|
||||
for a checked-in header, not documentation.
|
||||
|
||||
## Automation surface
|
||||
|
||||
`McpControl` exposes the document over JSON-RPC when `ORCA_CAD_MCP` is set in the environment,
|
||||
with `tools/orca_cad_mcp_bridge.py` as the client side. It describes the scene, queries
|
||||
topology, measures, and runs the same verbs the offer does — it re-implements nothing, so a
|
||||
scripted action and a clicked one cannot diverge. It is off unless the variable is set.
|
||||
The document is automated through the app's MCP server, on every platform, with the Design tab's commands, one
|
||||
per command entry of its table: what they are, how they are named and called, what each does and takes and which
|
||||
menu items call it are in [mcp-tools.md](mcp-tools.md), The Design tab's commands, and how the server holds them,
|
||||
their gate and their Speed Dial actions in [mcp-server.md](mcp-server.md). The commands
|
||||
(`Mcp/McpToolsDesign.hpp`, `Mcp/Tools/Design*.cpp`) describe the design, read topology, measure, and run the same
|
||||
verbs the offer does — they re-implement nothing, so a scripted action and a clicked one cannot diverge. Where a
|
||||
GUI action is bound to a selection, a card or a dialog, its work is split into a function both callers share, and
|
||||
the command calls that function with explicit arguments instead of driving the widgets; the functions the tab
|
||||
shares so are below.
|
||||
|
||||
The catalog holds the commands only when the CAD feature is on at startup, because the main window makes the
|
||||
Design page only then, so turning the feature on takes a restart. What a caller sees of that, and when the tab
|
||||
refuses a call, are in mcp-tools.md, The Design tab's commands.
|
||||
|
||||
Face and edge ids name faces and edges of the current model, and a rebuild renumbers them while a
|
||||
stale id still names a real face or edge, so the replies carry the model's `generation`: a call that
|
||||
passes ids with the `generation` they were read at is refused (`stale_ids`) once the model has moved
|
||||
on, rather than acting on another face or edge.
|
||||
|
||||
The commands add features through the kernel calls the cards use, named as the cards name them,
|
||||
one checkpoint per call. A rebuild that fails is taken back with `CadDocument::rollback()`, which
|
||||
leaves nothing to redo, and the status line says "Edit rejected" as it does for a refused GUI
|
||||
edit; the call reports the kernel's reason. A card's own Confirm in add mode does the same: a feature whose
|
||||
rebuild fails is taken back, and an add the card refuses or that adds nothing leaves no undo step, and either
|
||||
way the card stays open with the reason on the status line. Commit to Plate and Export STEP confirm an open card
|
||||
first, so that what is shown goes out, and stop where that Confirm does not take: nothing is sent or written and
|
||||
the Design tab stays in front. Planes are named as in the cards: a
|
||||
base plane through the modeling origin, the frame every feature uses, a datum Plane feature, or a
|
||||
planar face, which a sketch takes with its outward normal (`CadDocument::plane_of_face()`) and where a hole or a
|
||||
thread drills from the Hole card's inward face plane, its x along the face's longest edge
|
||||
(`CadDocument::inward_plane_of_face()`, shared with the card). A feature is read and edited as its
|
||||
card shows it: `feature_describe` and `feature_edit` share one table of each type's card fields and
|
||||
ranges, and an edit goes through `replace_feature()` as the card's Confirm does in edit mode. Numeric fields are
|
||||
set through `CadDocument::set_numeric_field()`, the allow-list expressions use, so a literal edit and a binding
|
||||
reach the same fields. A feature stores its body indices and face and edge ids as of the model just before it,
|
||||
and the rebuild replays them so; a Plane's, an Axis's and a Coordinate system's are the finished model's, where
|
||||
the engine reads them (`for_each_body_ref()`). `CadDocument::recompute()` records the bodies that existed just
|
||||
before each feature (`bodies_before`, not saved), and `CadDocument::history_before()` gives the history cut at a
|
||||
feature, without the undo and redo stacks and the display meshes, which `body_describe {before}` replays and the
|
||||
cards replay to list bodies when they edit. While a card that edits a feature is open, the viewport's pick is fed
|
||||
the model before the feature (but for those three), each of its bodies where the view draws the body it became
|
||||
(its placement, matched by identity, as its visibility is), and the Hole and Thread cards read the picked face's
|
||||
geometry from that model too. `CadDocument::for_each_feature_ref()` and, for a datum plane,
|
||||
`for_each_datum_ref()` are the kernel's own reference visitors, the lists that deleting and moving a feature
|
||||
remap, from which `feature_describe` reads `used_by`.
|
||||
|
||||
Commit to Plate and Export STEP… are split from their button and file dialog
|
||||
(`commit_to_plate()`, `export_step_to()`), so `design_commit_to_plate` and `design_export_step` run the GUI's own work,
|
||||
and `design_new` is New Design's `clear_document()` without the confirmation. The Feature tree's
|
||||
and Bodies list's row actions are split the same way, into cores that take an index
|
||||
(`delete_feature()`, `move_feature()`, `show_feature()`, `rename_feature()`, `delete_body()`,
|
||||
`rename_body()`, `set_body_color()`, `show_body()`), which the rows call with the selected one and
|
||||
the automation calls without selecting anything. A tree edit the kernel refuses has its features put back by the
|
||||
kernel, and `CadDocument::abandon_checkpoint()` drops the checkpoint and restores the redo branch it cleared, so
|
||||
no undo step is left. `design_select` selects through `mcp_select()` what a click would select.
|
||||
|
||||
A body's placement, where Commit to Plate and Export STEP send it, is view state the panel keeps per body
|
||||
(`m_body_xform`), keyed by the transient `uid` of the feature that made the body (`CadFeature::uid`), so that it
|
||||
follows the body when the bodies are renumbered. The Move / Rotate card and Place on Face (`place_on_face()`) set
|
||||
it, and so does `body_place` (mcp-tools.md, A body's placement). The section view and the
|
||||
view's switches have setters that take a value, which `view_set {tab: "design"}` uses where the toolbar and the
|
||||
rows only toggle, and `DesignCanvas::view_normal_to_sketch()` is the `N` key.
|
||||
|
||||
A sketch session opens through `begin_sketch_session()`, which a plane or face pick also runs, on the same plane
|
||||
frames, so a sketch on a base plane passes through the modeling origin. A committed sketch is re-opened in the session
|
||||
by `DesignCanvas::edit_sketch()` and `DesignSketchTool::begin_edit()`; mcp-tools.md (Behaviour a caller relies on)
|
||||
says what `sketch_edit` and the sketch commands then do. A committed sketch's loops come from
|
||||
`DesignSketchTool::loop_report(entities)`, which finds and numbers them over the whole sketch, as
|
||||
`region_entity_indices_with_holes()` numbers them; how a call names one is in mcp-tools.md (The selection). The
|
||||
viewport shows only the loops no extrude has taken, so its loops are numbered apart, and `DesignPanel::mcp_select()`
|
||||
selects a numbered loop by finding the shown loop with its entities (`display_region_of()`), refusing one an extrude
|
||||
took. `DesignPanel::default_revolve_axis_entity()` gives a sketch's only construction line, or none when it has none
|
||||
or several, which the Revolve card offers first as its axis. Inside a session, `DesignSketchTool`'s scripted entry
|
||||
points run the tools' own apply steps without a pointer: `fillet_scripted()` is the Fillet and Chamfer tools' Confirm
|
||||
(`confirm_op()`, which reports a refused value), `trim_scripted()` a Trim or Extend click (`apply_live_trim()`),
|
||||
`transform_scripted()` the transform gizmo's Confirm, for a move, rotate or scale and for a linear or circular
|
||||
pattern, `mirror_scripted()` the Mirror tool's, `offset_scripted()` the Offset tool's, `add_shape_scripted()` the last
|
||||
click of every drawing tool, which `sketch_draw` reaches by its `type` (the nineteen shapes, from a line to a polygon,
|
||||
built by the tool's own builder and grouping, with the constraints inferred exactly, and those the tool binds inside
|
||||
the shape at any slant, such as an oblique rectangle's right angles or a slot's tangencies, added where rounding left
|
||||
them out, batched as the tool's inference batches them; `make_polygon()` puts a polygon's side within 1e-9 rad of
|
||||
level or upright on an axis, because the rounding of its vertices' sines and cosines differs between platforms' math
|
||||
libraries and would leave a different set of sides exact on each), and `constrain_scripted()` a CONSTRAIN bar button
|
||||
or the Dimension tool, whose picks the planner it shares with the panel (`plan_entity_constraint()`,
|
||||
`write_plan_value()`, in `SketchEngine`) turns into constraints. Each keeps the armed tool and its sticky settings,
|
||||
and refuses while a gesture or a value field is pending, which the tool's apply step would take over. Text and SVG art
|
||||
have argument forms beside their dialog and file picker: `sketch_text` takes the Text dialog's outline and push
|
||||
(`DesignPanel::mcp_outline_text()`), and `sketch_insert_svg` adds an SVG file's outlines as Insert SVG does
|
||||
(`add_imported_regions`).
|
||||
|
||||
Topology reads come from the kernel: `GeometryEngine::surface_info()` gives a face's surface type,
|
||||
area and analytic numbers, `edge_faces()` the faces along each edge (one for a seam),
|
||||
`edge_convexity()` whether two faces meet in an outside or inside corner (OCCT's fillet classification,
|
||||
`ChFi3d::DefineConnectType`), and `min_distance()` the closest points of two shapes (OCCT's
|
||||
`BRepExtrema_DistShapeShape`). The Plane card's Confirm and the `construct_plane` command
|
||||
share `CadDocument::datum_plane_refusal()`, which refuses a construction that is missing a
|
||||
reference, names a face or edge no longer on the model, or puts a tangent plane on a face that is
|
||||
not a cylinder, so neither reaches the kernel's silent fallback to an offset plane; a refused
|
||||
Confirm leaves no undo step.
|
||||
|
||||
The Thread card's pick and `solid_thread` share `CadDocument::thread_target()` (the picked cylinder's
|
||||
axis frame) and `nearest_thread_standard()` (the size inferred from it). The Sweep card's path list
|
||||
holds Helix features as well as sketches, and a sweep along a helix is made with a binormal
|
||||
(`SketchEngine::make_sweep`). Thread, sweep and loft automation rebuilds through `recompute_guarded()`,
|
||||
as the cards do: the kernel works on a worker thread while the UI thread waits in `wxYield()` behind a progress
|
||||
dialog that appears after 300 ms, so the window stays live during a long build.
|
||||
|
||||
The tab borrows the app's shared camera when its page shows (`DesignPanel::on_tab_shown()`, which swaps it into
|
||||
the plater's slot) and gives it back when the page hides, so the Design view's camera is the one the camera tools
|
||||
act on while the tab is shown.
|
||||
|
||||
The viewport is a canvas target like Prepare's for the app's MCP server (`DesignCanvas::gl_canvas()`):
|
||||
`view_set {tab: "design"}` shows the tab and points its camera, `window_screenshot` captures the view
|
||||
(sketch overlay and status line included) and composites it into window captures, `mouse_gesture`
|
||||
clicks and drags it at pixels, so a left click picks and a right click opens the offer, and
|
||||
`widget_list` lists its in-canvas value fields. Keys sent with `keyboard_press` reach the panel's
|
||||
`wxEVT_CHAR_HOOK` as a real key press does, travelling up from the focused widget, so Escape,
|
||||
Enter and the tool shortcuts behave as they do for a person.
|
||||
|
||||
[mcp-tools.md](mcp-tools.md) describes the commands as a caller sees them, and [mcp-server.md](mcp-server.md) how
|
||||
the server holds them: the table they are made from and their gate.
|
||||
|
||||
## Where the code lives
|
||||
|
||||
|
|
@ -377,18 +534,32 @@ scripted action and a clicked one cannot diverge. It is off unless the variable
|
|||
| `src/slic3r/GUI/CAD/DesignRowList.*` | the Feature tree and Bodies lists, with per-row actions |
|
||||
| `src/slic3r/GUI/CAD/DesignCanvas.*` | viewport integration |
|
||||
| `src/slic3r/GUI/CAD/DesignSketchTool.*` | in-canvas sketching |
|
||||
| `src/slic3r/GUI/Mcp/McpToolsDesign.hpp`, `src/slic3r/GUI/Mcp/Tools/Design*.cpp` | the automation surface: the Design commands made from the table, their silent forms (`silent_forms()`) and their gate; `DesignTools.cpp` holds the gate, the registration and the Document heading's commands, and each other heading's are in a file of its own (`DesignSketchTools.cpp`, `DesignSolidTools.cpp` and so on) |
|
||||
| `src/slic3r/GUI/CAD/DesignInteraction.hpp` | the Esc level contract |
|
||||
| `src/slic3r/GUI/CAD/DesignOffer.hpp` | generated offer table |
|
||||
| `scripts/CAD/tool_atlas.json` | source of truth for the offer |
|
||||
| `src/slic3r/GUI/CAD/DesignOffer.hpp` | the generated table: the offer, the Speed Dial actions and the commands |
|
||||
| `scripts/CAD/tool_atlas.json` | source of truth for the table |
|
||||
|
||||
## Verification
|
||||
|
||||
The kernel is covered by Catch2 suites in `tests/libslic3r/` (`test_caddocument`,
|
||||
`test_sketchconstraints`, `test_sketchedit`, `test_sketchimport`, `test_sketchinference`,
|
||||
`test_sketchprofile`, `test_slvs_constraints`), which need no display;
|
||||
`scripts/CAD/run-kernel-tests.sh` builds only `libslic3r_tests` and runs them headless.
|
||||
`test_sketchprofile`, `test_slvs_constraints`), which need no display. They are part of
|
||||
`libslic3r_tests` in a CAD build and run under `ctest` and CI like any other suite;
|
||||
`libslic3r_tests "[CadDocument]"` runs the document's cases.
|
||||
|
||||
The GUI half is not covered by CI, which has no OpenGL canvas or synthetic input: the ladders
|
||||
in `scripts/CAD/` drive a running application in a local rig instead, and
|
||||
`scripts/CAD/run-all-checks.sh` is the gate that runs all of them. A green kernel run says
|
||||
nothing about the viewport, so the two are reported separately rather than as one number.
|
||||
The automation surface has its own checks. `slic3rutils_tests "[Mcp][CAD]"`
|
||||
(`tests/slic3rutils/test_mcp_cad.cpp`) runs the commands' argument checks and kernel calls on a
|
||||
`CadDocument` or a bare `DesignSketchTool`, with no panel, and checks the table and the commands the
|
||||
catalog holds; `scripts/CAD/test_gen_offer_table.py` checks the generator's refusals. On a live application,
|
||||
the MCP sweep's Design tests drive the commands through `tool_call` and, through the server's UI tools, the tab
|
||||
as a person does; `tools/mcp/test-entries/design.md` says what each checks. They need an English UI, and the
|
||||
MCP sweep runs them on the Linux AppImage; `tools/mcp/README.md` says how to run them by hand.
|
||||
|
||||
Three checks in `scripts/CAD/` drive a running app through its MCP server as an agent does and
|
||||
grade the sketch layer against arithmetic: `check-mcp-sketch.py`, `check-sketch-engine.py` and
|
||||
`check-sketch-engine-corpus.py`, which grades it against the vector geometry of real drawings.
|
||||
They need the MCP server and the CAD feature on and run on every platform; no CI job runs them.
|
||||
`scripts/CAD/README.md` says how to run each.
|
||||
|
||||
The offer table is checked in CI: the `check_cad_offer_table.yml` workflow fails when
|
||||
`DesignOffer.hpp` is not what `gen_offer_table.py` makes of `tool_atlas.json`.
|
||||
|
|
|
|||
|
|
@ -51,7 +51,10 @@ bare printable key in the frame hook would swallow that character in every text
|
|||
The dialog refuses such chords and `ShortcutRegistry::load()` drops them from the config.
|
||||
Space counts as typing. The speed dial's default is the one bare Space, and
|
||||
`MainFrame` leaves it to a focused control that uses Space itself (text fields, buttons,
|
||||
combo boxes), so it opens the dial from the canvases and the tab strip only.
|
||||
combo boxes), so it opens the dial from the canvases and the tab strip only. Selecting a page
|
||||
with a 3D view (Prepare, Preview, the Design tab) gives the view the keyboard: the page's own
|
||||
`SetFocus()` would hand it to its first focusable control, a sidebar control there, which keeps
|
||||
Space until the pointer enters the view.
|
||||
|
||||
`MainFrame::handle_global_shortcut` skips a chord that `KeyChord::edits_text()` reports
|
||||
while a text field has the focus (a wx text entry, spin control, web view or ImGui
|
||||
|
|
|
|||
564
docs/HLSD/mcp-server.md
Normal file
564
docs/HLSD/mcp-server.md
Normal file
|
|
@ -0,0 +1,564 @@
|
|||
# MCP Server
|
||||
|
||||
The MCP server lets an AI agent drive a running OrcaSlicer through the Model Context Protocol. A developer's agent
|
||||
reproduces a GitHub issue: it loads the files, picks presets, changes settings, clicks through the GUI, slices, takes
|
||||
screenshots before and after a fix and saves the steps as a replay. A user drives OrcaSlicer from Claude Code, Codex,
|
||||
Cursor or Claude Desktop. The server is off by default.
|
||||
|
||||
This document is the server's architecture and the principles its commands are built on. The commands themselves,
|
||||
how they are named and grouped, what each does and takes, which calls open a dialog and the behaviour a caller relies
|
||||
on, are in [mcp-tools.md](mcp-tools.md), and each command's description and schema, which `tool_describe` gives, is
|
||||
its manual. The Design tab, whose commands run on the same server, is in [design-tab.md](design-tab.md).
|
||||
|
||||
## Terms
|
||||
|
||||
- **Command**: one function the app can be asked to run, with a key (`object_mirror`), a JSON schema and a
|
||||
description. MCP lists it as a tool.
|
||||
- **Action**: an entry of the Speed Dial, the app's command palette. A command's actions run it with fixed
|
||||
arguments, and most of them are its menu items.
|
||||
- **Person's form**: a call whose arguments are exactly one of the command's actions'. It does what a person's pick
|
||||
of that action does, which may ask in a dialog; any other call runs from its arguments and opens nothing.
|
||||
- **Front end**: anything that runs commands: an MCP client over HTTP or the stdio bridge, Action Replay, the Run
|
||||
Script panel, a `--run` file, a plugin, and a person's pick in the Speed Dial or a menu.
|
||||
- **Job**: a call that runs on a thread of its own and can outlive its reply; `app_wait {for: "job"}` returns its
|
||||
result.
|
||||
- **Guard**: a command's class, `Inspect`, `Recover` or `Mutate`, which decides when it may run.
|
||||
- **Operation**: a function of the operations layer (`GUI/Operations/`), which holds what a command, a dialog and
|
||||
the plugin API share. A call's *background operation* is the slice, export or worker job it started and holds.
|
||||
- **Journal**: the session's record of the calls that changed something, which `replay_export` turns into a
|
||||
**replay**, a JSON file of calls that `replay_run`, `--run` and Action Replay run again.
|
||||
- **GUI instruments**: what driving the GUI needs beyond running commands: the UI inspector, the menu capture, ImGui
|
||||
item recording and, on Wayland, window-state hooks.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
MCP client ──HTTP──▶ McpEndpoint ◀──HTTP── orca-slicer --mcp-stdio ◀── stdio client
|
||||
(HTTP server, protocol, token, discovery file)
|
||||
│
|
||||
▼
|
||||
Action Replay ──▶ AutomationRuntime ── McpCore: arguments, guards, admission,
|
||||
Run Script ──▶ │ jobs (JobRegistry), Journal
|
||||
--run, plugins ─▶ │
|
||||
▼
|
||||
a person's pick ──▶ CommandCatalog (NativeCommands): Mcp/Tools/<Place>Tools.cpp
|
||||
│
|
||||
UiInvoker: every wx call on the UI thread
|
||||
│
|
||||
┌──────────────────┼───────────────────────┬────────────────────────┐
|
||||
▼ ▼ ▼ ▼
|
||||
Operations layer GUI automation: Capture: Replay engine,
|
||||
(GUI/Operations/) UiInspector, ModalTracker, ScreenCapture, Python runner
|
||||
│ SyntheticInput, page agent McpRecorder
|
||||
▼
|
||||
Plater, Tab, Sidebar, GCodeViewer and the other owners
|
||||
```
|
||||
|
||||
| Component | Its job | Code |
|
||||
|---|---|---|
|
||||
| `McpEndpoint` | The MCP server and nothing else: HTTP, the protocol, the request gate, the token, the discovery file, taking over a port another window gives up | `Mcp/McpEndpoint.cpp`, `McpHttpServer`, `McpProtocol` |
|
||||
| `AutomationRuntime` | Runs commands for every front end; owns the dispatch core, the jobs, the journal, the UI invoker, the `ModalTracker`, the recorder and the scopes a run, a plugin or a client leaves state in | `Mcp/AutomationRuntime.cpp` |
|
||||
| `McpCore` | Dispatches a call: checks its arguments, applies its guard and operation admission, runs it inline or as a job, journals it | `Mcp/McpCore.cpp` |
|
||||
| `CommandCatalog` | Every command, built once at startup and sealed, so any thread reads it | `CommandCatalog.hpp`, `NativeCommands.cpp`, `Mcp/Tools/` |
|
||||
| `ActionRegistry` | The Speed Dial's actions, a command's among them | `ActionRegistry.cpp` |
|
||||
| Operations layer | What more than one interface does, in one place: checks, refusals, undo, the owner calls | `GUI/Operations/` |
|
||||
| GUI automation | Sees the GUI as a person does and acts on it: the inspector and its refs, input, dialogs, web pages | `Mcp/UiInspector.cpp`, `Mcp/ModalTracker.cpp`, `Mcp/WebPages.cpp` |
|
||||
| Capture | Screenshots and recordings | `Mcp/ScreenCapture.cpp`, `Mcp/McpRecorder.cpp` |
|
||||
| Replay engine | Runs replays, and describes one for Action Replay | `Mcp/McpReplay.cpp`, `Mcp/McpReplaySummary.cpp` |
|
||||
| Python runner | Runs a script as the main program of a run, with the plugin API | `plugin/PythonScriptRunner.cpp`, `plugin/PythonSession.hpp` |
|
||||
| stdio bridge | Serves stdio clients and starts the app on demand | `Mcp/McpStdioBridge.cpp` |
|
||||
|
||||
The server runs inside the GUI process, because most of what an agent reproduces is GUI behaviour. `GUI_App` owns
|
||||
the runtime and the endpoint, and neither exists until something needs it: before then there is no thread, socket,
|
||||
modal-dialog hook or synthetic input state. The endpoint holds the runtime by reference, and the runtime does not
|
||||
know the endpoint, so every front end but MCP runs with the server off. The core that uses no wx (the command
|
||||
catalog's type, the dispatch core, the hand-off to the UI thread, the jobs, the journal, argument checking, the
|
||||
protocol and HTTP transport, the replay model, the stdio bridge and the token) is the library
|
||||
`libslic3r_automation`, unit-tested without the GUI.
|
||||
|
||||
## Design principles
|
||||
|
||||
1. **One command, every route.** A command is one function, `run(args, context)`, with JSON arguments that match its
|
||||
schema. `tools/call`, `tool_call`, a replay step, a script's or plugin's call, a Speed Dial pick and a menu item
|
||||
all reach it by its key and run it alike, so a feature added once reaches agents, replays, scripts and people.
|
||||
2. **A command does what the GUI does, through the GUI's code.** What a command shares with a dialog or another
|
||||
interface is an operation, which the dialog calls too, so the two cannot drift apart. A command writes a value
|
||||
through the control that sets it, and acts on the selection by selecting as a person would, so the app answers
|
||||
with its own undo steps, notifications and dialogs.
|
||||
3. **A call either asks or runs from its arguments.** The person's form asks as the menu item does; any other call
|
||||
opens nothing and takes the dialog's answers as arguments, or refuses with the question as its reason. So an agent
|
||||
can work without a person, and a person's pick behaves as it always has.
|
||||
4. **The UI thread is never blocked by a request, nor re-entered.** Handlers run off the UI thread and post every wx
|
||||
call to it; a guard keeps a change out of a modal dialog and out of another call's nested event loop. A call that
|
||||
outlives its reply budget becomes a job, and the server never retries a change.
|
||||
5. **A call owns its result.** A slice or export the call started is its background operation, numbered so it is
|
||||
never taken for someone else's, and one runs at a time, so no call changes the project under another's.
|
||||
6. **A replay does the same thing again.** The journal records each call in its schema's form, with indices rather
|
||||
than per-process ids, locators rather than refs, and the values a call resolved from saved state; defaults are
|
||||
fixed values, never what a person last set.
|
||||
7. **Agents find by listing, and replies say what they hold.** An agent lists a catalog and reads the manual of what
|
||||
it picked, since a word search does not match a person's words to a command. Descriptions state what a reply
|
||||
holds, what every tool shares is said once, and a reply's default size fits a client's reply cap.
|
||||
8. **Nothing leaves the machine, and secrets stay hidden.** The server binds to loopback and wants a token, scripts
|
||||
run under the plugin audit, and captions, the activity log, dialog text and URLs mask secrets.
|
||||
9. **It costs nothing until used.** The runtime and the endpoint start on first use, and the GUI instruments, which
|
||||
cost every frame, are on only while something drives the GUI.
|
||||
10. **Input stays inside the app.** Input goes in as wx events, never through the OS or the window manager, so no
|
||||
command needs OrcaSlicer in front and the app never takes the keyboard from the person's other app.
|
||||
|
||||
## Transport
|
||||
|
||||
The endpoint is `http://127.0.0.1:<port>/mcp`, bound to loopback; the default port is 13619, since 13618 is the
|
||||
OAuth callback server. It is stateless Streamable HTTP: each POST carries one JSON-RPC message, with no SSE stream,
|
||||
no `Mcp-Session-Id` and no batching. `McpHttpServer` serves every socket on one I/O thread and runs each request on a
|
||||
thread of its own, because a handler can block for a whole reply budget. Connections are capped, and at the cap the
|
||||
one stalled longest on its client is evicted, never one being handled, so a recovery call gets through. Sockets are
|
||||
not inherited by child processes, which would otherwise keep the port bound after the server closes it.
|
||||
|
||||
Every request is checked before any JSON is parsed: path, method, a loopback `Host` against DNS rebinding, a loopback
|
||||
`Origin` when sent, the bearer token in constant time, the content type and a size cap. No CORS headers are sent.
|
||||
`McpProtocol` serves the handshake era (2025-11-25, 2025-06-18) and the 2026-07-28 era, whose requests carry their
|
||||
version in `_meta` and need no handshake.
|
||||
|
||||
A tool result is one compact JSON text block plus any images. No tool declares an `outputSchema`: Claude Code shows
|
||||
its model a tool's description and input schema but never its output schema, and fails a call whose structured
|
||||
content does not match it, so a schema would teach nothing and could turn a call that ran into an error. Failures
|
||||
are `isError` results the model can act on (mcp-tools.md, How a failure shows). Before validation the server reads
|
||||
what agents commonly send in place of the schema's form (`normalize_arguments()`): an argument under a name the tool
|
||||
does not take as one it does, a value in another JSON form, an enum value under the other argument whose enum takes
|
||||
it. Each came from the bench, where it was an agent's first guess many times over, and the journal records the
|
||||
schema's form.
|
||||
|
||||
The server `instructions` fit the 4096 characters clients keep. Clients that defer tools load only names and the
|
||||
instructions at first, so the instructions say first how to find what to call, then what many tools share: never
|
||||
retry a call that returned a job, a call with an action's arguments may ask, the paging shape, 0-based indices, ids.
|
||||
|
||||
## Security, token and discovery
|
||||
|
||||
The bearer token is 32 random bytes in `<datadir>/mcp/token`, owner-only (created 0600 on POSIX, the per-user ACL on
|
||||
Windows) and kept out of AppConfig, whose writes use default permissions. `ORCA_MCP_TOKEN` overrides it for one run.
|
||||
Deleting the file and turning the server off and on issues a new token. While serving, `<datadir>/mcp/server.json`
|
||||
holds the URL, port, pid and token, so the stdio bridge and the test harness connect without the launch environment;
|
||||
it is written owner-only and removed on stop only by the process it names, since windows sharing a configuration
|
||||
folder share the file.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
The endpoint opens at startup, before the first startup dialog, when `--mcp`, `--mcp-port` or the `mcp_enabled`
|
||||
preference asks, so an agent can answer the TLS prompt or the setup wizard. The runtime starts on first use by any
|
||||
front end. `app_state.ready` stays false until the main window, the Prepare canvas's OpenGL and the tab pages are
|
||||
up, since a 3MF save needs GL for its thumbnail and a GTK web view made too early loses its message handler; after
|
||||
10 s it stops waiting, since a hidden canvas or a busy person can hold either back for ever.
|
||||
|
||||
When the app closes, the endpoint closes and the runtime stops: waiting calls wake with "shutting down", new calls
|
||||
are refused, and auto-answer rules end. Nothing is freed then, since a call may still be on the UI thread's stack in
|
||||
a nested loop; both are freed outside any event loop once their threads have left, or left in place after 10 s,
|
||||
since freeing under a call that never returns would crash. A language change rebuilds the GUI and only suspends the
|
||||
runtime: refs go stale and UI calls ask for a retry.
|
||||
|
||||
Windows that share a configuration folder share the port, and the bind is exclusive: the first window serves, and
|
||||
the others retry and take over when it closes. Windows meant to serve side by side need their own `--datadir` or
|
||||
`--mcp-port`. Turning the server off in Preferences closes only the endpoint, since the call that opened Preferences
|
||||
may itself be an MCP call; closing it ends the client's auto-answer rules, recording and held presses, so a person
|
||||
using the app afterwards never has a prompt answered for them.
|
||||
|
||||
## Threading
|
||||
|
||||
Tool handlers never run on the UI thread. Anything that touches wx runs in a closure that `ToolContext::run_ui()`
|
||||
posts through `UiInvoker` and waits for; a closure not started within 10 s is abandoned, and the call says it is safe
|
||||
to retry. After a change a tool makes one more round trip (`settle()`), so the events the change queued are handled
|
||||
before the reply. A person's pick is the one call that runs on the UI thread itself, in place.
|
||||
|
||||
**Guards.** The guard is checked in the closure, on the UI thread, since the app can change between posting and
|
||||
running. mcp-tools.md (When a command may run) lists the commands of each.
|
||||
|
||||
| Class | What it holds | Behind a modal or inside another call |
|
||||
|---|---|---|
|
||||
| `Inspect` | reads, lists, screenshots, `widget_list`, the recording commands | runs |
|
||||
| `Recover` | answering dialogs, `job_cancel`, `window_set`, GUI input aimed at the topmost modal | runs |
|
||||
| `Mutate` | everything else | refused, naming the dialogs |
|
||||
|
||||
A change inside another UI call's nested loop (a modal, a progress dialog, `wxYield`) would re-enter code that is in
|
||||
the middle of a call, which is why a mutate call is refused there. The input tools are recover calls so that they can
|
||||
answer the dialog that holds the app, and apply the mutate checks themselves once their target is outside it.
|
||||
|
||||
**Jobs.** Observation runs on the request thread; every tool that can activate UI runs as a job, since a click can
|
||||
open another modal. The request waits up to the reply budget, 45 s, under Codex's 60 s tool timeout, then replies
|
||||
`{status: "running", job}`. A handler that opens a modal blocks in its loop, so a probe posted into that loop reads
|
||||
the open dialogs, and the reply becomes `blocked_by_dialog` with a note on how to answer the dialog and how the next
|
||||
such call runs without asking, so an agent learns it from the call that asked.
|
||||
|
||||
**Platforms.** On macOS a native picker or message box pauses wx's pending events, and every posted closure with
|
||||
them, so the server answers from the snapshot the tracker publishes for any thread, and native dialogs are answered
|
||||
ahead by a `dialog_auto_answer` rule. Running closures some other way inside the Cocoa modal session would re-enter
|
||||
the app while the dialog is up. On Windows and Linux a native dialog's loop runs the closures, and on Windows the
|
||||
dispatcher also wakes the UI thread with a message, which menus' and system dialogs' loops need. On GTK a window the
|
||||
compositor isn't drawing gets no frames, so a call that times out says so instead of giving a misleading reason.
|
||||
|
||||
**Followed calls and the person mark.** A run a person starts (Action Replay, the Run Script panel, `--run`) outlives
|
||||
any reply, so the runtime follows it on a thread of its own and hands its result to the window that started it. Its
|
||||
jobs carry the person mark, so a script under a person's run runs as the person's (Python scripts, Identity).
|
||||
|
||||
### Operations
|
||||
|
||||
Slicing and G-code export finish in the background process, and arrange, orient and the gizmos' jobs on the Plater's
|
||||
job worker. A call that starts such work holds it as its background operation until it ends, so its reply is the
|
||||
work's outcome and `job_cancel` stops it. The worker does not record who queued a job, so a call that finds it idle
|
||||
at the start of one of its UI closures and busy at the end has started one and claims it; a job a person starts in
|
||||
that window is claimed too, a known cost of the rule.
|
||||
|
||||
**Admission.** While a background operation runs, every other `Mutate` call is refused, whichever client, replay or
|
||||
script sends it, and so are changes while the worker runs a job no call holds; reads are not. The check runs as the
|
||||
call arrives and again in each UI closure, so a call admitted just before an operation began still can't change the
|
||||
project under it.
|
||||
|
||||
**Identity.** An operation never takes another's completion for its own. `Plater` numbers slice requests and runs and
|
||||
keeps a project revision, so a slice knows its own runs, and is `superseded` when someone else slices or edits the
|
||||
project during them. Each plate's outcome comes from its last own run, and statistics come only while the project is
|
||||
as the slice left it. The rules are in `Operations/RunStatus`, free of wx and `Plater`, so they are unit-tested.
|
||||
|
||||
**Idle.** `app_wait {for: "idle"}` holds when no modal is open, nothing slices, the job worker and every gizmo's
|
||||
background work are idle, and no job runs but the caller and its ancestors, so a replay waiting for idle doesn't wait
|
||||
on itself.
|
||||
|
||||
## The operations layer
|
||||
|
||||
The Speed Dial, the MCP commands and the plugin API (`orca.host`) ask the app to do things by name, and what one does
|
||||
another often does too. The checks, the refusal and its wording, the undo snapshot and the order of the owner calls of
|
||||
such a function are in one place, `src/slic3r/GUI/Operations/` (namespace `Slic3r::GUI::Ops`), and each interface
|
||||
converts its arguments and results around it. Where a dialog does the same work (Clone, Preferences, the Plugins
|
||||
window, the Printer Selection and System Filaments dialogs, AMS sync, Fix Model), the dialog calls the operation too.
|
||||
|
||||
**What is an operation.** An effect, or a rule about one owner's state that its own widgets also apply, is a public
|
||||
method of the owner (`Plater`, `Sidebar`, `Tab`, `GCodeViewer`). What an automation caller invokes by name is an
|
||||
operation when more than one interface reaches it, and always for a new command. A caller calls an operation to
|
||||
change something and an owner to read. A function with one entry point is left as it is until a second appears.
|
||||
|
||||
**Shape.** An operation is a free function, `Outcome<Result> op(const Args&)`, over plain structs (no JSON, no
|
||||
`wxString`, no GUI pointer). An `Outcome` holds the result or a `Refusal`: a `kind` (`Precondition`, `Busy` or
|
||||
`Failed`), a stable `code`, one English message marked for translation, and `names` that help the caller. The Speed
|
||||
Dial shows the message translated; a tool and a Python exception carry it in English with its code, so a refusal
|
||||
reads the same through every route.
|
||||
|
||||
**Rules.** An operation runs on the UI thread and returns at once: background work returns a ticket and a status
|
||||
function, and the caller owns the wait, the timeout and the cancel. It takes its function's undo snapshot once, after
|
||||
its checks. It adds no guard and asks nothing: an answer a caller may give is a field of `Args`. An owner method whose
|
||||
menu item asks in a dialog takes the answer where a caller can give one (a path, a size, `keep_z`), which skips that
|
||||
dialog. For its other questions and messages it takes `Prompts`: `Ask` does as the menu item does, and `Skip` runs
|
||||
without them, each method saying what it answers in their place. An `Args` that passes the choice on holds a `Prompts`
|
||||
too. An operation includes owner headers, libslic3r and wx, and nothing of `GUI/Mcp`, `plugin/`, JSON or pybind11; the
|
||||
dispatch core includes nothing of it. A command does what a person's action does by running the code that action runs,
|
||||
not by writing the model or the config beside it: a dialog's OK is split into a function both call, and a command that
|
||||
acts on the object list's selection selects the row first.
|
||||
|
||||
**Keeping it so.** A command names the operations it reaches (`reaching()`), and the command reference lists them.
|
||||
`test_operations` requires every command outside the Design tab that is not read-only to name one, or to be on its
|
||||
exception list with a reason (it runs what its arguments name, drives the GUI, changes the session, has one entry
|
||||
point, runs its menu item's function, or steps a history).
|
||||
|
||||
## Tool catalog
|
||||
|
||||
The commands are the process's `CommandCatalog` (`NativeCommands::instance()`), built once at startup, before the
|
||||
runtime starts, and sealed, so any thread reads it. `register_all_commands()` gathers each place's commands from its
|
||||
file, `Mcp/Tools/<Place>Tools.cpp`, and sorts them by place, the first word of their names, in the order mcp-tools.md
|
||||
gives. A command is made with a maker that sets its guard and where it runs (`inspect_tool()`, `mutate_tool()`,
|
||||
`recover_input_tool()`, or `menu_command()` for one made from menu items). `tools/list` shows the commands that run
|
||||
from arguments; `tool_list` lists the rest (the menu items that take no arguments, the Design tab's commands, the
|
||||
plugins' operations), and `tool_call` runs any of them.
|
||||
|
||||
**Access labels.** Each tool's MCP annotations mark what a call does by its nature, not everything a call could
|
||||
reach. Codex asks before every call of a destructive tool and Claude Code runs read-only calls in parallel, so
|
||||
labelling by reach would put a confirmation on calls an agent makes all the time. `destructive` is a command whose
|
||||
every call deletes what a person made, with no undo; a command that loses work only when an argument says so, or that
|
||||
runs what its arguments name, is not. mcp-tools.md lists the commands of each label.
|
||||
|
||||
**Indices and ids.** Every argument that names an object, part or instance by index has a twin that names it by the id
|
||||
`object_list` reports. The index is what the app works by and moves when things before it go; the id stays with its
|
||||
thing, so a stale id is refused where a stale index would quietly name another. A call's ids are read as indices on
|
||||
the UI thread just before the command runs, so commands read indices only, and the journal records the indices,
|
||||
since ids belong to one process.
|
||||
|
||||
**Descriptions and replies.** A description gives what the tool does, the arguments that change it, `Reply:` with its
|
||||
fields, then edge cases, and what several tools share is written once (the locator grammar in `widget_list`, the
|
||||
paging shape in the server instructions), since every session loads the whole list. An argument name means one thing
|
||||
across the tools (mcp-tools.md, Naming). A name that misses is answered with the closest names, or with why the
|
||||
catalog left it out (the CAD feature off at startup). Lists page as `{items, offset, total}`, and defaults are sized
|
||||
so the bare call fits a client's reply cap. Numbers reach a client rounded, since a double's last digits are noise
|
||||
that costs tokens; a call asks for them whole with `_meta` `"orcaslicer/exact_numbers": true`. Paths are absolute,
|
||||
since a relative one would resolve against the GUI's working directory, and travel as UTF-8.
|
||||
|
||||
### Design tab: the Design commands
|
||||
|
||||
The Design tab's commands are made from one table, `kDesignTools` in `CAD/DesignOffer.hpp`, generated from
|
||||
`scripts/CAD/tool_atlas.json`, which is also the tab's right-click menu and its Speed Dial actions (design-tab.md, The
|
||||
offer is generated, not hand-written). An entry's description, closed schema, access and the operations it names all
|
||||
come from the table, and its silent form, in `Mcp/Tools/Design<Heading>Tools.cpp`, is bound to it by id. They join
|
||||
the catalog only when it is built with the CAD feature on, since the catalog is sealed at startup; otherwise a call by
|
||||
one of their names is told why (`design_unavailable`). They are not listed, so a session that never opens the tab
|
||||
pays only for their names, at the end of `tool_list`'s description.
|
||||
|
||||
A call that chooses a menu item opens that tool, as the menu does; any other call runs the silent form on the UI
|
||||
thread under the mutate guard. `design_gate()` refuses by cause first, and the entry's `access` decides what the tab
|
||||
lets through while a card, a Move or a sketch session is open. A failed rebuild is rolled back, so the design is as it
|
||||
was and the call is left out of a replay. mcp-tools.md (The Design tab's commands) has how they are named, called,
|
||||
refused and journaled.
|
||||
|
||||
## Speed Dial catalog
|
||||
|
||||
`action_list` and `action_run` serve the Speed Dial's `ActionRegistry`: the commands' actions, plates, recent
|
||||
projects, plugin scripts and pages, and settings on request. A menu item and the command that does its job are one
|
||||
command, so the items of one job are actions of one command, each with the arguments that pick its variant (Mirror >
|
||||
Along X Axis is `object_mirror {axis: "x"}`). An action keeps its menu item's id, title, section and icon, because a
|
||||
person's pins and run counts are stored under the id. The Design tab's actions are live: there while the tab is shown,
|
||||
in its mode, with the CAD feature on.
|
||||
|
||||
**One function, two contexts.** A call's context is the core's; a person's pick has a `PersonContext`, which runs in
|
||||
place on the UI thread with no job, no journal entry and no endpoint, so every action works with the server off. A
|
||||
long command a person picks runs as a job on the runtime's core instead, with the same guards and admission as a
|
||||
call, and shows its result as a notification. The makers place a command's function on the thread it needs:
|
||||
`ui_command()` on the UI thread, `long_command()` where its call runs, and `with_person_form()` and
|
||||
`with_menu_item_forms()` for a command whose person's form asks; `silent: true` runs such a command from its
|
||||
arguments, and the journal keeps it.
|
||||
|
||||
**action_run** runs an action as a call with its arguments would, after re-making the live families (plates, recent
|
||||
projects, the Design tab's actions), so it finds the app as it is. It is journaled as that `action_run`, so a replay
|
||||
never passes the action arguments it does not take, and an agent's runs never reorder the Speed Dial.
|
||||
|
||||
## GUI automation
|
||||
|
||||
The GUI commands (mcp-tools.md, Driving the GUI) let an agent see the app as a person does and act where the typed
|
||||
commands don't reach: a dialog, a gizmo's panel, a web page, a menu item with no command.
|
||||
|
||||
- **Seeing.** `UiInspector` turns the shown windows into a text tree: widgets, list rows, menus, the 3D toolbar and
|
||||
gizmos, the canvases' ImGui items (from ImGui's test-engine hooks, on only with the instruments) and web pages'
|
||||
elements. It reads an element as a person sees it, a field by the setting it edits or its label, so the tree is
|
||||
enough to act on without a screenshot. A ref is never reused and goes stale with its element; a locator names an
|
||||
element by what a person sees, so it holds across runs, and the journal records locators.
|
||||
- **Acting.** An element is activated through its owner's own dispatch (`wxEVT_MENU`, a toolbar's click action, a
|
||||
control's semantic event), and only custom-drawn widgets and the 3D views get synthesized mouse events, since a
|
||||
native control acts on what the system tells it. An element gets the state a person would see before it is listed
|
||||
or clicked. `SyntheticInput` holds the keys and buttons of a gesture for the code that reads hardware state, and a
|
||||
press is released by whoever made it or when its owner ends. The camera is turned with `view_set`, never a drag,
|
||||
since what a drag does is the user's mouse setting.
|
||||
- **Menus.** A native menu loop holds the UI thread until a person closes the menu, so a menu a call opens is
|
||||
captured instead of shown: listed in the reply, or its item dispatched as a pick from a shown menu is. Other menus
|
||||
opened while a call runs are closed unseen and noted.
|
||||
- **Dialogs.** `ModalTracker`, a `wxModalDialogHook`, sees every `ShowModal()`, native dialogs included, keeps the
|
||||
modal stack the guards read and publishes a snapshot for other threads. A dialog's message is read as a person
|
||||
reads it, with secrets masked. `dialog_answer` presses a wx dialog's own button, so its handler runs, and presses a
|
||||
native message box through the OS on Windows and Linux. An auto-answer rule answers a dialog as it opens: a picker
|
||||
takes its path as a person's choice would, and a wx dialog's button is pressed once its loop runs, since its
|
||||
handler does the dialog's work.
|
||||
- **Web pages.** Every web view, plugins' included, is read and driven by one page agent
|
||||
(`resources/web/mcp/page_agent.js`) that the server sends in with the request when a page lacks it, so no host
|
||||
needs a change. It lists a page after Playwright's accessibility snapshot, and sends what a person's input sends,
|
||||
since synthesized DOM events get no default action. A page's messages to its host are held while an action runs,
|
||||
so a page that closes its dialog can't destroy the web view under the call.
|
||||
- **Windows.** `window_set` changes only geometry and checks the whole request before anything changes. A window
|
||||
manager may apply a request later or change it, so the call waits until the window shows what was asked. Wayland
|
||||
has no request to place a window, so positions are refused there.
|
||||
|
||||
The windows a person keeps for themself (the Run Script panel, the Agent Activity pane, the Python scripts dialog,
|
||||
Action Replay's prompts) are named `kHiddenFromAutomation`, so no tool or auto-answer rule acts in them.
|
||||
|
||||
## Screenshots and recording
|
||||
|
||||
`window_screenshot` captures on the UI thread and encodes off it. The canvas capture forces a frame of a 3D view and
|
||||
reads it back before the swap, so it is exactly what is drawn on every platform. The window capture takes a window
|
||||
and composites the 3D views into it, since window capture loses OpenGL content on several platforms, and says
|
||||
`approximate` where it may differ from the screen.
|
||||
|
||||
| Platform | Window capture |
|
||||
|---|---|
|
||||
| Windows | Windows Graphics Capture, which reads what DWM composed, covered or not; `PrintWindow` would repaint the window and flash it |
|
||||
| macOS 14.4 and later | ScreenCaptureKit, the app's own windows only, which needs no Screen Recording permission |
|
||||
| macOS before 14.4 | the content view drawn into a bitmap, approximate |
|
||||
| Linux X11 | `XGetImage` of the window |
|
||||
| Linux Wayland | the window's widgets drawn into a bitmap, approximate |
|
||||
|
||||
A recording has to stay light, since it runs while the app works. The UI thread only captures, on a timer that fires
|
||||
inside modal loops too and backs off when capturing is slow; `RecordingSink`, which uses no wx, writes the frames as
|
||||
JPEG into a Matroska file, which keeps their real times and plays as it is, and drops a frame rather than wait for
|
||||
the disk. `recording_encode` runs the system `ffmpeg`, never a program a call names, at constant quality, which suits
|
||||
a mostly still screen. Captions name the calls that act, with secrets masked. While any recording runs the tab bar
|
||||
shows a REC pill, so a person always knows the app is being recorded.
|
||||
|
||||
## Replays and the journal
|
||||
|
||||
A replay is a JSON file of calls, which one engine (`McpReplay.cpp`, wx-free) runs for `replay_run`, `--run` and
|
||||
Action Replay:
|
||||
|
||||
```jsonc
|
||||
{ "orca_replay_version": "0.2.0", "name": "repro #12345", "vars": {"model": "${replay_dir}/part.stl"},
|
||||
"steps": [
|
||||
{"tool": "project_import", "args": {"paths": ["${vars.model}"]}},
|
||||
{"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}},
|
||||
{"tool": "window_screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}}
|
||||
]}
|
||||
```
|
||||
|
||||
`orca_replay_version` is the format's semver: a minor version adds tools or fields, a major one renames or removes
|
||||
them, and while the major version is 0 a build reads only its own minor version. The step fields, placeholders and
|
||||
matchers are in `replay_run`'s description. Steps are child calls of the replay's job, so they are not journaled and a
|
||||
replay's wait for idle doesn't wait for itself.
|
||||
|
||||
**The journal** records the client calls that change something, plus the waits, screenshots and recordings a replay
|
||||
needs, in the schema's form, with locators for refs and indices for ids. A call that runs as a job is judged by its
|
||||
final result, so a replay never repeats a call that did nothing, and one that asked in a dialog stays, since the
|
||||
steps after it answer that dialog. It keeps a bounded number of recent calls, so a long session can't grow it without
|
||||
limit.
|
||||
|
||||
**`--run FILE`** runs a replay or a Python script once the GUI is ready, then closes the app and exits 0 when it
|
||||
passed, 1 when a step failed and 2 when the file is invalid; `--outputdir` is where files saved without a path go.
|
||||
A `--run` launch is never handed to a running instance, so its exit code is its own, and its session is the run's, so
|
||||
a person's unsaved-project backup is still offered at their next launch.
|
||||
|
||||
**Action Replay** is a window where a person opens, writes and replays a file, whole or a step at a time. A replay is
|
||||
a file people pass around, so before a run the window describes each step and flags what reaches beyond the project:
|
||||
writing a file outside the output folder, changing presets, replacing the project, sending to a printer, or running a
|
||||
program. When a step would replace a project with unsaved changes, it asks whether to save first. The window's
|
||||
prompts are the person's own, so no tool and no auto-answer rule a replay registers answers them.
|
||||
|
||||
## Python scripts
|
||||
|
||||
A Python script is a `.py` file or a code string that runs on the plugin interpreter as the main program of a run,
|
||||
with the whole plugin API and without being packaged as a plugin. A person runs one in the Run Script panel or with
|
||||
`--run file.py`; an agent sends one with `script_run`, and a plugin's code may too. A script that runs under
|
||||
`python file.py`, or code written for a plugin's `execute()`, runs here unchanged. A *file run*, whose `filename`
|
||||
names an existing file, gets `__file__`, `sys.argv`, imports from its folder and its PEP 723 dependencies, installed
|
||||
into the package folder plugins share; code sent as text gets none of that. The outcome (`finished`, `raised`,
|
||||
`cancelled`, `timed_out`) is reported in a successful result, so the journal keeps the call and a replay of it fails
|
||||
again. What a script can rely on:
|
||||
|
||||
- **Runs overlap**, an agent's beside a person's, so a run's output, `__main__`, `sys.argv` and identity are keyed by
|
||||
the run bound to the calling thread, and carried into the threads and pool tasks it starts.
|
||||
- **Imports.** A file run imports from its folder without anyone changing `sys.path`, and an edited helper is
|
||||
compiled afresh on the next run. `sys.modules` is one cache, so overlapping scripts from different folders share a
|
||||
helper of the same name; helpers want distinct names.
|
||||
- **The end of a run.** Like `python file.py`, a run ends once its code, its non-daemon threads, its window callbacks
|
||||
and its pool tasks are done. Then it shuts down the pools its code created and calls its `atexit` functions once.
|
||||
Pool workers are shared by every run and belong to none.
|
||||
- **Stop.** `job_cancel` and `timeout_s` interrupt the run, again every second until it ends, but never inside the
|
||||
host's own bookkeeping; five seconds after the first stop the run stops waiting for its work. Code blocked in a C
|
||||
call holds the run until it returns.
|
||||
- **Windows.** What a run opens closes with it. A window callback runs on the UI thread, so it can't call tools,
|
||||
which wait for the UI thread, and hands work to the script's own code. While a modal the run opened is up, tool
|
||||
calls that change the project are refused, so interactive scripts use modeless windows.
|
||||
- **Idle.** A `script_run` job doesn't count as busy for `app_wait {for: "idle"}`, though the calls it makes do, so a
|
||||
macro waiting for the person doesn't hold every agent's wait.
|
||||
|
||||
**Identity.** A person's script runs under the audit identity `(script)` and an agent's under `(mcp)`, told apart by
|
||||
the person mark. The plugin audit ([plugin-permissions.md](plugin-permissions.md)) judges a script as it judges a
|
||||
plugin, but a script has no install state to hold a grant, so it is never asked. A plugin's own `script_run` runs
|
||||
under the plugin's identity and grants.
|
||||
|
||||
**The setting.** One switch, `python_scripts_unrestricted`, off by default, decides how scripts are judged. Off, a
|
||||
script's own code is held to OrcaSlicer's folders and denied programs, threads and the network; on, it may do what
|
||||
the audit allows any plugin. The audit is a Python audit hook, not a sandbox: the tools a script calls run
|
||||
OrcaSlicer's own code and are not judged. Only a person changes the switch, in a dialog no tool reaches, and
|
||||
`app_state.python.scripts_unrestricted` tells an agent what its script may do.
|
||||
|
||||
The Run Script panel is a dock pane where a person runs a file, a `# %%` cell or a console line in a live session,
|
||||
which keeps its globals between pieces of work and is an unjournaled person's job. Its Stop interrupts the work now
|
||||
running while the session goes on; Restart session, opening or closing a script and quitting end the session as a
|
||||
stopped run ends.
|
||||
|
||||
## Plugins and the tools
|
||||
|
||||
A plugin's code calls the commands through `orca.host.tools` only with the tools permission or full access, asked for
|
||||
at load or when it first calls, as its other permissions are ("Calling OrcaSlicer's tools" in
|
||||
[plugin-permissions.md](plugin-permissions.md)). The tools run OrcaSlicer's own code, which the plugin audit doesn't
|
||||
judge, so a plugin's other grants bound its Python code and not what it asks the tools to do, and each call is logged
|
||||
with the plugin's key. A call runs as a job owned by the plugin, never journaled, so the session tools are scoped to the
|
||||
plugin, and what its calls leave behind ends when it unloads or loses the permission, from which moment its calls are
|
||||
refused; a call made before that leaves nothing behind for the client.
|
||||
|
||||
A plugin may offer operations, `plugin.<plugin>.<name>`, which `tool_list` lists and `tool_call`, scripts and replay
|
||||
steps run. They are a source of the command catalog, looked up after its own commands, and run as jobs under the
|
||||
plugin's identity, guarded and journaled as a change when the plugin declares one.
|
||||
|
||||
## Agent Activity pane
|
||||
|
||||
View › Agent Activity shows a dock pane that lists, live, every call automation makes in the app, reads included:
|
||||
an agent's, a replay's, a script's and a plugin's, with the dialogs auto-answer rules answered. A person's own picks
|
||||
are left out. Each call into the core names its origin, and `ActivityLog` (no wx) lists only while the pane is open.
|
||||
It masks what captions mask, and fails closed where masking can't be complete. The pane only watches.
|
||||
|
||||
## stdio bridge
|
||||
|
||||
`orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]` serves clients that speak only stdio. It forwards each
|
||||
message to the instance the discovery file names, and starts OrcaSlicer only for a tool call, so a session
|
||||
registered user-wide that never calls a tool never opens the app. Until an instance answers, it answers the handshake,
|
||||
`tools/list` and the rest itself from the same command catalog, with the server's exact replies, which needs a
|
||||
catalog built without the runtime, so registering a command never reads app state. A tool call with nothing
|
||||
answering starts `orca-slicer --mcp` and waits for it to be ready. If a running instance without MCP takes that
|
||||
launch over, each tool call says to turn the server on in Preferences, and a failed start is not tried again, so a
|
||||
stuck start never makes every call another launch. A request that could not be sent, or was refused because the
|
||||
token changed, is sent once more; one that lost its reply is never sent again, since it may have run. Every request
|
||||
has a deadline, so a server that never replies can't hang the agent.
|
||||
|
||||
## Making a feature reachable
|
||||
|
||||
A change to the GUI needs nothing for automation until someone writes its command: until then the GUI commands (GUI
|
||||
automation) reach it as a person does. A menu item of the Design tab is an entry of `tool_atlas.json` either way (A
|
||||
Design command, below).
|
||||
|
||||
A feature is a command, named for its place, then its verb (mcp-tools.md, Naming), declared in its place's file:
|
||||
|
||||
1. **Build it** with `inspect_tool()` for pure observation or `mutate_tool()` for a change, label it, give it a
|
||||
schema, a description in the order above and one to three examples. A new place word goes in `kPlaceWords`, and
|
||||
a new heading in `kHeadingOrder`.
|
||||
2. **Put what it does in an operation** of `GUI/Operations` and name it with `reaching()`, or join
|
||||
`test_operations`' exception list with a reason. The handler reads its arguments, resolves its targets, calls
|
||||
the operation and shapes the reply; all wx work is in `ctx.run_ui()`, and a change ends with `settle()`.
|
||||
3. **Make its menu items its actions** (`NativeCommands::action()`), with the arguments that pick the variant, and
|
||||
give the command its person's form. The call with arguments must not prompt.
|
||||
|
||||
The command then appears in `tools/list` or `tool_list`, `tool_describe`, the Speed Dial and replays. A new or
|
||||
changed command changes the command reference, `tests/data/command_catalog.json`, where a reader outside the app sees
|
||||
every command and which the skill's action list is written from (`tools/mcp/gen_skill_reference.py`). The test "the
|
||||
checked-in command reference matches the catalog" fails until it is regenerated: run
|
||||
`slic3rutils_tests "[Reference]"` with `ORCA_UPDATE_COMMAND_REFERENCE=1` and check the file in.
|
||||
|
||||
#### A Design command
|
||||
|
||||
A Design command is an entry of `scripts/CAD/tool_atlas.json` instead:
|
||||
|
||||
1. Name it by its place, then its verb (`solid_shell`), and add its entry under its heading: a menu item with its
|
||||
argument form (a `tool` block), a menu-only item, an argument-only command, or a folded variant of a command that
|
||||
exists.
|
||||
2. Wire a menu item's handler in `DesignPanel`, which the entry's `action` names.
|
||||
3. Run `scripts/CAD/gen_offer_table.py`, which writes `DesignOffer.hpp` and refuses a table that breaks its rules.
|
||||
4. Write its silent form in its heading's `Design<Heading>Tools.cpp` and bind it by id. A change an operation stands
|
||||
for goes through the operation, and several Prepare edits share one outer snapshot, so the call is one undo step.
|
||||
5. Update the counts and names `tests/slic3rutils/test_mcp_cad.cpp` pins, keep `tool_list`'s names index within 4096
|
||||
characters, and regenerate the command reference. A new heading also needs its file in `src/slic3r/CMakeLists.txt`
|
||||
and `localization/i18n/list.txt`.
|
||||
|
||||
## Configuration
|
||||
|
||||
- `--mcp` opens the endpoint at startup, and `--mcp-port N` on that port (0 takes the preference's).
|
||||
- `--mcp-stdio` runs the stdio bridge in place of the app.
|
||||
- `--run FILE` with `--outputdir DIR` runs a replay or a script (Replays and the journal).
|
||||
- `--unrestricted-scripts` lets scripts run unrestricted for the run, and `--cad` turns the Design tab on.
|
||||
|
||||
A flag turns its setting on for the run and never writes the configuration. AppConfig holds `mcp_enabled` (off) and
|
||||
`mcp_port` (13619). Preferences › General › AI features turns the server on, shows its port and address, and copies
|
||||
the setup for an agent (Claude Code, Codex, opencode and others). HTTP is the default, since its URL stays the same
|
||||
whichever build runs and nothing runs on the agent's side; the cost is that OrcaSlicer must be running with the
|
||||
server on, and a registration holds the token, so a new token or port means copying the setup again. Stdio suits an
|
||||
agent that should open OrcaSlicer on demand, and its setup names this executable, so it breaks when the program
|
||||
moves. `--run` beside a slicing action, where no GUI starts, is refused rather than left unrun.
|
||||
|
||||
## Testing
|
||||
|
||||
The wx-free core is tested by `automation_tests` (`tests/automation/`), which links nothing of the GUI library, so a
|
||||
wx include in a core unit fails to compile. What needs the GUI library is tested in `tests/slic3rutils/`
|
||||
(`slic3rutils_tests "[Mcp],[CommandCatalog],[Operations],[ImGuiWrapper]"`). `[CommandCatalog]` checks the catalog's
|
||||
rules, `[Reference]` the checked-in command reference, and `[Mcp][CAD]` the Design commands (design-tab.md,
|
||||
Verification); `tests/AGENTS.md` says where a new case goes.
|
||||
|
||||
End to end, the MCP sweep (`tools/mcp/run_sweep.py`) drives the built app through its server, as an agent does:
|
||||
[tools/mcp/TESTS.md](../../tools/mcp/TESTS.md) holds its rules and the index of its tests, and
|
||||
[tools/mcp/README.md](../../tools/mcp/README.md) says how to run it. No sweep test sends a print job or reaches a
|
||||
physical printer.
|
||||
1687
docs/HLSD/mcp-tools.md
Normal file
1687
docs/HLSD/mcp-tools.md
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -33,6 +33,7 @@ Permissions are stored per plugin key. A plugin can hold:
|
|||
| `threading` | boolean | Permission to start a Python thread with `_thread.start_new_thread`. |
|
||||
| `events` | target list | Audited events that expose no target, keyed as `<Category>:<event>`, for example `Socket:socket.__new__`. Matched verbatim. |
|
||||
| `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". |
|
||||
| `tools` | boolean | Permission to call OrcaSlicer's tools through `orca.host.tools`. See "Calling OrcaSlicer's tools". |
|
||||
|
||||
Create and delete grants are independent of read and read/write grants. An empty list grants
|
||||
no folders; an absolute folder path grants operations directly inside that folder, while a path
|
||||
|
|
@ -172,6 +173,22 @@ order:
|
|||
After a granted root event with a target, the hook records the operation frame so the
|
||||
nested events of the same operation are not asked again.
|
||||
|
||||
### Python scripts
|
||||
|
||||
A Python script run from the Run Script panel, with `--run` or by an agent's `script_run`
|
||||
is not a plugin, but its events are judged here under an identity of its own, `(script)` or `(mcp)`
|
||||
(see "Python scripts" in [mcp-server.md](mcp-server.md)). A script has no sidecar, so it holds
|
||||
no grant and is never asked: steps 1 to 3 apply to it, and any other event is denied with a
|
||||
`PermissionError` that names the setting below. A file run also reads the folder of its file,
|
||||
through a per-call scoped root.
|
||||
|
||||
The "Run Python scripts unrestricted" setting (`python_scripts_unrestricted`: Preferences, AI features,
|
||||
Python scripts; off by default) lifts this for every script, and so does the command line's
|
||||
`--unrestricted-scripts` for one run, without writing the setting: while either is on, a script's event
|
||||
is allowed right after step 1, so only the denied paths stay blocked. No plugin's key is a script identity: a
|
||||
local plugin's key keeps only the letters, digits, `_`, `-` and `.` of its file name, and a cloud plugin's is
|
||||
its UUID.
|
||||
|
||||
## Permission prompts
|
||||
|
||||
### Declared permissions during load
|
||||
|
|
@ -185,6 +202,8 @@ GUI-thread caller is rejected when another prompt is active instead of blocking
|
|||
Denying the request aborts the load. A readable sidecar with `full_access` accepts the
|
||||
declaration without a prompt and without adding a grant.
|
||||
|
||||
`request_permissions(tools=True)` is one more bucket of that combined prompt, as `threading=True` is.
|
||||
|
||||
Network URLs passed to `request_permissions(network=...)` are normalized to
|
||||
`scheme://host` before prompting or storing, so one approval covers every path and port
|
||||
on that host and also authorizes raw sockets to it. A relative filesystem tree grant is
|
||||
|
|
@ -196,7 +215,8 @@ sidecar show the absolute scope it covers.
|
|||
An event that is not covered by a saved grant or an implicit rule is either put to the
|
||||
user or denied. If the caller is on the wx main thread and no audit prompt is active, the
|
||||
modal runs inline. Otherwise, as on the Script workflow, the plugin-load worker, or the
|
||||
slicing worker, the current event is denied and the prompt is queued for the GUI thread.
|
||||
slicing worker, the current event is denied and the prompt is queued for the GUI thread. A
|
||||
plugin's tool call without the tools grant takes the same path from its Script worker.
|
||||
`AuditPromptQueue` serializes runtime prompts, one-time recursive-delete consent, and
|
||||
load-time declarations, so at most one is shown at a time,
|
||||
including during a modal dialog's nested event loop. An event raised inside that loop is
|
||||
|
|
@ -279,7 +299,7 @@ The following are denied before any allowed root or full-access check:
|
|||
|
||||
Grants and install state live in `.install_state.json` in the plugin root. The
|
||||
`permissions` object stores `fs_read`, `fs_readwrite`, `fs_create`, `fs_delete`, `network_http`,
|
||||
`network_socket`, `process`, `threading`, `events`, and `full_access`. It never stores a
|
||||
`network_socket`, `process`, `threading`, `tools`, `events`, and `full_access`. It never stores a
|
||||
recursive-delete consent: that approval and any retry approval are in memory only, so accepting
|
||||
one does not widen the plugin's saved delete scope. The file is
|
||||
written by `write_install_state`, the single writer for the sidecar schema. In-process
|
||||
|
|
@ -295,6 +315,7 @@ Reading is deliberately fail-closed:
|
|||
form. Reading never rewrites the file.
|
||||
- `full_access` is enabled only by an explicit JSON boolean. A missing key, a string, a
|
||||
number, or any other type reads as false.
|
||||
- `tools` is granted only by a JSON `true`; a missing key or any other value reads as `false`.
|
||||
|
||||
A sidecar that exists but cannot be read is never overwritten, because it may still hold
|
||||
grants and capability choices. The one exception is a plugin load: if the sidecar is a
|
||||
|
|
@ -343,8 +364,8 @@ lowercase `scheme://host`, dropping port, path, query and fragment. Bare hosts,
|
|||
schemes, wildcards and URLs carrying userinfo are refused rather than guessed. Network
|
||||
entries cover every port, path and query on the host.
|
||||
|
||||
The dialog warns before enabling full access. Grants stored
|
||||
while full access is on are inert and apply again when full access is off. Turning full access
|
||||
The dialog warns before enabling full access. The OrcaSlicer tools switch is a yes/no switch like
|
||||
Threading's. Grants stored while full access is on are inert and apply again when full access is off. Turning full access
|
||||
on does not delete the stored lists. A permission change affects subsequent audit decisions,
|
||||
not operations already authorized.
|
||||
|
||||
|
|
@ -353,6 +374,35 @@ On Linux and macOS, create and delete operations using a directory file descript
|
|||
against its resolved path. If that path cannot be resolved, the operation is denied, even with
|
||||
full access.
|
||||
|
||||
## Calling OrcaSlicer's tools
|
||||
|
||||
`orca.host.tools` lets a plugin call every command a plugin caller has: an agent's commands, less the few
|
||||
[mcp-tools.md](mcp-tools.md) refuses a plugin (`replay_export`) or limits to its own jobs. Through them it reaches
|
||||
the project, presets and files, post-processing scripts (which run as programs), the window, and its dialogs,
|
||||
permission requests included. A plugin holding it can therefore give itself any other permission,
|
||||
which is why its prompt says so. `orca.host.tools.list()` and `describe()` only read the
|
||||
catalog and need no permission, and operations a plugin offers with `orca.register_operation` stay
|
||||
free; a Python script a person or an agent runs is not a plugin and is unaffected.
|
||||
|
||||
The grant is `tools` true or full access, read from the sidecar on every call. A plugin's own call asks
|
||||
for it as an undeclared audited event does, on the plugin's Script worker before the call is admitted
|
||||
(`PluginAuditManager::request_tools_permission` in `admit_plugin_call`): without the grant the call is
|
||||
refused and the prompt queued (see "Runtime prompts"), and a Yes is saved, so the plugin's next call
|
||||
works. A sidecar that exists but cannot be read refuses the call without asking, as a declaration is refused,
|
||||
since a Yes could not be saved there. The admission on the UI thread checks the grant again without asking
|
||||
(`PluginManager::plugin_may_call_tools`), so a grant withdrawn in between cannot reopen the plugin's
|
||||
scope, and every call a plugin owns, its script and replay runs' children included, is checked again
|
||||
where the MCP core runs it (`JobRegistry::tools_refused` in `McpCore::run`). Each refuses with
|
||||
`orca.host.tools.ToolError`, `details["code"] == "tools_not_allowed"`.
|
||||
|
||||
When a Plugins-dialog edit leaves a plugin without the tools, `AutomationRuntime::plugin_tools_withdrawn`
|
||||
asks its running calls to stop and ends its scope and its running runs' scopes, popping their
|
||||
auto-answer rules, ending their recording and releasing their held presses, as an unload does, but
|
||||
without blocking it, so a later grant works without a reload. A call that passed its check just before
|
||||
is refused the moment it would leave such an effect behind: the plugin is marked withdrawn until a call
|
||||
admitted under a new grant opens its scope again, and the places that publish a press or start a
|
||||
recording check the scope is still open (`require_owner_scope`).
|
||||
|
||||
## Full access
|
||||
|
||||
Full access is a per-plugin boolean that turns off the permission decision. It does not
|
||||
|
|
@ -360,7 +410,8 @@ remove the audit hook. For recognized events it is reached after the uncondition
|
|||
denied-path check, so the application configuration, the cloud user-secret file,
|
||||
certificates, configuration paths, and `.install_state.json` stay blocked from direct
|
||||
Python access. Everything else that the audit hook recognizes is allowed without a grant
|
||||
or a prompt, and declared permissions are accepted without prompting. The read-only
|
||||
or a prompt, and declared permissions are accepted without prompting. It also allows the plugin's
|
||||
tool calls. The read-only
|
||||
`resources_dir()` root is a normal-mode restriction only: full access permits writes there
|
||||
when the operating system allows them. The denied `cert` keyword still blocks the bundled
|
||||
certificate.
|
||||
|
|
@ -405,7 +456,10 @@ never treated as an opt-out.
|
|||
- **Host APIs are not audit events.** Calls into OrcaSlicer's Python host APIs, such as
|
||||
preset updates or UI actions, execute C++ host code and follow that API's contract. The
|
||||
audit hook judges the Python-level filesystem, network, process and thread events it is
|
||||
given, not the host API's internal work.
|
||||
given, not the host API's internal work. `orca.host.tools` is gated by the tools permission
|
||||
instead (see "Calling OrcaSlicer's tools"), and once granted it reaches every command a plugin
|
||||
caller has: the files those tools write, post-processing scripts, and dialogs, permission
|
||||
prompts included.
|
||||
- **Denied paths are a direct-access block.** Path laundering through a symlink,
|
||||
hardlink, subprocess, or Windows 8.3 short name is outside the model. A tree grant is
|
||||
canonicalized for matching, but the deny check itself is base-name and component based.
|
||||
|
|
@ -461,7 +515,10 @@ never treated as an opt-out.
|
|||
- `src/slic3r/plugin/PluginManager.hpp` / `.cpp` - `mutate_plugin_permissions`,
|
||||
`revoke_plugin_permissions`, `get_install_state`.
|
||||
- `src/slic3r/GUI/PluginsDialog.cpp` - permission editor payloads, native confirmations,
|
||||
and the full-access request path.
|
||||
the full-access request path, the tools switch and its withdrawal call.
|
||||
- `src/slic3r/GUI/Mcp/McpPluginCaller.cpp`, `JobRegistry.hpp` / `.cpp`, `McpCore.cpp`,
|
||||
`AutomationRuntime.hpp` / `.cpp` - the tools checks (`admit_plugin_call`, `tools_refused`),
|
||||
`plugin_tools_withdrawn` and `require_owner_scope`.
|
||||
- `tests/slic3rutils/test_plugin_audit.cpp`, `tests/slic3rutils/test_plugin_install.cpp`,
|
||||
`tests/slic3rutils/test_plugin_lifecycle.cpp` - audit decision, sidecar, and permission
|
||||
mutation coverage.
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ presets are never serialized — they have their own storage and their own lifec
|
|||
| `resources/profiles/` | `<vendor>.opc` alone — the profile and its preset JSONs both pruned | What the app ships with and what installing copies from; read directly for vendors not installed |
|
||||
| `<data_dir>/system/` | `<vendor>.opc` alone, or `<vendor>.json` + `<vendor>/` after an update | What the user has installed |
|
||||
| `<data_dir>/system/` (dev build) | `<vendor>.json` + `<vendor>/` + `<vendor>.opc` written at runtime | A developer tree caches as it parses |
|
||||
| `<data_dir>/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard only; never shipped (see "The wizard's profile-data cache") |
|
||||
| `<data_dir>/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard and the commands that list and install printer models (`Ops::printer_profile_data()`); never shipped (see "The wizard's profile-data cache") |
|
||||
|
||||
Two forms of the same vendor therefore exist, and the system's central rule is that
|
||||
**a vendor's cache is the whole of it**. Where a cache ships or is installed, no profile
|
||||
|
|
@ -273,7 +273,9 @@ function of the vendor set: each vendor's name and version, in load order. A pro
|
|||
change requires a version bump, so name and version determine a vendor's content
|
||||
wherever its copy sits; which directory served it is deliberately **not** stamped,
|
||||
and installing or removing a copy at an unchanged version leaves the cache valid. So
|
||||
the wizard caches the *derived JSON*, not another form of the inputs:
|
||||
the wizard caches the *derived JSON*, not another form of the inputs
|
||||
(`Ops::printer_profile_data()`, `GUI/Operations/InstallOps.cpp`, which `printer_list_models`,
|
||||
`printer_install` and `printer_uninstall` read the catalog through too):
|
||||
`<data_dir>/cache/wizard_profile_data.json` holds the stamp list and the catalog. On
|
||||
open, the wizard computes the current stamps (one version peek per vendor) and, when
|
||||
they match, serves the catalog from the file — no bundle built, no preset installed.
|
||||
|
|
|
|||
|
|
@ -70,9 +70,10 @@ coroutine loop are described in
|
|||
- **Filament:** `slot_number` identifies the slot. If `preset_name` is omitted,
|
||||
the transaction targets the preset currently assigned to that slot. If supplied,
|
||||
it requests that preset for the slot and selects it through the normal UI flow;
|
||||
the name must be among the presets offered by that slot's dropdown, with one
|
||||
exception: the preset currently assigned to the slot stays targetable even when the
|
||||
slot's dropdown hides it (for example an incompatible-but-selected preset). Selecting
|
||||
the name must be among the presets offered by that slot's dropdown, with two
|
||||
exceptions: a hidden preset that suits the printer is shown in the selectors first,
|
||||
and the preset currently assigned to the slot stays targetable even when the
|
||||
slot's dropdown omits it (for example an incompatible-but-selected preset). Selecting
|
||||
a different preset changes the slot-to-preset mapping. In both cases the transaction
|
||||
edits the shared preset, not an isolated slot override.
|
||||
- **Process and printer:** omitting `preset_name` targets the currently active
|
||||
|
|
@ -80,6 +81,9 @@ coroutine loop are described in
|
|||
dropdown. It must be one of the choices the dropdown currently offers, rather
|
||||
than merely any preset present in the collection. This is particularly important
|
||||
for process presets, whose selectable choices can depend on the current context.
|
||||
A hidden preset that suits the printer (a system printer or filament the setup
|
||||
wizard has not added) is shown in the selectors first and stays shown until the
|
||||
app restarts.
|
||||
- A transaction targets exactly one preset. Multi-preset transactions are not
|
||||
supported: applying them would require switching among targets while the
|
||||
application has only one managed edited copy per collection.
|
||||
|
|
@ -216,21 +220,30 @@ undo decisions the user already accepted in an earlier dialog. Target resolution
|
|||
preserves those side effects and then verifies the resulting edited target.
|
||||
|
||||
Filament `preset_name` is an additional integration on top of `Tab::select_preset()`:
|
||||
selecting a different name for a slot also updates the slot-to-preset mapping and its
|
||||
dependent UI/configuration state, mirroring the filament branch of the Plater's normal
|
||||
selection path (`PresetBundle::set_filament_preset()` plus the project/selection refresh,
|
||||
the dynamic filament list, the conditional support-filament flushing recalc, the slot
|
||||
combo refresh and its AMS sync badge). A mixed-color virtual slot is not targetable.
|
||||
once the filament tab edits the preset, a different name for a slot is assigned to the
|
||||
slot by `GUI::Ops::assign_filament_preset()`, the operation the MCP `preset_select` command
|
||||
calls too (docs/HLSD/mcp-server.md, "The operations layer"). It does what picking the
|
||||
preset in the slot's sidebar selector does (`Sidebar::select_filament_preset()`): the
|
||||
slot's colour settings follow the preset, the slot-to-preset mapping, the dynamic
|
||||
filament list and the slot's AMS sync badge are updated, the flushing volumes are
|
||||
recalculated as the automatic calculation's setting says, the project is marked changed
|
||||
and every plate's slice result is invalidated. The tab is not switched a second time,
|
||||
which would ask again about changes the first switch transferred. A mixed-color virtual
|
||||
slot is not targetable.
|
||||
|
||||
Process and printer dropdown choices are constrained by visibility and compatibility,
|
||||
and compatibility may depend on the active context. Target resolution checks the tab
|
||||
and compatibility may depend on the active context. Target resolution
|
||||
(`GUI::Ops::resolve_preset()`, the rule the `preset_select` command resolves by, which
|
||||
words its refusals) checks the tab
|
||||
dropdown's actual items before the selection flow, so a target the user cannot pick
|
||||
fails without raising that flow's unsaved-edit prompt; a name two entries carry is
|
||||
rejected as ambiguous. A filament `preset_name` resolves against the requested slot's
|
||||
own sidebar selector rather than the tab's, so that slot's compatibility filter is the
|
||||
one that applies. A name the slot's dropdown does not show is rejected unless it names
|
||||
that slot's current assignment (a hidden or incompatible-but-selected preset), which
|
||||
stays targetable.
|
||||
rejected as ambiguous. A hidden preset that suits the printer is shown in the
|
||||
selectors first, as for the command, and a process or printer selection that leaves
|
||||
another preset edited is refused by `GUI::Ops::select_preset()`. A filament
|
||||
`preset_name` resolves against the requested slot's own sidebar selector rather than
|
||||
the tab's, so that slot's compatibility filter is the one that applies. A name the
|
||||
slot's dropdown still does not show is rejected unless it names that slot's current
|
||||
assignment (an incompatible-but-selected preset), which stays targetable.
|
||||
|
||||
`commit()` applies its batch through `Tab::apply_preset_config_values`, which parses and
|
||||
validates the whole batch before touching the edited preset and restores the edited
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ can be pasted into an issue.
|
|||
## What it does
|
||||
|
||||
`run_scene_benchmark()` in `src/slic3r/GUI/SceneBenchmark.cpp` is reached from Help >
|
||||
Benchmark 3D Scene, the command palette and Preferences > Graphics. After a confirmation
|
||||
Benchmark 3D Scene, the Speed Dial and Preferences > Graphics. After a confirmation
|
||||
it starts a new project, which asks to save the current one if needed, loads the
|
||||
OrcaSliced Combo handy model and arranges it. A small dialog in a corner of the 3D view
|
||||
then shows the progress; every other window is disabled until the run ends, so a click
|
||||
|
|
|
|||
|
|
@ -127,6 +127,8 @@ src/slic3r/GUI/Jobs/SLAImportJob.cpp
|
|||
src/slic3r/GUI/Jobs/UpgradeNetworkJob.cpp
|
||||
src/slic3r/GUI/AboutDialog.cpp
|
||||
src/slic3r/GUI/ActionRegistry.cpp
|
||||
src/slic3r/GUI/ActionReplayDialog.cpp
|
||||
src/slic3r/GUI/AgentActivityPanel.cpp
|
||||
src/slic3r/GUI/AMSMaterialsSetting.cpp
|
||||
src/slic3r/GUI/ExtrusionCalibration.cpp
|
||||
src/slic3r/GUI/AmsMappingPopup.cpp
|
||||
|
|
@ -152,6 +154,32 @@ src/slic3r/GUI/CameraPopup.cpp
|
|||
src/slic3r/GUI/ConnectPrinter.cpp
|
||||
src/slic3r/GUI/HMSPanel.cpp
|
||||
src/slic3r/GUI/MainFrame.cpp
|
||||
src/slic3r/GUI/Mcp/McpPersonContext.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/AppTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/CatalogTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignBodyTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignConstructTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignHistoryTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignInspectTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignSketchTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignSolidTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignSurfaceTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/DesignTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/FilamentTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/GuiTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/ObjectTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/PlateTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/PluginTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/PresetTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/PrinterTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/ProjectTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/RecordingTools.cpp
|
||||
src/slic3r/GUI/Mcp/Tools/ViewTools.cpp
|
||||
src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp
|
||||
src/slic3r/GUI/Mcp/RecordingSettings.cpp
|
||||
src/slic3r/GUI/RecordingDialog.cpp
|
||||
src/slic3r/GUI/RecordingIndicator.cpp
|
||||
src/slic3r/GUI/RunScriptPanel.cpp
|
||||
src/slic3r/GUI/MediaPlayCtrl.cpp
|
||||
src/slic3r/GUI/MediaFilePanel.cpp
|
||||
src/slic3r/GUI/ImageGrid.cpp
|
||||
|
|
@ -167,6 +195,16 @@ src/slic3r/GUI/NotificationManager.hpp
|
|||
src/slic3r/GUI/NotificationManager.cpp
|
||||
src/slic3r/GUI/ObjectDataViewModel.cpp
|
||||
src/slic3r/GUI/OpenGLManager.cpp
|
||||
src/slic3r/GUI/Operations/ExportOps.cpp
|
||||
src/slic3r/GUI/Operations/InstallOps.cpp
|
||||
src/slic3r/GUI/Operations/GizmoOps.cpp
|
||||
src/slic3r/GUI/Operations/ObjectOps.cpp
|
||||
src/slic3r/GUI/Operations/PlateOps.cpp
|
||||
src/slic3r/GUI/Operations/PluginOps.cpp
|
||||
src/slic3r/GUI/Operations/PreferenceOps.cpp
|
||||
src/slic3r/GUI/Operations/PresetOps.cpp
|
||||
src/slic3r/GUI/Operations/PrinterOps.cpp
|
||||
src/slic3r/GUI/Operations/ProjectOps.cpp
|
||||
src/slic3r/GUI/OptionsGroup.cpp
|
||||
src/slic3r/GUI/OptionStateRegistry.cpp
|
||||
src/slic3r/GUI/PrintOptionsDialog.cpp
|
||||
|
|
@ -398,3 +436,4 @@ src/slic3r/GUI/PostProcessor.cpp
|
|||
src/slic3r/GUI/TaskManager.cpp
|
||||
src/slic3r/GUI/Widgets/ProgressDialog.hpp
|
||||
src/slic3r/GUI/Widgets/StepCtrl.cpp
|
||||
src/slic3r/GUI/Widgets/WebViewHostDialog.cpp
|
||||
|
|
|
|||
1
resources/images/recording_start.svg
Normal file
1
resources/images/recording_start.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="7.5" cy="7.5" r="7" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/><circle cx="7.5" cy="7.5" r="3.5" style="fill:#f04438"/></svg>
|
||||
|
After Width: | Height: | Size: 255 B |
1
resources/images/recording_stop.svg
Normal file
1
resources/images/recording_stop.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><circle cx="7.5" cy="7.5" r="7" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/><rect x="4.5" y="4.5" width="6" height="6" rx="1" style="fill:#f04438"/></svg>
|
||||
|
After Width: | Height: | Size: 271 B |
1
resources/images/screenshot.svg
Normal file
1
resources/images/screenshot.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M1.5,3.5H4l1.5-2h4l1.5,2h2.5a1,1,0,0,1,1,1v8a1,1,0,0,1-1,1H1.5a1,1,0,0,1-1-1v-8A1,1,0,0,1,1.5,3.5Z" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/><circle cx="7.5" cy="8.5" r="3" style="fill:none;stroke:#009688;stroke-linecap:round;stroke-linejoin:round"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
597
resources/web/dialog/ActionReplay/action_replay.js
Normal file
597
resources/web/dialog/ActionReplay/action_replay.js
Normal file
|
|
@ -0,0 +1,597 @@
|
|||
// Action Replay page. The host (ActionReplayDialog) parses, describes and replays replay files and words what
|
||||
// it reports; this page shows the steps as a rail that fills in as the replay runs, and asks.
|
||||
|
||||
const FLAG_LABELS = {
|
||||
writes_file: ["flag_writes_file", "Writes a file"],
|
||||
changes_presets: ["flag_changes_presets", "Changes presets"],
|
||||
replaces_project: ["flag_replaces_project", "Replaces the project"],
|
||||
sends_to_printer: ["flag_sends_to_printer", "Sends to a printer"],
|
||||
runs_program: ["flag_runs_program", "Can run a program"],
|
||||
};
|
||||
|
||||
const state = {
|
||||
ready: false,
|
||||
fileName: "", // the file the replay was opened from or saved to; empty for a new replay
|
||||
savedText: "", // the text as opened or last saved (for a new replay, its draft), to tell when it's edited
|
||||
name: "", // the replay's name, as last parsed
|
||||
parseSeq: 0,
|
||||
parseTimer: 0,
|
||||
parsed: null, // the host's last description: {ok, error, name, steps, count_text}
|
||||
steps: [], // the steps of the last text that parsed, shown while later text doesn't
|
||||
stale: false, // the text has changed since the host described it; Run waits for the new description
|
||||
pending: false, // Run was pressed and the host hasn't started or refused the run yet
|
||||
running: false,
|
||||
single: null, // the step of a single-step run
|
||||
total: 0,
|
||||
started: new Map(), // step index -> start time of a running step
|
||||
results: new Map(), // step index -> what the host reported when it finished
|
||||
skipped: new Set(),
|
||||
open: new Set(), // step indexes opened to their details
|
||||
outcome: null, // the last run's {kind, text, detail}
|
||||
outDir: "",
|
||||
hasRun: false,
|
||||
message: null, // a refusal or error to show in the footer: {kind, text, detail}
|
||||
};
|
||||
|
||||
const rows = new Map(); // step index -> its <li>
|
||||
let ticker = 0;
|
||||
let savedTimer = 0;
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
|
||||
function send(command, extra) {
|
||||
SendWXMessage(JSON.stringify(Object.assign({ command }, extra || {})));
|
||||
}
|
||||
|
||||
function el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined && text !== null) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
function seconds(ms) { return T("seconds", "%s s", (ms / 1000).toFixed(1)); }
|
||||
|
||||
// ---- source -----------------------------------------------------------------------------------
|
||||
|
||||
function sourceText() { return ed.editor.getValue(); }
|
||||
|
||||
function scheduleParse(delay) {
|
||||
clearTimeout(state.parseTimer);
|
||||
// Numbered now, so a description of the text before this change is not taken for this one.
|
||||
const seq = ++state.parseSeq;
|
||||
state.stale = true;
|
||||
state.parseTimer = setTimeout(() => {
|
||||
// Asked again once the automation runtime is ready (HandleStudio's "runtime").
|
||||
if (!state.ready) return;
|
||||
if (!sourceText().trim()) {
|
||||
onParsed({ seq, ok: false, empty: true });
|
||||
return;
|
||||
}
|
||||
send("parse", { seq });
|
||||
}, delay);
|
||||
}
|
||||
|
||||
// What the editor holds when the dialog opens: a replay that runs as it is, with comments on the format.
|
||||
function draftReplay() {
|
||||
return [
|
||||
"// " + T("draft_about", "A replay file runs OrcaSlicer's tools in order, the way an AI agent does through MCP."),
|
||||
"// " + T("draft_steps", "Each step names a \"tool\" and its \"args\"; \"expect\" checks the result before the next step."),
|
||||
"// " + T("draft_out_dir", "%s is this run's output folder.", "${out_dir}"),
|
||||
"// " + T("draft_keys", "%s shows suggestions, %s replays the file.", T("key_suggest", "Ctrl+Space"), T("key_run", "Ctrl+Enter")),
|
||||
"{",
|
||||
' "orca_replay_version": ' + JSON.stringify(REPLAY_VERSION) + ",",
|
||||
' "name": ' + JSON.stringify(T("untitled_replay", "Untitled replay")) + ",",
|
||||
' "steps": [',
|
||||
' {"tool": "app_wait", "args": {"for": "ready"}},',
|
||||
' {"tool": "plate_add"},',
|
||||
' {"tool": "object_add_handy_model", "args": {"model": "orca_cube"}},',
|
||||
' {"tool": "object_center"},',
|
||||
' {"tool": "plate_slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}},',
|
||||
' {"tool": "window_screenshot",',
|
||||
' "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}}',
|
||||
" ]",
|
||||
"}",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// A new source: the dialog's draft or an opened file, unedited, read from the top, with no run of it yet
|
||||
// and no steps until the host describes it.
|
||||
function setSource(text) {
|
||||
closeEditorSuggestions(ed.editor);
|
||||
setEditorText(ed.editor, text);
|
||||
// As the editor holds it: its line breaks are LF whatever the file has.
|
||||
state.savedText = sourceText();
|
||||
state.outDir = "";
|
||||
state.parsed = null;
|
||||
state.steps = [];
|
||||
state.name = "";
|
||||
resetRun();
|
||||
buildRail();
|
||||
reportEdit();
|
||||
scheduleParse(0);
|
||||
render();
|
||||
}
|
||||
|
||||
function onSource(msg) {
|
||||
state.fileName = msg.file_name;
|
||||
setSource(msg.text);
|
||||
}
|
||||
|
||||
function onSourceInput() {
|
||||
reportEdit();
|
||||
scheduleParse(250);
|
||||
render();
|
||||
}
|
||||
|
||||
function renderChip() {
|
||||
$("chip-name").textContent = state.fileName || state.name || T("untitled_replay", "Untitled replay");
|
||||
$("chip-edited").hidden = !(state.fileName && edited());
|
||||
}
|
||||
|
||||
// ---- saving -------------------------------------------------------------------------------------
|
||||
|
||||
function edited() { return sourceText() !== state.savedText; }
|
||||
|
||||
// The host keeps the text and whether it's edited, to parse, run and save it and to ask before closing or
|
||||
// replacing it.
|
||||
function reportEdit() { send("edit", { text: sourceText(), edited: edited() }); }
|
||||
|
||||
// Save writes an opened or saved replay back to its file and asks where to put a new one; Save as
|
||||
// (`pick`) asks where to put a copy.
|
||||
function save(pick) {
|
||||
const button = pick ? $("save-as") : $("save");
|
||||
if (!button.hidden && !button.disabled) send("save", { pick });
|
||||
}
|
||||
|
||||
function onSaved(msg) {
|
||||
state.fileName = msg.file_name;
|
||||
state.savedText = msg.text;
|
||||
reportEdit();
|
||||
showSaved();
|
||||
// Saved somewhere new, the replay is that file's: its steps are described again with the file's
|
||||
// folders, and the last run's output folder belongs to the replay as it was.
|
||||
if (msg.moved) {
|
||||
state.outDir = "";
|
||||
resetRun();
|
||||
scheduleParse(0);
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
function showSaved() {
|
||||
const note = $("save-note");
|
||||
clearTimeout(savedTimer);
|
||||
note.classList.remove("is-fading");
|
||||
note.hidden = false;
|
||||
savedTimer = setTimeout(() => {
|
||||
note.classList.add("is-fading");
|
||||
savedTimer = setTimeout(() => { note.hidden = true; }, 400);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function renderSave() {
|
||||
const button = $("save");
|
||||
button.textContent = state.fileName ? T("save", "Save") : T("save_new", "Save…");
|
||||
button.disabled = busy() || (!!state.fileName && !edited());
|
||||
$("save-as").hidden = !state.fileName;
|
||||
$("save-as").disabled = busy();
|
||||
if (edited()) {
|
||||
clearTimeout(savedTimer);
|
||||
$("save-note").hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- sections ---------------------------------------------------------------------------------
|
||||
|
||||
function setSectionOpen(id, open) {
|
||||
const section = $(id);
|
||||
section.classList.toggle("is-open", open);
|
||||
const head = section.querySelector(".section-head");
|
||||
head.setAttribute("aria-expanded", String(open));
|
||||
$(head.getAttribute("aria-controls")).hidden = !open;
|
||||
}
|
||||
|
||||
function toggleSection(id) { setSectionOpen(id, !$(id).classList.contains("is-open")); }
|
||||
|
||||
// ---- the step list ----------------------------------------------------------------------------
|
||||
|
||||
function onParsed(msg) {
|
||||
if (msg.seq !== state.parseSeq) return; // an answer to text that has changed since
|
||||
// Run waits for the latest description and the text is frozen from the click on, so no answer can
|
||||
// arrive for a run's replay; none may reset a run's log either way.
|
||||
if (busy()) return;
|
||||
state.stale = false;
|
||||
state.parsed = msg;
|
||||
resetRun();
|
||||
// A replay that doesn't parse keeps the last steps that did, faded, so typing doesn't empty the list.
|
||||
if (msg.ok || msg.empty) {
|
||||
state.steps = msg.ok ? msg.steps : [];
|
||||
buildRail();
|
||||
}
|
||||
if (msg.ok) state.name = msg.name || "";
|
||||
render();
|
||||
}
|
||||
|
||||
function resetRun() {
|
||||
state.results.clear();
|
||||
state.skipped.clear();
|
||||
state.started.clear();
|
||||
state.open.clear();
|
||||
state.outcome = null;
|
||||
state.message = null;
|
||||
state.hasRun = false;
|
||||
}
|
||||
|
||||
function buildRail() {
|
||||
const rail = $("steps");
|
||||
rail.textContent = "";
|
||||
rows.clear();
|
||||
for (const step of state.steps) {
|
||||
const row = makeRow(step);
|
||||
rows.set(step.index, row);
|
||||
rail.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
function makeRow(step) {
|
||||
const row = el("li", "step is-wait");
|
||||
row.dataset.index = step.index;
|
||||
|
||||
row.appendChild(el("span", "dot", String(step.index)));
|
||||
|
||||
const main = el("div", "step-main");
|
||||
const head = el("button", "step-head");
|
||||
head.type = "button";
|
||||
head.setAttribute("aria-expanded", "false");
|
||||
head.appendChild(el("span", "step-title", step.title));
|
||||
if (step.what_text) head.appendChild(el("span", "step-what", step.what_text));
|
||||
if (step.args_text) head.appendChild(el("span", "step-args", step.args_text));
|
||||
const tags = el("span", "step-tags");
|
||||
for (const id of step.flags || []) {
|
||||
const label = FLAG_LABELS[id];
|
||||
if (label) tags.appendChild(el("span", "tag", T(label[0], label[1])));
|
||||
}
|
||||
if (step.checks_result) tags.appendChild(el("span", "tag is-check", T("checks_result", "Checks the result")));
|
||||
if (tags.childNodes.length) head.appendChild(tags);
|
||||
head.addEventListener("click", () => toggleStep(step.index));
|
||||
main.appendChild(head);
|
||||
|
||||
const detail = el("div", "step-detail");
|
||||
detail.hidden = true;
|
||||
main.appendChild(detail);
|
||||
row.appendChild(main);
|
||||
|
||||
const side = el("div", "step-side");
|
||||
side.appendChild(el("span", "time"));
|
||||
const play = el("button", "play", "▷");
|
||||
play.type = "button";
|
||||
play.title = T("run_this_step", "Run this step");
|
||||
play.setAttribute("aria-label", play.title);
|
||||
play.addEventListener("click", () => runStep(step.index));
|
||||
side.appendChild(play);
|
||||
row.appendChild(side);
|
||||
return row;
|
||||
}
|
||||
|
||||
function stepOf(index) { return state.steps.find((s) => s.index === index); }
|
||||
|
||||
function toggleStep(index) {
|
||||
if (state.open.has(index)) state.open.delete(index);
|
||||
else state.open.add(index);
|
||||
renderRow(index);
|
||||
}
|
||||
|
||||
function renderRow(index) {
|
||||
const row = rows.get(index);
|
||||
const step = stepOf(index);
|
||||
if (!row || !step) return;
|
||||
const result = state.results.get(index);
|
||||
let status = "wait";
|
||||
if (state.started.has(index)) status = "running";
|
||||
else if (result) status = result.cancelled ? "stopped" : !result.ok ? "fail" : result.warning_text ? "warn" : "done";
|
||||
else if (state.skipped.has(index)) status = "skip";
|
||||
row.className = "step is-" + status + (state.open.has(index) ? " is-open" : "");
|
||||
|
||||
const dot = row.querySelector(".dot");
|
||||
dot.textContent = status === "done" ? "✓" : status === "fail" || status === "stopped" || status === "warn" ? "!" : String(index);
|
||||
|
||||
const time = row.querySelector(".time");
|
||||
if (status === "running") time.textContent = seconds(Date.now() - state.started.get(index));
|
||||
else if (result) time.textContent = seconds(result.duration_ms || 0);
|
||||
else if (status === "skip") time.textContent = T("skipped", "Skipped");
|
||||
else time.textContent = "";
|
||||
|
||||
row.querySelector(".play").disabled = !canRun();
|
||||
const head = row.querySelector(".step-head");
|
||||
head.setAttribute("aria-expanded", String(state.open.has(index)));
|
||||
const detail = row.querySelector(".step-detail");
|
||||
detail.hidden = !state.open.has(index);
|
||||
if (!detail.hidden) fillDetail(detail, step, result);
|
||||
}
|
||||
|
||||
function fillDetail(detail, step, result) {
|
||||
detail.textContent = "";
|
||||
const args = step.args || {};
|
||||
const keys = Object.keys(args);
|
||||
if (keys.length) {
|
||||
const dl = el("dl", "args");
|
||||
for (const key of keys) {
|
||||
dl.appendChild(el("dt", "", key));
|
||||
const value = args[key];
|
||||
dl.appendChild(el("dd", "", typeof value === "string" ? value : JSON.stringify(value)));
|
||||
}
|
||||
detail.appendChild(dl);
|
||||
}
|
||||
if (step.checks && step.checks.length) {
|
||||
// A failed check is told in the failure box; after a pass, each one is marked as met.
|
||||
const checks = el("ul", "checks");
|
||||
for (const text of step.checks) checks.appendChild(el("li", result && result.ok ? "is-met" : "", text));
|
||||
detail.appendChild(checks);
|
||||
}
|
||||
if (result) {
|
||||
const problem = result.failure_text || result.warning_text;
|
||||
if (problem) {
|
||||
const box = el("div", "failure", problem);
|
||||
const more = result.failure_detail || result.warning_detail;
|
||||
if (more) box.appendChild(el("span", "failure-detail", more));
|
||||
detail.appendChild(box);
|
||||
}
|
||||
for (const line of result.result_lines || []) detail.appendChild(el("div", "result-line", line));
|
||||
if (result.thumbnail || (result.files && result.files.length)) {
|
||||
const files = el("div", "files");
|
||||
if (result.thumbnail && result.files && result.files.length) {
|
||||
const img = el("img", "thumb");
|
||||
img.src = result.thumbnail;
|
||||
img.alt = result.files[0].name;
|
||||
img.addEventListener("click", () => send("open_image", { path: result.files[0].path }));
|
||||
files.appendChild(img);
|
||||
}
|
||||
for (const file of result.files || []) {
|
||||
const link = el("button", "link", file.name);
|
||||
link.type = "button";
|
||||
link.title = T("show_in_folder", "Show in folder");
|
||||
link.addEventListener("click", () => send("open_location", { path: file.path }));
|
||||
files.appendChild(link);
|
||||
}
|
||||
detail.appendChild(files);
|
||||
}
|
||||
}
|
||||
const actions = el("div", "actions");
|
||||
const run = el("button", "btn small", "▷ " + T("run_this_step", "Run this step"));
|
||||
run.type = "button";
|
||||
run.disabled = !canRun();
|
||||
run.addEventListener("click", () => runStep(step.index));
|
||||
actions.appendChild(run);
|
||||
if (result && result.raw) {
|
||||
const raw = el("pre", "raw", JSON.stringify(result.raw, null, 2));
|
||||
raw.hidden = true;
|
||||
const toggle = el("button", "link", T("show_raw", "Show raw result"));
|
||||
toggle.type = "button";
|
||||
toggle.addEventListener("click", () => {
|
||||
raw.hidden = !raw.hidden;
|
||||
toggle.textContent = raw.hidden ? T("show_raw", "Show raw result") : T("hide_raw", "Hide raw result");
|
||||
});
|
||||
actions.appendChild(toggle);
|
||||
detail.appendChild(actions);
|
||||
detail.appendChild(raw);
|
||||
} else {
|
||||
detail.appendChild(actions);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- running ----------------------------------------------------------------------------------
|
||||
|
||||
function busy() { return state.pending || state.running; }
|
||||
|
||||
function canRun() { return state.ready && !busy() && !state.stale && state.parsed && state.parsed.ok; }
|
||||
|
||||
function requestRun(extra) {
|
||||
if (!canRun()) return;
|
||||
// Frozen at once: the host may ask about unsaved changes first, and the replay must not change meanwhile.
|
||||
state.pending = true;
|
||||
send("run", extra);
|
||||
render();
|
||||
}
|
||||
|
||||
function runAll() { requestRun({}); }
|
||||
|
||||
function runStep(index) { requestRun({ step: index }); }
|
||||
|
||||
function onRunStarted(msg) {
|
||||
state.pending = false;
|
||||
state.running = true;
|
||||
state.single = msg.step || null;
|
||||
state.total = state.parsed && state.parsed.ok ? state.parsed.steps.length : 0;
|
||||
state.message = null;
|
||||
if (state.single) {
|
||||
state.results.delete(state.single);
|
||||
state.skipped.delete(state.single);
|
||||
} else {
|
||||
state.results.clear();
|
||||
state.skipped.clear();
|
||||
state.outcome = null;
|
||||
}
|
||||
clearInterval(ticker);
|
||||
ticker = setInterval(() => state.started.forEach((_, index) => renderRow(index)), 200);
|
||||
render();
|
||||
}
|
||||
|
||||
function onStepStarted(msg) {
|
||||
state.started.set(msg.index, Date.now());
|
||||
renderRow(msg.index);
|
||||
renderFooter();
|
||||
const row = rows.get(msg.index);
|
||||
if (row) row.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
|
||||
function onStepFinished(msg) {
|
||||
state.started.delete(msg.index);
|
||||
state.results.set(msg.index, msg);
|
||||
if (!msg.ok || msg.warning_text) state.open.add(msg.index);
|
||||
renderRow(msg.index);
|
||||
}
|
||||
|
||||
function onRunFinished(msg) {
|
||||
state.pending = false;
|
||||
state.running = false;
|
||||
state.started.clear();
|
||||
clearInterval(ticker);
|
||||
state.outDir = msg.out_dir || state.outDir;
|
||||
if (!msg.single) {
|
||||
state.hasRun = true;
|
||||
// A run that ended early leaves the steps after it unrun.
|
||||
if (!msg.passed && state.parsed && state.parsed.ok)
|
||||
for (const step of state.parsed.steps)
|
||||
if (!state.results.has(step.index)) state.skipped.add(step.index);
|
||||
}
|
||||
if (msg.outcome_text) state.outcome = { kind: msg.outcome_kind, text: msg.outcome_text, detail: msg.error_detail || "" };
|
||||
render();
|
||||
}
|
||||
|
||||
function onRunRefused(msg) {
|
||||
state.pending = false;
|
||||
state.running = false;
|
||||
clearInterval(ticker);
|
||||
state.message = msg.message ? { kind: "fail", text: msg.message, detail: msg.detail || "" } : null;
|
||||
render();
|
||||
}
|
||||
|
||||
// ---- footer and header --------------------------------------------------------------------------
|
||||
|
||||
function render() {
|
||||
const hasRows = rows.size > 0;
|
||||
$("steps").hidden = !hasRows;
|
||||
$("steps").classList.toggle("is-stale", !!(state.parsed && !state.parsed.ok));
|
||||
$("steps-hint").hidden = hasRows;
|
||||
renderChip();
|
||||
renderSave();
|
||||
rows.forEach((_, index) => renderRow(index));
|
||||
renderSummary();
|
||||
renderFooter();
|
||||
|
||||
$("open-file").disabled = busy();
|
||||
ed.editor.setReadOnly(busy());
|
||||
$("editor").classList.toggle("is-readonly", busy());
|
||||
if (busy()) closeEditorSuggestions(ed.editor);
|
||||
}
|
||||
|
||||
function runningText() {
|
||||
const index = [...state.started.keys()].pop() || state.single || state.results.size + 1;
|
||||
return state.single ? T("running_one", "Running step %s", index) : T("running_step", "Running step %s of %s", index, state.total);
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
const summary = $("steps-summary");
|
||||
summary.classList.remove("is-error");
|
||||
if (state.running) summary.textContent = runningText();
|
||||
else if (state.outcome) summary.textContent = state.outcome.text;
|
||||
else if (state.parsed && state.parsed.ok) summary.textContent = state.parsed.count_text || "";
|
||||
else if (state.parsed && !state.parsed.empty && state.parsed.error) {
|
||||
summary.textContent = state.parsed.error;
|
||||
// Over faded steps the reason stays quiet while the replay is being written.
|
||||
summary.classList.toggle("is-error", rows.size === 0);
|
||||
} else summary.textContent = "";
|
||||
summary.title = summary.textContent;
|
||||
}
|
||||
|
||||
function renderFooter() {
|
||||
const outcome = $("outcome");
|
||||
const detail = $("outcome-detail");
|
||||
let shown = null;
|
||||
if (!state.ready) shown = { kind: "quiet", text: T("starting", "OrcaSlicer is still starting…"), detail: "" };
|
||||
else if (state.running) shown = { kind: "quiet", text: runningText(), detail: T("hands_off", "Don't use OrcaSlicer until the replay finishes.") };
|
||||
else if (state.message) shown = state.message;
|
||||
else if (state.outcome) shown = state.outcome;
|
||||
outcome.className = shown ? "is-" + shown.kind : "";
|
||||
outcome.textContent = shown ? shown.text : "";
|
||||
detail.textContent = shown ? shown.detail : "";
|
||||
detail.title = detail.textContent;
|
||||
|
||||
$("run").hidden = state.running;
|
||||
$("run").disabled = !canRun();
|
||||
$("run").textContent = state.hasRun ? T("run_again", "Replay again") : T("run", "Replay");
|
||||
$("stop").hidden = !state.running;
|
||||
$("open-output").hidden = state.running || !state.outDir;
|
||||
renderSummary();
|
||||
}
|
||||
|
||||
// ---- host messages ------------------------------------------------------------------------------
|
||||
|
||||
function HandleStudio(msg) {
|
||||
switch (msg.command) {
|
||||
case "runtime": {
|
||||
const was = state.ready;
|
||||
state.ready = !!msg.ready;
|
||||
if (msg.tools) setEditorTools(msg.tools);
|
||||
// A replay parsed while the automation runtime was starting got only "still starting" back.
|
||||
if (state.ready && !was && !busy()) scheduleParse(0);
|
||||
render();
|
||||
break;
|
||||
}
|
||||
case "source": onSource(msg); break;
|
||||
case "saved": onSaved(msg); break;
|
||||
case "parsed": onParsed(msg); break;
|
||||
case "run_started": onRunStarted(msg); break;
|
||||
case "step_started": onStepStarted(msg); break;
|
||||
case "step_finished": onStepFinished(msg); break;
|
||||
case "run_finished": onRunFinished(msg); break;
|
||||
case "run_refused": onRunRefused(msg); break;
|
||||
case "key": onKey(msg.action); break;
|
||||
case "error":
|
||||
state.pending = false;
|
||||
state.message = { kind: "fail", text: msg.message, detail: "" };
|
||||
render();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// A key the host forwards from its menus while this window has the focus: Save and Save as as the buttons save, the
|
||||
// editing actions through runEditorAction(), so one press acts once.
|
||||
function onKey(action) {
|
||||
if (action === "save" || action === "save_as") {
|
||||
if (!ownKeyRan(ed.editor, action === "save" ? "save" : "saveAs")) save(action === "save_as");
|
||||
} else
|
||||
runEditorAction(ed.editor, action);
|
||||
}
|
||||
|
||||
// Ctrl/Cmd+Enter replays, Ctrl/Cmd+S saves and with Shift saves as: in the editor as its commands, elsewhere on the page
|
||||
// through the document's key handler.
|
||||
const PAGE_COMMANDS = [
|
||||
{ name: "replay", bindKey: { win: "Ctrl-Return", mac: "Command-Return" }, exec: () => runAll(), readOnly: true },
|
||||
{ name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S" }, exec: () => save(false), readOnly: true },
|
||||
{ name: "saveAs", bindKey: { win: "Ctrl-Shift-S", mac: "Command-Shift-S" }, exec: () => save(true), readOnly: true },
|
||||
];
|
||||
|
||||
function OnInit() {
|
||||
TranslatePage();
|
||||
initEditor(onSourceInput, PAGE_COMMANDS);
|
||||
$("open-file").addEventListener("click", () => send("open_file"));
|
||||
$("save").addEventListener("click", () => save(false));
|
||||
$("save-as").addEventListener("click", () => save(true));
|
||||
$("save").title = T("key_save", "Ctrl+S");
|
||||
$("save-as").title = T("key_save_as", "Ctrl+Shift+S");
|
||||
$("run").addEventListener("click", runAll);
|
||||
$("stop").addEventListener("click", () => send("stop"));
|
||||
$("close").addEventListener("click", () => send("close_page"));
|
||||
$("open-output").addEventListener("click", () => send("open_output"));
|
||||
for (const id of ["steps-section", "source-section"])
|
||||
$(id).querySelector(".section-head").addEventListener("click", () => toggleSection(id));
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (!(e.ctrlKey || e.metaKey) || e.altKey) return;
|
||||
if (e.key.toLowerCase() === "s") {
|
||||
e.preventDefault();
|
||||
// Recorded as the editor's own Save, so the host's forwarded one for this press does nothing more.
|
||||
ed.editor.$orcaOwnAt[e.shiftKey ? "saveAs" : "save"] = Date.now();
|
||||
save(e.shiftKey);
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
runAll();
|
||||
}
|
||||
});
|
||||
setSource(draftReplay());
|
||||
send("init");
|
||||
// The keys the editor takes, which the host keeps from its menus while this window has the focus.
|
||||
send("editor_keys", { chords: editorChords(ed.editor) });
|
||||
}
|
||||
77
resources/web/dialog/ActionReplay/index.html
Normal file
77
resources/web/dialog/ActionReplay/index.html
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Action Replay</title>
|
||||
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../js/code_editor.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../css/step_rail.css" />
|
||||
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||
<script type="text/javascript" src="../../include/i18n.js"></script>
|
||||
<script type="text/javascript" src="../js/globalapi.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ace.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ext-language_tools.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ext-searchbox.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/mode-json.js"></script>
|
||||
<script type="text/javascript" src="../js/code_editor.js"></script>
|
||||
<script type="text/javascript" src="./replay_editor.js"></script>
|
||||
<script type="text/javascript" src="./action_replay.js"></script>
|
||||
</head>
|
||||
<body onload="OnInit()">
|
||||
<div class="runner">
|
||||
<header class="source-bar">
|
||||
<button type="button" id="open-file" class="btn" data-i18n="open_replay">Open replay…</button>
|
||||
<span class="chip">
|
||||
<span id="chip-name"></span>
|
||||
<span id="chip-edited" class="chip-note" hidden data-i18n="edited">(edited)</span>
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<main class="sections">
|
||||
<section id="steps-section" class="section is-open">
|
||||
<div class="section-row">
|
||||
<button type="button" class="section-head" aria-expanded="true" aria-controls="steps-body">
|
||||
<span class="chevron" aria-hidden="true"></span>
|
||||
<span class="section-title" data-i18n="steps">Steps</span>
|
||||
<span id="steps-summary" class="section-summary"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div id="steps-body" class="section-body">
|
||||
<p id="steps-hint" class="steps-hint" data-i18n="steps_hint">Steps appear here as you write them.</p>
|
||||
<ol id="steps" class="rail" hidden></ol>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="source-section" class="section is-open">
|
||||
<div class="section-row">
|
||||
<button type="button" class="section-head" aria-expanded="true" aria-controls="source-body">
|
||||
<span class="chevron" aria-hidden="true"></span>
|
||||
<span class="section-title" data-i18n="replay_source">Replay file</span>
|
||||
</button>
|
||||
<div class="section-actions">
|
||||
<span id="save-note" class="save-note" hidden role="status" data-i18n="saved">Saved</span>
|
||||
<button type="button" id="save" class="btn small"></button>
|
||||
<button type="button" id="save-as" class="btn small" hidden data-i18n="save_as">Save as…</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="source-body" class="section-body">
|
||||
<div id="editor" class="editor"></div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="foot">
|
||||
<div class="outcome" role="status" aria-live="polite">
|
||||
<span id="outcome"></span>
|
||||
<span id="outcome-detail" class="outcome-detail"></span>
|
||||
</div>
|
||||
<button type="button" id="open-output" class="btn" hidden data-i18n="open_output">Open output folder</button>
|
||||
<button type="button" id="stop" class="btn" hidden data-i18n="stop">Stop</button>
|
||||
<button type="button" id="run" class="btn primary" disabled data-i18n="run">Replay</button>
|
||||
<button type="button" id="close" class="btn" data-i18n="close">Close</button>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
275
resources/web/dialog/ActionReplay/replay_editor.js
Normal file
275
resources/web/dialog/ActionReplay/replay_editor.js
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
// The replay editor's language: a replay's highlighting (the orca_replay mode), and suggestions for its keys, tool
|
||||
// names, a tool's args and their allowed values, and ${…} placeholders, with what accepting one and Return write. The
|
||||
// editor is Ace, set up by ../js/code_editor.js; the pure functions here are also loaded by replay_editor.test.js.
|
||||
|
||||
// The replay format version the draft and the version key's suggestion write: the host's REPLAY_VERSION
|
||||
// (src/slic3r/GUI/Mcp/McpReplay.hpp), which says which versions it reads.
|
||||
const REPLAY_VERSION = "0.2.0";
|
||||
|
||||
// The keys of a replay and of a step, with the JSON type of their values. Accepting a key writes a
|
||||
// value of that type after its colon (an empty string, object or array with the caret inside, or true),
|
||||
// or the item's own `then`; for a number the caret waits after the colon.
|
||||
const ROOT_KEYS = [
|
||||
{ label: "orca_replay_version", detail: "string", then: JSON.stringify(REPLAY_VERSION) },
|
||||
{ label: "name", detail: "string" },
|
||||
{ label: "vars", detail: "object" },
|
||||
{ label: "steps", detail: "array" },
|
||||
];
|
||||
const STEP_KEYS = [
|
||||
{ label: "tool", detail: "string" },
|
||||
{ label: "args", detail: "object" },
|
||||
{ label: "expect", detail: "object" },
|
||||
{ label: "optional", detail: "boolean" },
|
||||
{ label: "await", detail: "boolean" },
|
||||
{ label: "save_as", detail: "string" },
|
||||
{ label: "timeout_s", detail: "integer" },
|
||||
];
|
||||
const EMPTY_VALUES = { string: '""', object: "{}", array: "[]", boolean: "true" };
|
||||
const MATCHERS = ["eq", "ne", "gt", "ge", "lt", "le", "contains", "regex", "exists", "empty"];
|
||||
|
||||
// Comments, strings (opening quote and body, then the closing quote; an unclosed one ends with its
|
||||
// line), numbers, literals and punctuation: what the reader walks.
|
||||
const TOKEN = /(\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|("(?:[^"\\\n]|\\.)*)("?)|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b|([{}[\],:])/g;
|
||||
|
||||
const ed = {
|
||||
tools: new Map(), // tool name -> {title, args: {name: {type, enum}}}, from the host
|
||||
editor: null, // the Ace editor, once initEditor() made it
|
||||
};
|
||||
|
||||
// ---- highlighting ---------------------------------------------------------------------------------
|
||||
|
||||
// Ace's JSON mode with a replay's own highlighting: // and /* */ comments, keys (a string a colon follows on its line),
|
||||
// strings, ${…} inside keys and strings, numbers, true/false/null and punctuation, coloured by code_editor.css.
|
||||
function defineReplayMode() {
|
||||
ace.define("ace/mode/orca_replay_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"],
|
||||
(require, exports) => {
|
||||
const oop = require("ace/lib/oop");
|
||||
const TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
|
||||
function ReplayHighlightRules() {
|
||||
const placeholder = { token: "orca_var", regex: /\$\{[^}"]*\}/ };
|
||||
this.$rules = {
|
||||
start: [
|
||||
{ token: "comment", regex: /\/\/.*$/ },
|
||||
{ token: "comment", regex: /\/\*/, next: "comment" },
|
||||
{ token: "variable", regex: /"(?=(?:[^"\\]|\\.)*"\s*:)/, next: "key" },
|
||||
{ token: "string", regex: /"/, next: "string" },
|
||||
{ token: "constant.numeric", regex: /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/ },
|
||||
{ token: "constant.language", regex: /\b(?:true|false|null)\b/ },
|
||||
{ token: "paren.lparen", regex: /[[{]/ },
|
||||
{ token: "paren.rparen", regex: /[\]}]/ },
|
||||
{ token: "punctuation", regex: /[,:]/ },
|
||||
],
|
||||
key: [placeholder, { token: "variable", regex: /\\./ }, { token: "variable", regex: /"|$/, next: "start" }, { defaultToken: "variable" }],
|
||||
string: [placeholder, { token: "string", regex: /\\./ }, { token: "string", regex: /"|$/, next: "start" }, { defaultToken: "string" }],
|
||||
comment: [{ token: "comment", regex: /\*\//, next: "start" }, { defaultToken: "comment" }],
|
||||
};
|
||||
}
|
||||
oop.inherits(ReplayHighlightRules, TextHighlightRules);
|
||||
exports.ReplayHighlightRules = ReplayHighlightRules;
|
||||
});
|
||||
ace.define("ace/mode/orca_replay", ["require", "exports", "module", "ace/lib/oop", "ace/mode/json", "ace/mode/orca_replay_highlight_rules"],
|
||||
(require, exports) => {
|
||||
const oop = require("ace/lib/oop");
|
||||
const JsonMode = require("ace/mode/json").Mode;
|
||||
function Mode() {
|
||||
JsonMode.call(this);
|
||||
this.HighlightRules = require("ace/mode/orca_replay_highlight_rules").ReplayHighlightRules;
|
||||
}
|
||||
oop.inherits(Mode, JsonMode);
|
||||
Mode.prototype.$id = "ace/mode/orca_replay";
|
||||
// A replay is JSON with comments: JSON's worker would flag them.
|
||||
Mode.prototype.createWorker = () => null;
|
||||
exports.Mode = Mode;
|
||||
});
|
||||
}
|
||||
|
||||
// ---- reading the structure --------------------------------------------------------------------
|
||||
|
||||
// Walks the tokens before `at` keeping a frame per open object ({key, colon, keys, tool}) and
|
||||
// array ({array, index}). Returns the frames, the string `at` is in (after its opening quote) if
|
||||
// any, and the vars and saved job names seen; null when `at` is in a comment.
|
||||
function readReplay(text, at) {
|
||||
const frames = [];
|
||||
const vars = new Set();
|
||||
const jobs = new Set();
|
||||
let m;
|
||||
TOKEN.lastIndex = 0;
|
||||
while ((m = TOKEN.exec(text)) && m.index < at) {
|
||||
const end = TOKEN.lastIndex;
|
||||
const top = frames[frames.length - 1];
|
||||
if (m[1] !== undefined) {
|
||||
if (end > at || (end === at && !m[1].endsWith("*/"))) return null;
|
||||
continue;
|
||||
}
|
||||
if (m[2] !== undefined) {
|
||||
const closed = m[3] === '"';
|
||||
if (at < end || (at === end && !closed))
|
||||
return { frames, vars, jobs, string: { start: m.index, end, closed } };
|
||||
const value = m[2].slice(1);
|
||||
if (top && !top.array) {
|
||||
if (!top.colon) {
|
||||
top.key = value;
|
||||
top.keys.add(value);
|
||||
if (frames.length === 2 && frames[0].key === "vars") vars.add(value);
|
||||
} else if (top.key === "tool") top.tool = value;
|
||||
else if (top.key === "save_as") jobs.add(value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
switch (m[6]) {
|
||||
case "{": frames.push({ array: false, key: null, colon: false, keys: new Set(), tool: null }); break;
|
||||
case "[": frames.push({ array: true, index: 0 }); break;
|
||||
case "}": case "]": frames.pop(); break;
|
||||
case ":": if (top && !top.array) top.colon = true; break;
|
||||
case ",":
|
||||
if (top && top.array) top.index++;
|
||||
else if (top) { top.key = null; top.colon = false; }
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { frames, vars, jobs, string: null };
|
||||
}
|
||||
|
||||
// The step a path inside steps[] belongs to, as its frame: frames are root, steps, step, ...
|
||||
function stepTool(frames) {
|
||||
const step = frames[2];
|
||||
return step && !step.array ? ed.tools.get(step.tool) : null;
|
||||
}
|
||||
|
||||
function typeText(type) { return Array.isArray(type) ? type.join(" | ") : type || ""; }
|
||||
|
||||
function keyItems(frames, path) {
|
||||
const top = frames[frames.length - 1];
|
||||
let items = [];
|
||||
if (path.length === 0) items = ROOT_KEYS;
|
||||
else if (path.length === 2 && path[0] === "steps") items = STEP_KEYS;
|
||||
else if (path.length === 3 && path[0] === "steps" && path[2] === "args") {
|
||||
const tool = stepTool(frames);
|
||||
if (tool)
|
||||
items = Object.entries(tool.args).map(([name, arg]) => ({
|
||||
label: name,
|
||||
detail: typeText(arg.type),
|
||||
info: arg.enum ? arg.enum.join(" | ") : "",
|
||||
}));
|
||||
} else if (path.length === 4 && path[0] === "steps" && path[2] === "expect")
|
||||
items = MATCHERS.map((label) => ({ label }));
|
||||
return items.filter((item) => !top.keys.has(item.label));
|
||||
}
|
||||
|
||||
function valueItems(frames, path) {
|
||||
if (path.length === 3 && path[0] === "steps" && path[2] === "tool")
|
||||
return [...ed.tools.values()].map((tool) => {
|
||||
const args = Object.keys(tool.args);
|
||||
return { label: tool.name, detail: tool.title, info: args.length ? "args: " + args.join(", ") : "" };
|
||||
});
|
||||
if (path.length === 4 && path[0] === "steps" && path[2] === "args") {
|
||||
const tool = stepTool(frames);
|
||||
const arg = tool && tool.args[path[3]];
|
||||
if (arg && arg.enum) return arg.enum.filter((v) => typeof v === "string").map((label) => ({ label }));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// What can go at `at`: the range a suggestion replaces, how it is written there, and the candidates.
|
||||
// Inside a string that is a key or a value, or after an unclosed ${ in a string; elsewhere only when
|
||||
// asked (`explicit`), at a key or value position.
|
||||
function suggestionsAt(text, at, explicit) {
|
||||
const read = readReplay(text, at);
|
||||
if (!read || !read.frames.length) return null;
|
||||
const { frames, string } = read;
|
||||
const top = frames[frames.length - 1];
|
||||
const path = frames.slice(0, -1).map((f) => (f.array ? f.index : f.key));
|
||||
const wordEnd = at + /^[\w.-]*/.exec(text.slice(at))[0].length;
|
||||
if (string) {
|
||||
const typed = text.slice(string.start + 1, at);
|
||||
const open = typed.lastIndexOf("${");
|
||||
if (open >= 0 && typed.indexOf("}", open) < 0) {
|
||||
const items = ["replay_dir", "out_dir", ...[...read.vars].map((k) => "vars." + k), ...[...read.jobs].map((k) => "jobs." + k)];
|
||||
return { kind: "var", from: string.start + 3 + open, to: wordEnd, items: items.map((label) => ({ label })) };
|
||||
}
|
||||
} else if (!explicit) return null;
|
||||
// A suggestion replaces what was typed and, in a closed string, the rest of it up to the quote.
|
||||
const found = string
|
||||
? { quoted: true, from: string.start + 1, to: string.closed ? string.end : wordEnd }
|
||||
: { quoted: false, from: at - /[\w.-]*$/.exec(text.slice(0, at))[0].length, to: wordEnd };
|
||||
// Unquoted, only where a key or value can start, not right after one.
|
||||
if (!string && !/(^|[{[,:])\s*$/.test(text.slice(0, found.from))) return null;
|
||||
if (!top.array && !top.colon) return Object.assign(found, { kind: "key", items: keyItems(frames, path) });
|
||||
const value = [...path, top.array ? top.index : top.key];
|
||||
return Object.assign(found, { kind: "value", items: valueItems(frames, value) });
|
||||
}
|
||||
|
||||
// ---- suggestions -----------------------------------------------------------------------------------
|
||||
|
||||
// What accepting `item` of what suggestionsAt() `found` writes: [from, to) replaced with `insert`, the
|
||||
// caret `back` characters before its end, and whether the suggestions open again there. A key gets its
|
||||
// colon and an empty value of its type (unless a colon follows already), with the caret inside a
|
||||
// string, object or array; a ${…} gets its closing brace.
|
||||
function acceptEdit(text, found, item) {
|
||||
if (found.kind === "var")
|
||||
return { from: found.from, to: text[found.to] === "}" ? found.to + 1 : found.to, insert: item.label + "}", back: 0, reopen: false };
|
||||
let insert = (found.quoted ? "" : '"') + item.label + '"';
|
||||
let back = 0;
|
||||
let then = "";
|
||||
if (found.kind === "key" && !/^\s*:/.test(text.slice(found.to))) {
|
||||
then = item.then !== undefined ? item.then : EMPTY_VALUES[item.detail] || "";
|
||||
insert += ": " + then;
|
||||
back = then.length === 2 ? 1 : 0;
|
||||
}
|
||||
return { from: found.from, to: found.to, insert, back, reopen: then === '""' };
|
||||
}
|
||||
|
||||
// What Return writes for the selection [start, end): the line's indent, one level more after an
|
||||
// opening bracket; between a pair of brackets the closing one goes on its own line, the caret `back`
|
||||
// characters before the end on the line between.
|
||||
function newlineEdit(text, start, end) {
|
||||
const lineStart = text.lastIndexOf("\n", start - 1) + 1;
|
||||
const indent = /^[ \t]*/.exec(text.slice(lineStart, start))[0];
|
||||
const opens = /[{[]\s*$/.test(text.slice(lineStart, start));
|
||||
const closes = /^[ \t]*[}\]]/.test(text.slice(end));
|
||||
if (opens && closes) return { from: start, to: end, insert: "\n" + indent + " \n" + indent, back: indent.length + 1 };
|
||||
return { from: start, to: end, insert: "\n" + indent + (opens ? " " : ""), back: 0 };
|
||||
}
|
||||
|
||||
// ---- the editor ------------------------------------------------------------------------------------
|
||||
|
||||
function setEditorTools(tools) {
|
||||
ed.tools = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
}
|
||||
|
||||
// What the replay editor suggests: the word Ace filters by is the text from where a suggestion starts to the caret, so
|
||||
// it takes the characters of a tool name, a key and vars.x; typing a quote or a brace (of ${) opens the list.
|
||||
const replayCompleter = {
|
||||
suggestionsAt,
|
||||
acceptEdit,
|
||||
identifierRegexps: [/[\w.-]/],
|
||||
triggerCharacters: ['"', "{"],
|
||||
};
|
||||
|
||||
// Makes the editor in #editor: `onChange(text)` for every edit, and the page's `commands` (Run, Save, Save as) beside
|
||||
// Return, which writes newlineEdit()'s edit, since Ace's own brace handling splits only {}.
|
||||
function initEditor(onChange, commands) {
|
||||
defineReplayMode();
|
||||
const newlineCommand = {
|
||||
name: "replayNewline",
|
||||
bindKey: { win: "Return", mac: "Return" },
|
||||
exec: (editor) => {
|
||||
const range = editor.getSelectionRange();
|
||||
const doc = editor.session.doc;
|
||||
applyEditorEdit(editor, newlineEdit(editor.getValue(), doc.positionToIndex(range.start), doc.positionToIndex(range.end)));
|
||||
},
|
||||
};
|
||||
ed.editor = createCodeEditor(document.getElementById("editor"), {
|
||||
mode: "ace/mode/orca_replay",
|
||||
tabSize: 2,
|
||||
placeholder: T("source_placeholder", "Write a replay here, or open one."),
|
||||
completer: replayCompleter,
|
||||
onChange,
|
||||
commands: [newlineCommand, ...commands],
|
||||
});
|
||||
return ed.editor;
|
||||
}
|
||||
|
||||
// The language's pure functions, for the page's tests (node --test), which load this file as a module.
|
||||
if (typeof module === "object" && module.exports)
|
||||
module.exports = { readReplay, suggestionsAt, acceptEdit, newlineEdit, setEditorTools };
|
||||
117
resources/web/dialog/ActionReplay/replay_editor.test.js
Normal file
117
resources/web/dialog/ActionReplay/replay_editor.test.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
"use strict";
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const editor = require("./replay_editor.js");
|
||||
|
||||
// Two tools, as the host's catalog lists them: one taking a plain number, one an enum and a nullable number.
|
||||
editor.setEditorTools([
|
||||
{ name: "plate_slice", title: "Slice", args: { plates: { type: "integer" } } },
|
||||
{ name: "view_set", title: "Set the view", args: { camera: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } },
|
||||
]);
|
||||
|
||||
// What suggestionsAt() finds with the caret at the end of `text`.
|
||||
function at(text, explicit) { return editor.suggestionsAt(text, text.length, !!explicit); }
|
||||
function labels(found) { return found.items.map((item) => item.label); }
|
||||
|
||||
test("a replay's root keys are suggested in a key's string", () => {
|
||||
const found = at('{\n "');
|
||||
assert.equal(found.kind, "key");
|
||||
assert.equal(found.from, 5);
|
||||
assert.equal(found.to, 5);
|
||||
assert.deepEqual(labels(found), ["orca_replay_version", "name", "vars", "steps"]);
|
||||
});
|
||||
|
||||
test("a step's keys are suggested inside steps[], leaving out the ones it has", () => {
|
||||
const found = at('{"steps": [{"tool": "plate_slice", "');
|
||||
assert.equal(found.kind, "key");
|
||||
assert.deepEqual(labels(found), ["args", "expect", "optional", "await", "save_as", "timeout_s"]);
|
||||
});
|
||||
|
||||
test("a step's tool is suggested from the catalog with its title and arguments", () => {
|
||||
const text = '{"steps": [{"tool": "pl';
|
||||
const found = at(text);
|
||||
assert.equal(found.kind, "value");
|
||||
assert.equal(found.from, text.length - 2);
|
||||
assert.equal(found.to, text.length);
|
||||
assert.deepEqual(found.items, [
|
||||
{ label: "plate_slice", detail: "Slice", info: "args: plates" },
|
||||
{ label: "view_set", detail: "Set the view", info: "args: camera, zoom" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a tool's arguments are suggested in its args with their types and allowed values", () => {
|
||||
const found = at('{"steps": [{"tool": "view_set", "args": {"');
|
||||
assert.equal(found.kind, "key");
|
||||
assert.deepEqual(found.items, [
|
||||
{ label: "camera", detail: "string", info: "top | front" },
|
||||
{ label: "zoom", detail: "number | null", info: "" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("an argument's allowed values are suggested as its value", () => {
|
||||
const found = at('{"steps": [{"tool": "view_set", "args": {"camera": "');
|
||||
assert.equal(found.kind, "value");
|
||||
assert.deepEqual(labels(found), ["top", "front"]);
|
||||
});
|
||||
|
||||
test("a placeholder suggests the folders, the vars and the saved jobs", () => {
|
||||
const text = '{"vars": {"part": 1}, "steps": [{"tool": "plate_slice", "save_as": "s1"}, {"tool": "view_set", "args": {"camera": "${';
|
||||
const found = at(text);
|
||||
assert.equal(found.kind, "var");
|
||||
assert.equal(found.from, text.length);
|
||||
assert.equal(found.to, text.length);
|
||||
assert.deepEqual(labels(found), ["replay_dir", "out_dir", "vars.part", "jobs.s1"]);
|
||||
});
|
||||
|
||||
test("nothing is suggested outside a string unless asked for, nor in a comment", () => {
|
||||
assert.equal(at('{"steps": [{'), null);
|
||||
const asked = at('{"steps": [{', true);
|
||||
assert.equal(asked.kind, "key");
|
||||
assert.equal(asked.quoted, false);
|
||||
assert.equal(at('// "'), null);
|
||||
});
|
||||
|
||||
test("an accepted key gets its colon and an empty value with the caret inside", () => {
|
||||
const text = '{"';
|
||||
const found = at(text);
|
||||
const steps = found.items.find((item) => item.label === "steps");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, steps), { from: 2, to: 2, insert: 'steps": []', back: 1, reopen: false });
|
||||
// A string's value opens the suggestions again inside its quotes.
|
||||
const name = found.items.find((item) => item.label === "name");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 2, insert: 'name": ""', back: 1, reopen: true });
|
||||
// The format version is written whole, with the caret after it.
|
||||
const version = found.items.find((item) => item.label === "orca_replay_version");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_replay_version": "0.2.0"', back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("a key accepted before an existing colon replaces only the key", () => {
|
||||
const text = '{"na": 1}';
|
||||
const found = editor.suggestionsAt(text, 4, false);
|
||||
const name = found.items.find((item) => item.label === "name");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 5, insert: 'name"', back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("a value accepted in a closed string replaces it up to its quote", () => {
|
||||
const text = '{"steps": [{"tool": "pl"}]}';
|
||||
const caret = text.indexOf('pl"') + 2;
|
||||
const found = editor.suggestionsAt(text, caret, false);
|
||||
assert.equal(found.from, caret - 2);
|
||||
assert.equal(found.to, caret + 1);
|
||||
assert.deepEqual(editor.acceptEdit(text, found, { label: "plate_slice" }), { from: caret - 2, to: caret + 1, insert: 'plate_slice"', back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("an accepted placeholder closes its brace, over one already typed", () => {
|
||||
const text = '{"vars": {"part": 1}, "steps": [{"tool": "x", "args": {"p": "${va}"}}]}';
|
||||
const caret = text.indexOf("${va") + 4;
|
||||
const found = editor.suggestionsAt(text, caret, false);
|
||||
assert.equal(found.kind, "var");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, { label: "vars.part" }), { from: caret - 2, to: caret + 1, insert: "vars.part}", back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("Return keeps the indent, adds a level after an opening bracket and splits a pair", () => {
|
||||
assert.deepEqual(editor.newlineEdit("{", 1, 1), { from: 1, to: 1, insert: "\n ", back: 0 });
|
||||
assert.deepEqual(editor.newlineEdit("{}", 1, 1), { from: 1, to: 1, insert: "\n \n", back: 1 });
|
||||
assert.deepEqual(editor.newlineEdit(" []", 3, 3), { from: 3, to: 3, insert: "\n \n ", back: 3 });
|
||||
const line = ' "a": 1,';
|
||||
assert.deepEqual(editor.newlineEdit(line, line.length, line.length), { from: line.length, to: line.length, insert: "\n ", back: 0 });
|
||||
});
|
||||
199
resources/web/dialog/ActionReplay/style.css
Normal file
199
resources/web/dialog/ActionReplay/style.css
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
/* Action Replay. Colours come from the host theme contract (--orca-*) and theme.css's status roles,
|
||||
* so the page follows the app in light and dark. The one distinctive element is the step rail
|
||||
* (../css/step_rail.css): an accent thread that fills down the list as steps pass. Everything else
|
||||
* stays quiet and host-native. */
|
||||
|
||||
:root {
|
||||
--sr-footer: var(--footer-bg, #fafafa);
|
||||
--sr-btn-bg: var(--btn-bg, #ffffff);
|
||||
--sr-btn-border: var(--btn-border, #cccccc);
|
||||
--sr-btn-hover: var(--btn-hover, #f0f0f0);
|
||||
--sr-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-fg);
|
||||
font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
.runner { display: flex; flex-direction: column; height: 100%; }
|
||||
|
||||
/* ---- buttons ---- */
|
||||
.btn {
|
||||
font: inherit;
|
||||
color: var(--sr-fg);
|
||||
background: var(--sr-btn-bg);
|
||||
border: 1px solid var(--sr-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 4px 14px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn:hover:not(:disabled) { background: var(--sr-btn-hover); }
|
||||
.btn.primary { color: var(--sr-accent-fg); background: var(--sr-accent); border-color: var(--sr-accent); }
|
||||
.btn.primary:hover:not(:disabled) { background: var(--sr-accent); filter: brightness(1.08); }
|
||||
.btn.small { padding: 2px 10px; font-size: 12px; }
|
||||
.btn:disabled { opacity: 0.45; cursor: default; }
|
||||
.link {
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--sr-accent);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accent); outline-offset: 1px; }
|
||||
|
||||
/* ---- source bar ---- */
|
||||
.source-bar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--sr-rule);
|
||||
}
|
||||
.chip {
|
||||
margin-left: 6px;
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--sr-accent-tint);
|
||||
color: var(--sr-fg);
|
||||
overflow: hidden;
|
||||
}
|
||||
#chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.chip-note { color: var(--sr-muted); white-space: nowrap; }
|
||||
|
||||
/* ---- foldable sections ---- */
|
||||
.sections { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.section { display: flex; flex-direction: column; min-height: 0; }
|
||||
.section + .section { border-top: 1px solid var(--sr-rule); }
|
||||
.section.is-open { flex: 1 1 0; }
|
||||
#steps-section.is-open { flex-grow: 2; }
|
||||
#source-section.is-open { flex-grow: 3; }
|
||||
/* A section's head row: the fold button fills it, and a section's actions sit at its end, outside it. */
|
||||
.section-row { flex: none; display: flex; align-items: center; border-bottom: 1px solid transparent; }
|
||||
.section.is-open .section-row { border-bottom-color: var(--sr-rule); }
|
||||
.section-row:hover { background: var(--sr-hover); }
|
||||
.section-head {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 12px;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
color: var(--sr-fg);
|
||||
background: none;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.section-actions { flex: none; display: flex; align-items: center; gap: 6px; padding-right: 12px; }
|
||||
.save-note { margin-right: 2px; font-size: 12px; color: var(--sr-pass); transition: opacity 0.4s; }
|
||||
.save-note.is-fading { opacity: 0; }
|
||||
@media (prefers-reduced-motion: reduce) { .save-note { transition: none; } }
|
||||
.chevron {
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-style: solid;
|
||||
border-width: 4px 0 4px 6px;
|
||||
border-color: transparent transparent transparent var(--sr-muted);
|
||||
transition: transform 120ms ease;
|
||||
}
|
||||
.section.is-open .chevron { transform: rotate(90deg); }
|
||||
.section-summary {
|
||||
margin-left: auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 400;
|
||||
font-size: 12px;
|
||||
color: var(--sr-muted);
|
||||
}
|
||||
.section-summary.is-error { color: var(--sr-fail); }
|
||||
.section-body { flex: 1; min-height: 0; overflow: auto; }
|
||||
|
||||
/* ---- no steps yet ---- */
|
||||
.steps-hint { margin: 0; padding: 12px 14px; color: var(--sr-muted); }
|
||||
|
||||
/* ---- the step rail: what only Action Replay's steps have ---- */
|
||||
/* The last steps that parsed, kept while the text doesn't, so typing doesn't empty the list. */
|
||||
.rail.is-stale { opacity: 0.45; }
|
||||
.step.is-skip .dot { border-style: dashed; }
|
||||
.step.is-wait .step-title, .step.is-skip .step-title { font-weight: 400; color: var(--sr-muted); }
|
||||
.play {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
font-size: 10px;
|
||||
line-height: 1;
|
||||
color: var(--sr-accent);
|
||||
background: none;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
}
|
||||
.step:hover .play:not(:disabled), .play:focus-visible { opacity: 1; border-color: var(--sr-rule); }
|
||||
.result-line { margin: 2px 0; }
|
||||
.checks { list-style: none; margin: 0 0 6px; padding: 0; color: var(--sr-muted); }
|
||||
.checks li { margin: 2px 0; overflow-wrap: anywhere; }
|
||||
.checks li.is-met::before { content: "\2713\00a0"; color: var(--sr-pass); }
|
||||
.files { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 4px 0; }
|
||||
.actions { display: flex; gap: 12px; align-items: center; margin-top: 6px; }
|
||||
|
||||
/* ---- source editor ----
|
||||
* Ace (../js/code_editor.js), filling the section; code_editor.css colours what is inside it. */
|
||||
#source-body { display: flex; padding: 8px 12px; }
|
||||
.editor {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 80px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.editor.ace_focus { border-color: var(--sr-accent); }
|
||||
.editor.is-readonly .ace_content { opacity: 0.6; }
|
||||
|
||||
/* ---- footer ---- */
|
||||
.foot {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--sr-rule);
|
||||
background: var(--sr-footer);
|
||||
}
|
||||
.outcome { flex: 1; min-width: 0; display: flex; flex-direction: column; }
|
||||
#outcome { font-weight: 600; }
|
||||
#outcome.is-pass { color: var(--sr-pass); }
|
||||
#outcome.is-fail { color: var(--sr-fail); }
|
||||
#outcome.is-warn { color: var(--sr-warn); }
|
||||
#outcome.is-quiet { font-weight: 400; color: var(--sr-muted); }
|
||||
.outcome-detail { font-size: 12px; color: var(--sr-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.chevron { transition: none; }
|
||||
}
|
||||
437
resources/web/dialog/AgentActivity/agent_activity.js
Normal file
437
resources/web/dialog/AgentActivity/agent_activity.js
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
// The Agent Activity pane's page. The host (AgentActivityPanel) sends the activity log's entries as they change, with
|
||||
// their titles, targets and source labels in the UI's language; this page draws them as a step rail, filters them, and
|
||||
// asks the host to clear the list or copy a request or response.
|
||||
|
||||
const M = AgentActivityModel;
|
||||
const MASK = "\u2022\u2022\u2022";
|
||||
|
||||
const S = {
|
||||
store: M.createStore(),
|
||||
open: new Set(), // the entries the person opened
|
||||
show: "all", // all | changes | failures
|
||||
source: "all", // a sourceKey(), or all
|
||||
find: "",
|
||||
following: true, // the list follows the newest call until the person scrolls up
|
||||
newBelow: 0, // calls that came while the person read further up
|
||||
tree: { top: [], children: new Map() },
|
||||
};
|
||||
const rows = new Map(); // entry id -> its <li>
|
||||
|
||||
const ICON = {
|
||||
agent: '<svg viewBox="0 0 16 16"><path d="M8 1.5c.5 3.2 1.8 5 5.5 6.5-3.7 1.5-5 3.3-5.5 6.5-.5-3.2-1.8-5-5.5-6.5C6.2 6.5 7.5 4.7 8 1.5z" fill="currentColor"/></svg>',
|
||||
action_replay: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3.4 8.6A4.7 4.7 0 1 0 5 4.4"/><path d="M2.8 2.2v3.3h3.3"/></svg>',
|
||||
run_script: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="2.5" width="13" height="11" rx="2"/><path d="M4.5 6.5 6.5 8l-2 1.5M8.2 10h3.3"/></svg>',
|
||||
command_line: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 4.5 6 8l-3.5 3.5M7.5 12h6"/></svg>',
|
||||
plugin: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"><path d="M6.2 2.6a1.6 1.6 0 0 1 3.2 0V4h3.1v3.1h-1.3a1.6 1.6 0 0 0 0 3.2h1.3v3.2H3.3v-3.2h1.2a1.6 1.6 0 0 0 0-3.2H3.3V4h2.9z"/></svg>',
|
||||
dialog: '<svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"><path d="M1.8 2.2h8.4v5.6H5.4L3 9.8V7.8H1.8z"/></svg>',
|
||||
};
|
||||
|
||||
function $(id) { return document.getElementById(id); }
|
||||
|
||||
function send(command, extra) { SendWXMessage(JSON.stringify(Object.assign({ command }, extra || {}))); }
|
||||
|
||||
function el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
// An icon from the fixed set above, never from an entry.
|
||||
function icon(name) {
|
||||
const span = el("span", "icon");
|
||||
span.innerHTML = ICON[name] || ICON.agent;
|
||||
return span;
|
||||
}
|
||||
|
||||
// ---- JSON, laid out as the Run Script console lays out a result ---------------------------------------------------
|
||||
|
||||
function jsonBlock(value) {
|
||||
const pre = el("pre", "raw");
|
||||
if (M.truncated(value)) {
|
||||
pre.className = "raw is-note";
|
||||
pre.textContent = M.tr("too_large", "Too large to show here (%s bytes).", value.bytes);
|
||||
return pre;
|
||||
}
|
||||
const shown = RunScriptModel.formatJson(JSON.stringify(value));
|
||||
const tokens = RunScriptModel.jsonTokens(shown);
|
||||
if (!tokens) {
|
||||
pre.textContent = shown;
|
||||
return pre;
|
||||
}
|
||||
for (const token of tokens) {
|
||||
if (token.type === "space") pre.append(document.createTextNode(token.text));
|
||||
else pre.append(el("span", "j-" + token.type + (token.text === '"' + MASK + '"' ? " mask" : ""), token.text));
|
||||
}
|
||||
return pre;
|
||||
}
|
||||
|
||||
// ---- a step -------------------------------------------------------------------------------------------------------
|
||||
|
||||
function makeRow(entry) {
|
||||
const row = el("li", "step");
|
||||
row.dataset.id = entry.id;
|
||||
row.append(el("span", "dot"));
|
||||
const main = el("div", "step-main");
|
||||
const head = el("button", "step-head");
|
||||
head.type = "button";
|
||||
head.setAttribute("aria-expanded", "false");
|
||||
head.append(el("span", "step-title"), el("span", "step-what"));
|
||||
head.addEventListener("click", () => toggle(entry.id));
|
||||
const nested = el("ol", "rail nested");
|
||||
nested.hidden = true;
|
||||
const detail = el("div", "step-detail");
|
||||
detail.hidden = true;
|
||||
main.append(head, el("div", "step-tags"), el("div", "failure"), nested, detail);
|
||||
row.append(main, el("div", "step-side"));
|
||||
return row;
|
||||
}
|
||||
|
||||
function nestedOf(row) { return row.querySelector(":scope > .step-main > .rail.nested"); }
|
||||
|
||||
function anyRunning(entry) {
|
||||
return entry.status === "running" || (S.tree.children.get(entry.id) || []).some(anyRunning);
|
||||
}
|
||||
|
||||
function renderRow(entry) {
|
||||
const row = rows.get(entry.id);
|
||||
const open = S.open.has(entry.id);
|
||||
const children = S.tree.children.get(entry.id) || [];
|
||||
const status = { running: "is-running", done: "is-done", failed: "is-fail" }[entry.status] || "is-done";
|
||||
row.className = "step " + status + (entry.status !== "running" ? " is-ended" : "") + (entry.read ? " is-read" : "") +
|
||||
(entry.kind === "dialog" ? " is-dialog" : "") + (open ? " is-open" : "") + (row.classList.contains("is-hidden") ? " is-hidden" : "") +
|
||||
(row.classList.contains("is-last") ? " is-last" : "");
|
||||
|
||||
const dot = row.querySelector(":scope > .dot");
|
||||
dot.textContent = "";
|
||||
if (entry.kind === "dialog") dot.append(icon("dialog"));
|
||||
else dot.textContent = entry.number ? String(entry.number) : "";
|
||||
dot.title = entry.kind === "dialog" ? M.tr("dialog_answered", "A dialog a rule answered")
|
||||
: entry.read ? M.tr("read_call", "A call that only reads") : M.tr("change_call", "A call that changes something");
|
||||
|
||||
const head = row.querySelector(":scope > .step-main > .step-head");
|
||||
head.setAttribute("aria-expanded", String(open));
|
||||
head.querySelector(".step-title").textContent = entry.title || entry.tool || "";
|
||||
const what = head.querySelector(".step-what");
|
||||
what.textContent = entry.what || "";
|
||||
if (entry.kind === "dialog" && entry.request && entry.request.button) what.append(el("span", "pressed", entry.request.button));
|
||||
if (entry.status === "running" && entry.job && !entry.read)
|
||||
what.append(el("span", "res is-run", (entry.what ? " " : "") + M.tr("running_as_job", "running as job %s", entry.job)));
|
||||
|
||||
const tags = row.querySelector(":scope > .step-main > .step-tags");
|
||||
tags.textContent = "";
|
||||
// What a call does beyond the open project, labelled by the host as Action Replay's steps are ("flag_" + id).
|
||||
for (const id of entry.flags || []) tags.append(el("span", "tag", M.tr("flag_" + id, id)));
|
||||
tags.hidden = !tags.childNodes.length;
|
||||
|
||||
const failure = row.querySelector(":scope > .step-main > .failure");
|
||||
failure.hidden = entry.status !== "failed" || !entry.error;
|
||||
failure.textContent = entry.status === "failed" ? (entry.error || "").split("\n")[0] : "";
|
||||
|
||||
// A run's own steps, while it runs or once opened.
|
||||
const nested = nestedOf(row);
|
||||
nested.hidden = !children.length || !(open || anyRunning(entry));
|
||||
|
||||
const detail = row.querySelector(":scope > .step-main > .step-detail");
|
||||
detail.hidden = !open;
|
||||
if (open) fillDetail(detail, entry);
|
||||
|
||||
const side = row.querySelector(":scope > .step-side");
|
||||
side.textContent = "";
|
||||
if (!entry.parent || !S.store.has(entry.parent)) {
|
||||
const src = el("span", "src");
|
||||
src.title = entry.source_label || "";
|
||||
src.append(el("span", "src-name", entry.source_label || ""), icon(entry.source));
|
||||
side.append(src, el("span", "clock", M.clock(entry.started)));
|
||||
}
|
||||
side.append(el("span", "time", entry.kind === "dialog" ? "" : M.duration(M.elapsed(entry, Date.now()))));
|
||||
}
|
||||
|
||||
function fillDetail(detail, entry) {
|
||||
detail.textContent = "";
|
||||
if (entry.kind === "dialog") {
|
||||
const d = entry.request || {};
|
||||
detail.append(el("div", "kv-head", M.tr("dialog", "Dialog")));
|
||||
const dl = el("dl", "args plain");
|
||||
for (const [key, fallback, value] of [["dialog_title", "Title", d.title], ["dialog_message", "Message", d.message], ["pressed", "Pressed", d.button]])
|
||||
if (value) dl.append(el("dt", "", M.tr(key, fallback)), el("dd", "", value));
|
||||
detail.append(dl);
|
||||
const rule = M.ruleSetter(entry, S.store);
|
||||
const ruleHead = el("div", "kv-head", M.tr("rule", "Rule"));
|
||||
if (rule) {
|
||||
ruleHead.append(el("span", "meta", M.tr("set_by", "set by call %s, %s", rule.number, rule.title || rule.tool)));
|
||||
const show = el("button", "link", M.tr("show_call", "Show that call"));
|
||||
show.type = "button";
|
||||
show.addEventListener("click", () => reveal(rule.id));
|
||||
ruleHead.append(show);
|
||||
} else ruleHead.append(el("span", "meta", M.tr("rule_gone", "the call that set it isn't listed")));
|
||||
detail.append(ruleHead);
|
||||
const rl = el("dl", "args");
|
||||
// The rule's own arguments, by their names.
|
||||
rl.append(el("dt", "", "match"), el("dd", "", d.match || ""), el("dt", "", "button"), el("dd", "", d.button || ""));
|
||||
detail.append(rl);
|
||||
return;
|
||||
}
|
||||
const parent = S.store.get(entry.parent);
|
||||
detail.append(section(M.tr("request", "Request"), M.requestNote(entry, parent && (parent.title || parent.tool)), entry.request,
|
||||
M.tr("copy_request", "Copy request")));
|
||||
const state = M.responseState(entry);
|
||||
detail.append(section(M.tr("response", "Response"), M.responseNote(entry, Date.now()), state === "value" ? entry.response : undefined,
|
||||
M.tr("copy_response", "Copy response"), state === "withheld"));
|
||||
// The files its result names, as Action Replay lists a step's: a screenshot opens in the system's viewer, and each
|
||||
// file shows in its folder. The host finds a file by the entry and its place in the list.
|
||||
const files = entry.files || [];
|
||||
if (files.length) {
|
||||
const box = el("div", "files");
|
||||
if (entry.thumb) {
|
||||
const img = el("img", "thumb");
|
||||
img.src = entry.thumb;
|
||||
img.alt = files[0];
|
||||
img.addEventListener("click", () => send("open_file", { id: entry.id, index: 0 }));
|
||||
box.append(img);
|
||||
}
|
||||
files.forEach((name, index) => {
|
||||
const link = el("button", "link", name);
|
||||
link.type = "button";
|
||||
link.title = M.tr("show_in_folder", "Show in folder");
|
||||
link.addEventListener("click", () => send("show_file", { id: entry.id, index }));
|
||||
box.append(link);
|
||||
});
|
||||
detail.append(box);
|
||||
}
|
||||
}
|
||||
|
||||
// A titled JSON block with its note and a Copy link; "Nothing yet." while a call has no response, and a note in place of
|
||||
// a response the host withheld.
|
||||
function section(title, note, value, copyLabel, withheld) {
|
||||
const wrap = el("div", "kv");
|
||||
const head = el("div", "kv-head", title);
|
||||
head.append(el("span", "meta", note));
|
||||
if (value !== undefined && !M.truncated(value)) {
|
||||
const copy = el("button", "link", copyLabel);
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
send("copy", { text: JSON.stringify(value, null, 2) });
|
||||
copy.textContent = M.tr("copied", "Copied");
|
||||
setTimeout(() => { copy.textContent = copyLabel; }, 1200);
|
||||
});
|
||||
head.append(copy);
|
||||
}
|
||||
wrap.append(head, withheld ? el("p", "none", M.tr("withheld", "Can't be shown: it repeats a call whose record the pane no longer has."))
|
||||
: value === undefined ? el("p", "none", M.tr("nothing_yet_response", "Nothing yet."))
|
||||
: jsonBlock(value));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function toggle(id) {
|
||||
if (S.open.has(id)) S.open.delete(id);
|
||||
else S.open.add(id);
|
||||
const entry = S.store.get(id);
|
||||
if (entry) renderRow(entry);
|
||||
refresh();
|
||||
}
|
||||
|
||||
// Opens an entry and scrolls to it: the call a dialog's rule came from.
|
||||
function reveal(id) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry) return;
|
||||
S.open.add(id);
|
||||
const above = ancestors(entry);
|
||||
for (const up of above) S.open.add(up.id);
|
||||
for (const shown of [entry].concat(above)) renderRow(shown);
|
||||
refresh();
|
||||
S.following = false;
|
||||
const row = rows.get(id);
|
||||
const list = $("list");
|
||||
if (row) list.scrollTop = row.getBoundingClientRect().top - list.getBoundingClientRect().top + list.scrollTop - 8;
|
||||
}
|
||||
|
||||
function ancestors(entry) {
|
||||
const out = [];
|
||||
for (let up = S.store.get(entry.parent); up; up = S.store.get(up.parent)) out.push(up);
|
||||
return out;
|
||||
}
|
||||
|
||||
function atBottom(list) { return list.scrollHeight - list.scrollTop - list.clientHeight < 30; }
|
||||
|
||||
// ---- the list -----------------------------------------------------------------------------------------------------
|
||||
|
||||
function onEntries(msg) {
|
||||
const list = $("list");
|
||||
const wasAtBottom = atBottom(list);
|
||||
const before = S.tree.top.length;
|
||||
if (msg.reset) {
|
||||
rows.clear();
|
||||
$("rail").textContent = "";
|
||||
S.open.clear();
|
||||
}
|
||||
for (const id of msg.removed || []) {
|
||||
const row = rows.get(id);
|
||||
if (row) row.remove();
|
||||
rows.delete(id);
|
||||
S.open.delete(id);
|
||||
}
|
||||
M.apply(S.store, msg);
|
||||
S.tree = M.tree(S.store);
|
||||
// A new row goes last under its parent, or at the end of the list: ids only grow.
|
||||
const place = (entry) => {
|
||||
if (!rows.has(entry.id)) rows.set(entry.id, makeRow(entry));
|
||||
const row = rows.get(entry.id);
|
||||
const host = entry.parent && rows.has(entry.parent) ? nestedOf(rows.get(entry.parent)) : $("rail");
|
||||
if (row.parentNode !== host) host.append(row);
|
||||
};
|
||||
const changed = new Set((msg.entries || []).map((e) => e.id));
|
||||
const walk = (entries) => {
|
||||
for (const entry of entries) {
|
||||
if (msg.reset || changed.has(entry.id) || !rows.has(entry.id)) place(entry);
|
||||
walk(S.tree.children.get(entry.id) || []);
|
||||
}
|
||||
};
|
||||
walk(S.tree.top);
|
||||
// Each changed entry and, once each, the runs above them, whose running state and counts follow their steps.
|
||||
const render = new Set();
|
||||
for (const id of changed) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry) continue;
|
||||
render.add(entry);
|
||||
for (const up of ancestors(entry)) render.add(up);
|
||||
}
|
||||
for (const entry of render) renderRow(entry);
|
||||
const following = S.following || wasAtBottom || msg.reset;
|
||||
S.newBelow = following ? 0 : S.newBelow + Math.max(0, S.tree.top.length - before);
|
||||
refresh();
|
||||
if (following) list.scrollTop = list.scrollHeight;
|
||||
}
|
||||
|
||||
// Which rows show, the thread's end, the source names that repeat, the toolbar.
|
||||
function refresh() {
|
||||
const { shown, last } = M.visibility(S.tree, { show: S.show, source: S.source, find: S.find });
|
||||
for (const [id, row] of rows) {
|
||||
row.classList.toggle("is-hidden", !shown.has(id));
|
||||
row.classList.toggle("is-last", last.has(id));
|
||||
}
|
||||
let previous = null;
|
||||
for (const entry of S.tree.top) {
|
||||
if (!shown.has(entry.id)) continue;
|
||||
const src = rows.has(entry.id) ? rows.get(entry.id).querySelector(":scope > .step-side .src") : null;
|
||||
if (src) src.classList.toggle("same", entry.source_label === previous);
|
||||
previous = entry.source_label;
|
||||
}
|
||||
const empty = $("empty");
|
||||
empty.hidden = S.tree.top.some((e) => shown.has(e.id));
|
||||
empty.textContent = S.tree.top.length ? M.tr("no_match", "No call matches.")
|
||||
: M.tr("empty", "Calls from agents, Action Replay, Run Script and plugins appear here as they run.");
|
||||
$("latest").hidden = !S.newBelow;
|
||||
$("latest-n").textContent = M.tr("new_calls", "New calls: %s", S.newBelow);
|
||||
renderToolbar();
|
||||
}
|
||||
|
||||
function renderToolbar() {
|
||||
document.querySelectorAll(".seg button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.show === S.show)));
|
||||
const sources = M.sources(S.tree.top);
|
||||
const picked = sources.find((s) => s.key === S.source);
|
||||
if (S.source !== "all" && !picked) S.source = "all";
|
||||
$("src-label").textContent = picked ? picked.label : M.tr("everyone", "Everyone");
|
||||
|
||||
const status = M.status(S.tree.top);
|
||||
const counts = M.counts(S.tree.top);
|
||||
const box = $("status");
|
||||
box.textContent = "";
|
||||
const who = el("span", status.busy ? "is-busy" : "");
|
||||
who.append(el("span", "sdot"), el("span", "who", status.text));
|
||||
box.append(who, el("span", "counts", M.tr("calls", "Calls: %s", counts.calls)));
|
||||
if (counts.failed) {
|
||||
const failed = el("button", "nfail", M.tr("failed", "Failed: %s", counts.failed));
|
||||
failed.type = "button";
|
||||
failed.addEventListener("click", () => setShow("failures"));
|
||||
box.append(failed);
|
||||
}
|
||||
}
|
||||
|
||||
function setShow(show) {
|
||||
S.show = show;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function renderSourceMenu() {
|
||||
const menu = $("src-menu");
|
||||
menu.textContent = "";
|
||||
const items = [{ key: "all", label: M.tr("everyone", "Everyone"), count: S.tree.top.length }].concat(M.sources(S.tree.top));
|
||||
for (const item of items) {
|
||||
const b = el("button");
|
||||
b.type = "button";
|
||||
b.setAttribute("role", "menuitemradio");
|
||||
b.setAttribute("aria-checked", String(S.source === item.key));
|
||||
b.append(el("span", "tick", S.source === item.key ? "✓" : ""));
|
||||
if (item.source) b.append(icon(item.source));
|
||||
b.append(el("span", "label", item.label), el("span", "mc", String(item.count)));
|
||||
b.addEventListener("click", () => {
|
||||
S.source = item.key;
|
||||
closeSourceMenu();
|
||||
refresh();
|
||||
});
|
||||
menu.append(b);
|
||||
}
|
||||
}
|
||||
|
||||
function closeSourceMenu() {
|
||||
$("src-menu").hidden = true;
|
||||
$("src-btn").setAttribute("aria-expanded", "false");
|
||||
}
|
||||
|
||||
// The running calls' durations, four times a second.
|
||||
function tick() {
|
||||
const now = Date.now();
|
||||
for (const [id, row] of rows) {
|
||||
const entry = S.store.get(id);
|
||||
if (!entry || entry.status !== "running") continue;
|
||||
const time = row.querySelector(":scope > .step-side .time");
|
||||
if (time) time.textContent = M.duration(now - entry.started);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- host messages ------------------------------------------------------------------------------------------------
|
||||
|
||||
function HandleStudio(msg) {
|
||||
switch (msg.command) {
|
||||
case "entries": onEntries(msg); break;
|
||||
}
|
||||
}
|
||||
|
||||
function OnInit() {
|
||||
TranslatePage();
|
||||
$("clear").addEventListener("click", () => send("clear"));
|
||||
document.querySelectorAll(".seg button").forEach((b) => b.addEventListener("click", () => setShow(b.dataset.show)));
|
||||
$("src-btn").addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const menu = $("src-menu");
|
||||
if (!menu.hidden) return closeSourceMenu();
|
||||
renderSourceMenu();
|
||||
menu.hidden = false;
|
||||
$("src-btn").setAttribute("aria-expanded", "true");
|
||||
});
|
||||
document.addEventListener("click", (e) => { if (!$("src-menu").contains(e.target)) closeSourceMenu(); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeSourceMenu(); });
|
||||
$("find").addEventListener("input", () => {
|
||||
S.find = $("find").value;
|
||||
refresh();
|
||||
});
|
||||
const list = $("list");
|
||||
list.addEventListener("scroll", () => {
|
||||
S.following = atBottom(list);
|
||||
if (S.following && S.newBelow) {
|
||||
S.newBelow = 0;
|
||||
$("latest").hidden = true;
|
||||
}
|
||||
});
|
||||
$("latest").addEventListener("click", () => {
|
||||
S.following = true;
|
||||
S.newBelow = 0;
|
||||
list.scrollTop = list.scrollHeight;
|
||||
$("latest").hidden = true;
|
||||
});
|
||||
setInterval(tick, 250);
|
||||
refresh();
|
||||
send("ready");
|
||||
}
|
||||
188
resources/web/dialog/AgentActivity/agent_activity_model.js
Normal file
188
resources/web/dialog/AgentActivity/agent_activity_model.js
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
// The Agent Activity page's pure logic: the host's entries merged into one list and nested by run, what the filters
|
||||
// show, what the toolbar counts and names, and the times and notes a step shows. Loaded by the page as a script and by
|
||||
// agent_activity_model.test.js as a module.
|
||||
(function (root, factory) {
|
||||
"use strict";
|
||||
const api = factory();
|
||||
if (typeof module === "object" && module.exports) module.exports = api;
|
||||
else root.AgentActivityModel = api;
|
||||
})(typeof globalThis === "object" ? globalThis : this, function () {
|
||||
"use strict";
|
||||
|
||||
// The page's T() (i18n.js) where it is loaded; the English with its %s filled in a test.
|
||||
function tr(key, fallback, ...args) {
|
||||
if (typeof T === "function") return T(key, fallback, ...args);
|
||||
let text = fallback;
|
||||
args.forEach((arg) => { text = text.replace("%s", () => String(arg)); });
|
||||
return text;
|
||||
}
|
||||
|
||||
// ---- the list ----------------------------------------------------------------------------------------------------
|
||||
|
||||
// The entries by id. apply() merges a host message {reset, entries, removed}: with reset, what the host sends is all
|
||||
// there is.
|
||||
function createStore() { return new Map(); }
|
||||
function apply(store, msg) {
|
||||
if (msg.reset) store.clear();
|
||||
for (const entry of msg.entries || []) store.set(entry.id, entry);
|
||||
for (const id of msg.removed || []) store.delete(id);
|
||||
}
|
||||
|
||||
// The top-level entries oldest first, and the entries nested under each id, oldest first. An entry whose parent is
|
||||
// gone stands at the top level.
|
||||
function tree(store) {
|
||||
const top = [];
|
||||
const children = new Map();
|
||||
const ids = Array.from(store.keys()).sort((a, b) => a - b);
|
||||
for (const id of ids) {
|
||||
const entry = store.get(id);
|
||||
if (entry.parent && store.has(entry.parent)) {
|
||||
if (!children.has(entry.parent)) children.set(entry.parent, []);
|
||||
children.get(entry.parent).push(entry);
|
||||
} else top.push(entry);
|
||||
}
|
||||
return { top, children };
|
||||
}
|
||||
|
||||
// ---- filters -----------------------------------------------------------------------------------------------------
|
||||
|
||||
// What the source menu sorts by: a plugin's entries by the plugin.
|
||||
function sourceKey(entry) { return entry.source === "plugin" ? "plugin:" + (entry.plugin || "") : entry.source || ""; }
|
||||
|
||||
// Whether `entry`, or an entry nested under it, passes Everything / Changes / Failures and Find a call. A dialog a rule
|
||||
// answered changed something: a button was pressed.
|
||||
function matches(entry, filter, children) {
|
||||
const find = (filter.find || "").trim().toLowerCase();
|
||||
const self = (filter.show === "all" || !filter.show || (filter.show === "changes" && !entry.read) ||
|
||||
(filter.show === "failures" && entry.status === "failed")) &&
|
||||
(!find || [entry.title, entry.what, entry.tool, entry.source_label].join(" ").toLowerCase().includes(find));
|
||||
return self || (children.get(entry.id) || []).some((c) => matches(c, filter, children));
|
||||
}
|
||||
|
||||
// Whether a top-level entry shows: its source is the one the menu picked, and it matches.
|
||||
function showsAtTop(entry, filter, children) {
|
||||
return (!filter.source || filter.source === "all" || sourceKey(entry) === filter.source) && matches(entry, filter, children);
|
||||
}
|
||||
|
||||
// Whether an entry nested under a shown one shows: all of them under Everything with nothing to find, else those
|
||||
// that match.
|
||||
function showsNested(entry, filter, children) {
|
||||
return ((filter.show === "all" || !filter.show) && !(filter.find || "").trim()) || matches(entry, filter, children);
|
||||
}
|
||||
|
||||
// Which entries show under `filter`, and which shown entry ends its list, where its thread stops: {shown, last}, sets of
|
||||
// ids. A top-level entry shows by showsAtTop(), an entry nested under a shown one by showsNested(), at any depth.
|
||||
function visibility(tree, filter) {
|
||||
const shown = new Set();
|
||||
const last = new Set();
|
||||
const walk = (entries, top) => {
|
||||
let end = null;
|
||||
for (const entry of entries) {
|
||||
if (!(top ? showsAtTop(entry, filter, tree.children) : showsNested(entry, filter, tree.children))) continue;
|
||||
shown.add(entry.id);
|
||||
end = entry;
|
||||
walk(tree.children.get(entry.id) || [], false);
|
||||
}
|
||||
if (end) last.add(end.id);
|
||||
};
|
||||
walk(tree.top, true);
|
||||
return { shown, last };
|
||||
}
|
||||
|
||||
// ---- the toolbar -------------------------------------------------------------------------------------------------
|
||||
|
||||
// The calls listed at the top level, which the last number counts, and how many of them failed. A dialog is no call.
|
||||
function counts(top) {
|
||||
const calls = top.filter((e) => e.kind !== "dialog");
|
||||
return { calls: calls.length, failed: calls.filter((e) => e.status === "failed").length };
|
||||
}
|
||||
|
||||
// The sources of the top-level entries, in the order they first came, with their labels and how many entries each.
|
||||
function sources(top) {
|
||||
const out = new Map();
|
||||
for (const entry of top) {
|
||||
const key = sourceKey(entry);
|
||||
if (!out.has(key)) out.set(key, { key, source: entry.source, label: entry.source_label || "", count: 0 });
|
||||
const item = out.get(key);
|
||||
++item.count;
|
||||
// The newest label: an agent's name may have become "Agent" since.
|
||||
if (entry.source_label) item.label = entry.source_label;
|
||||
}
|
||||
return Array.from(out.values());
|
||||
}
|
||||
|
||||
// What the status says: who works now (the newest running top-level entry's source), else whether anything ran.
|
||||
function status(top) {
|
||||
const running = top.filter((e) => e.status === "running");
|
||||
if (running.length) return { busy: true, text: tr("working", "%s is working", running[running.length - 1].source_label) };
|
||||
return { busy: false, text: top.length ? tr("idle", "Idle") : tr("nothing_yet", "Nothing yet") };
|
||||
}
|
||||
|
||||
// ---- a step ------------------------------------------------------------------------------------------------------
|
||||
|
||||
// A duration: tenths of a second under ten seconds, then whole seconds, then minutes and seconds.
|
||||
function duration(ms) {
|
||||
const s = Math.max(0, ms) / 1000;
|
||||
if (s < 60) return tr("seconds", "%s s", s < 10 ? s.toFixed(1) : Math.floor(s));
|
||||
return tr("minutes_seconds", "%s min %s s", Math.floor(s / 60), Math.floor(s % 60));
|
||||
}
|
||||
|
||||
// The time of day `ms` (since the epoch) was, as hours, minutes and seconds.
|
||||
function clock(ms) {
|
||||
const d = new Date(ms);
|
||||
const two = (n) => String(n).padStart(2, "0");
|
||||
return `${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function elapsed(entry, now) { return (entry.ended || now) - entry.started; }
|
||||
|
||||
// Calls a person sees run for longer than this ran as a job the agent was told to wait for.
|
||||
const LONG_MS = 1500;
|
||||
|
||||
// The note beside Response: how the call answered, or that it still runs.
|
||||
function responseNote(entry, now) {
|
||||
const took = duration(elapsed(entry, now));
|
||||
if (entry.status === "running")
|
||||
return entry.job ? tr("running_no_result", "running as job %s; no result yet", entry.job) : tr("waiting_reply", "waiting for the reply");
|
||||
if (entry.status === "failed") return tr("failed_after", "failed after %s", took);
|
||||
if (entry.job && elapsed(entry, now) > LONG_MS) return tr("ran_as_job", "ran as job %s; finished after %s", entry.job, took);
|
||||
return tr("answered_in", "answered in %s", took);
|
||||
}
|
||||
|
||||
// Whether an agent's request went through tool_call, the tool for commands the tool list leaves out.
|
||||
function viaToolCall(entry) {
|
||||
const params = entry.request && entry.request.params;
|
||||
return !!params && params.name === "tool_call";
|
||||
}
|
||||
|
||||
// The note beside Request: where it came from.
|
||||
function requestNote(entry, parentTitle) {
|
||||
const at = clock(entry.started);
|
||||
if (entry.parent && parentTitle) return tr("made_by", "made by %s", parentTitle);
|
||||
if (entry.kind === "work") return tr("work_at", "run in the Run Script panel at %s", at);
|
||||
if (entry.source === "agent" && entry.request && entry.request.method === "tools/call")
|
||||
return viaToolCall(entry) ? tr("tools_call_via", "tools/call from %s through tool_call, at %s", entry.source_label, at)
|
||||
: tr("tools_call_from", "tools/call from %s at %s", entry.source_label, at);
|
||||
return tr("sent_at", "sent at %s", at);
|
||||
}
|
||||
|
||||
// What an entry's Response section shows: "withheld" when the host can't show it (it repeats a job's result whose masking
|
||||
// record the host no longer has), "pending" while there is none yet, else "value".
|
||||
function responseState(entry) {
|
||||
if (entry.withheld === true) return "withheld";
|
||||
return entry.response === null || entry.response === undefined ? "pending" : "value";
|
||||
}
|
||||
|
||||
// The entry of the call that set the rule a dialog's answer came from, or null when the list doesn't hold it.
|
||||
function ruleSetter(entry, store) {
|
||||
return (entry.rule && store.get(entry.rule)) || null;
|
||||
}
|
||||
|
||||
// A request or response the host left out for its size: {truncated: true, bytes}.
|
||||
function truncated(value) {
|
||||
return !!value && typeof value === "object" && value.truncated === true && typeof value.bytes === "number" && Object.keys(value).length === 2;
|
||||
}
|
||||
|
||||
return { tr, createStore, apply, tree, sourceKey, matches, showsAtTop, showsNested, visibility, counts, sources, status, duration, clock,
|
||||
elapsed, responseNote, requestNote, viaToolCall, responseState, ruleSetter, truncated };
|
||||
});
|
||||
144
resources/web/dialog/AgentActivity/agent_activity_model.test.js
Normal file
144
resources/web/dialog/AgentActivity/agent_activity_model.test.js
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
"use strict";
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const model = require("./agent_activity_model.js");
|
||||
|
||||
// An entry as the host sends it, with what a test leaves out filled in.
|
||||
function entry(fields) {
|
||||
return Object.assign({ id: 1, parent: 0, number: 1, kind: "call", source: "agent", source_label: "Claude Code", plugin: "",
|
||||
tool: "app_state", title: "Get app state", what: "", read: false, status: "done", error: "", job: "",
|
||||
started: 1000, ended: 1200, request: {}, response: {}, rule: 0 }, fields);
|
||||
}
|
||||
|
||||
test("the host's changes merge into the list, and a reset starts it over", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { reset: true, entries: [entry({ id: 1 }), entry({ id: 2, status: "running" })] });
|
||||
model.apply(store, { entries: [entry({ id: 2, status: "done" }), entry({ id: 3 })], removed: [1] });
|
||||
assert.deepEqual(Array.from(store.keys()).sort(), [2, 3]);
|
||||
assert.equal(store.get(2).status, "done");
|
||||
model.apply(store, { reset: true, entries: [entry({ id: 9 })] });
|
||||
assert.deepEqual(Array.from(store.keys()), [9]);
|
||||
});
|
||||
|
||||
test("a run's steps nest under it in order, and a step whose run is gone stands at the top", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [entry({ id: 5, parent: 1 }), entry({ id: 1 }), entry({ id: 3, parent: 1 }), entry({ id: 7, parent: 4 })] });
|
||||
const { top, children } = model.tree(store);
|
||||
assert.deepEqual(top.map((e) => e.id), [1, 7]);
|
||||
assert.deepEqual(children.get(1).map((e) => e.id), [3, 5]);
|
||||
});
|
||||
|
||||
test("Changes leaves out reads, Failures shows failed calls, and a run shows when one of its steps matches", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, read: true }),
|
||||
entry({ id: 2, title: "Slice", what: "Plate 1" }),
|
||||
entry({ id: 3, tool: "replay_run", title: "Run a replay" }),
|
||||
entry({ id: 4, parent: 3, title: "Export", status: "failed", error: "Disk full" }),
|
||||
entry({ id: 5, kind: "dialog", title: "Answered a dialog", read: false }),
|
||||
] });
|
||||
const { top, children } = model.tree(store);
|
||||
const shown = (filter) => top.filter((e) => model.showsAtTop(e, filter, children)).map((e) => e.id);
|
||||
assert.deepEqual(shown({ show: "all" }), [1, 2, 3, 5]);
|
||||
assert.deepEqual(shown({ show: "changes" }), [2, 3, 5]);
|
||||
assert.deepEqual(shown({ show: "failures" }), [3]);
|
||||
assert.deepEqual(shown({ show: "all", find: "plate 1" }), [2]);
|
||||
assert.deepEqual(shown({ show: "all", find: "EXPORT" }), [3]);
|
||||
// Under a shown run, Everything with nothing to find shows every step; otherwise the ones that match.
|
||||
const step = store.get(4);
|
||||
assert.equal(model.showsNested(step, { show: "all" }, children), true);
|
||||
assert.equal(model.showsNested(step, { show: "changes", find: "slice" }, children), false);
|
||||
});
|
||||
|
||||
test("the source menu lists each source once with its newest label, and a plugin's entries by plugin", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, source: "agent", source_label: "Claude Code" }),
|
||||
entry({ id: 2, source: "plugin", plugin: "brim", source_label: "Brim Ears" }),
|
||||
entry({ id: 3, source: "agent", source_label: "Agent" }),
|
||||
entry({ id: 4, source: "plugin", plugin: "fill", source_label: "Fill" }),
|
||||
entry({ id: 5, parent: 2, source: "plugin", plugin: "brim", source_label: "Brim Ears" }),
|
||||
] });
|
||||
const { top, children } = model.tree(store);
|
||||
assert.deepEqual(model.sources(top).map((s) => [s.key, s.label, s.count]),
|
||||
[["agent", "Agent", 2], ["plugin:brim", "Brim Ears", 1], ["plugin:fill", "Fill", 1]]);
|
||||
assert.deepEqual(top.filter((e) => model.showsAtTop(e, { show: "all", source: "plugin:brim" }, children)).map((e) => e.id), [2]);
|
||||
});
|
||||
|
||||
test("the counts are of top-level calls, without dialogs, and the status names who works", () => {
|
||||
const top = [entry({ id: 1 }), entry({ id: 2, status: "failed" }), entry({ id: 3, kind: "dialog" }),
|
||||
entry({ id: 4, status: "running", source_label: "Action Replay" })];
|
||||
assert.deepEqual(model.counts(top), { calls: 3, failed: 1 });
|
||||
assert.deepEqual(model.status(top), { busy: true, text: "Action Replay is working" });
|
||||
assert.deepEqual(model.status([entry({ id: 1 })]), { busy: false, text: "Idle" });
|
||||
assert.deepEqual(model.status([]), { busy: false, text: "Nothing yet" });
|
||||
});
|
||||
|
||||
test("durations read in tenths, seconds, then minutes", () => {
|
||||
assert.equal(model.duration(420), "0.4 s");
|
||||
assert.equal(model.duration(12400), "12 s");
|
||||
assert.equal(model.duration(125000), "2 min 5 s");
|
||||
});
|
||||
|
||||
test("the response note says how the call answered, or that it still runs", () => {
|
||||
const now = 10000;
|
||||
assert.equal(model.responseNote(entry({ started: 1000, ended: 1300 }), now), "answered in 0.3 s");
|
||||
assert.equal(model.responseNote(entry({ job: "j4", started: 1000, ended: 9000 }), now), "ran as job j4; finished after 8.0 s");
|
||||
assert.equal(model.responseNote(entry({ job: "j4", status: "running", ended: 0 }), now), "running as job j4; no result yet");
|
||||
assert.equal(model.responseNote(entry({ status: "running", ended: 0 }), now), "waiting for the reply");
|
||||
assert.equal(model.responseNote(entry({ status: "failed", started: 1000, ended: 1500 }), now), "failed after 0.5 s");
|
||||
});
|
||||
|
||||
test("the request note names an agent's tools/call, through tool_call where it went, and a step's run", () => {
|
||||
const started = new Date(2026, 10, 23, 14, 2, 5).getTime();
|
||||
const call = entry({ started, request: { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "plate_slice" } } });
|
||||
assert.equal(model.requestNote(call), "tools/call from Claude Code at 14:02:05");
|
||||
const wrapped = entry({ started, request: { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "tool_call", arguments: { tool: "sketch_create" } } } });
|
||||
assert.equal(model.requestNote(wrapped), "tools/call from Claude Code through tool_call, at 14:02:05");
|
||||
assert.equal(model.requestNote(entry({ parent: 2 }), "Run a replay"), "made by Run a replay");
|
||||
assert.equal(model.requestNote(entry({ started, kind: "work", source: "run_script" })), "run in the Run Script panel at 14:02:05");
|
||||
});
|
||||
|
||||
test("a payload the host left out for its size is told apart from one that only looks like it", () => {
|
||||
assert.equal(model.truncated({ truncated: true, bytes: 40000 }), true);
|
||||
assert.equal(model.truncated({ truncated: true, bytes: 40000, extra: 1 }), false);
|
||||
assert.equal(model.truncated({ truncated: "yes", bytes: 1 }), false);
|
||||
assert.equal(model.truncated(null), false);
|
||||
});
|
||||
|
||||
test("the filters reach every depth: a replay's script's steps show or hide by their own match", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [
|
||||
entry({ id: 1, tool: "replay_run", title: "Run a replay" }),
|
||||
entry({ id: 2, parent: 1, tool: "script_run", title: "Run a Python script" }),
|
||||
entry({ id: 3, parent: 2, read: true, title: "List objects" }),
|
||||
entry({ id: 4, parent: 2, title: "Export", status: "failed", error: "Disk full" }),
|
||||
entry({ id: 5, read: true, title: "Get app state" }),
|
||||
] });
|
||||
const tree = model.tree(store);
|
||||
const failures = model.visibility(tree, { show: "failures" });
|
||||
assert.deepEqual(Array.from(failures.shown).sort(), [1, 2, 4]);
|
||||
assert.deepEqual(Array.from(failures.last).sort(), [1, 2, 4]); // each list's last shown entry
|
||||
const all = model.visibility(tree, { show: "all" });
|
||||
assert.deepEqual(Array.from(all.shown).sort(), [1, 2, 3, 4, 5]);
|
||||
assert.deepEqual(Array.from(all.last).sort(), [2, 4, 5]);
|
||||
const changes = model.visibility(tree, { show: "changes" });
|
||||
assert.equal(changes.shown.has(3), false);
|
||||
assert.equal(changes.shown.has(5), false);
|
||||
});
|
||||
|
||||
test("a withheld response is told by the entry, not by what the response holds", () => {
|
||||
assert.equal(model.responseState(entry({ withheld: true, response: null })), "withheld");
|
||||
assert.equal(model.responseState(entry({ withheld: false, response: { withheld: true } })), "value");
|
||||
assert.equal(model.responseState(entry({ status: "running", response: null })), "pending");
|
||||
assert.equal(model.responseState(entry({ response: { ok: true } })), "value");
|
||||
});
|
||||
|
||||
test("a dialog's rule links the call that set it only while the list holds that call", () => {
|
||||
const store = model.createStore();
|
||||
model.apply(store, { entries: [entry({ id: 4, tool: "dialog_auto_answer" }), entry({ id: 6, kind: "dialog", rule: 4 })] });
|
||||
assert.equal(model.ruleSetter(store.get(6), store).id, 4);
|
||||
assert.equal(model.ruleSetter(entry({ kind: "dialog", rule: 0 }), store), null);
|
||||
model.apply(store, { entries: [], removed: [4] });
|
||||
assert.equal(model.ruleSetter(store.get(6), store), null);
|
||||
});
|
||||
41
resources/web/dialog/AgentActivity/index.html
Normal file
41
resources/web/dialog/AgentActivity/index.html
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Agent Activity</title>
|
||||
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../js/code_editor.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../css/step_rail.css" />
|
||||
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||
<script type="text/javascript" src="../../include/i18n.js"></script>
|
||||
<script type="text/javascript" src="../js/globalapi.js"></script>
|
||||
<script type="text/javascript" src="../RunScript/run_script_model.js"></script>
|
||||
<script type="text/javascript" src="./agent_activity_model.js"></script>
|
||||
<script type="text/javascript" src="./agent_activity.js"></script>
|
||||
</head>
|
||||
<body onload="OnInit()">
|
||||
<div class="pane">
|
||||
<div class="toolbar" role="toolbar" aria-label="Agent Activity" data-i18n-aria-label="pane">
|
||||
<button type="button" id="clear" class="btn" data-i18n="clear">Clear list</button>
|
||||
<span class="tsep"></span>
|
||||
<div class="seg" role="group" aria-label="Show" data-i18n-aria-label="show">
|
||||
<button type="button" data-show="all" aria-pressed="true" data-i18n="show_all">Everything</button><button type="button" data-show="changes" aria-pressed="false" data-i18n="show_changes">Changes</button><button type="button" data-show="failures" aria-pressed="false" data-i18n="show_failures">Failures</button>
|
||||
</div>
|
||||
<div class="menu-wrap">
|
||||
<button type="button" id="src-btn" class="btn" aria-haspopup="menu" aria-expanded="false"><span class="t-opt" data-i18n="from">From:</span><span id="src-label"></span><svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M2 3.5 5 6.5 8 3.5"/></svg></button>
|
||||
<div class="menu" id="src-menu" role="menu" hidden></div>
|
||||
</div>
|
||||
<input class="find" id="find" type="search" placeholder="Find a call" aria-label="Find a call" data-i18n-placeholder="find" data-i18n-aria-label="find" />
|
||||
<div class="status" id="status" aria-live="polite"></div>
|
||||
</div>
|
||||
<div class="list-wrap">
|
||||
<div class="list" id="list">
|
||||
<p class="empty" id="empty"></p>
|
||||
<ol class="rail" id="rail"></ol>
|
||||
</div>
|
||||
<button type="button" class="latest" id="latest" hidden><svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 3.5 5 6.5 8 3.5"/></svg><span id="latest-n"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
239
resources/web/dialog/AgentActivity/style.css
Normal file
239
resources/web/dialog/AgentActivity/style.css
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
/* Agent Activity. The step rail comes from ../css/step_rail.css, as Action Replay's; this adds the toolbar, a read's
|
||||
* quiet line, a dialog's step, the nested steps of a run, and the request and response under an opened step. Colours
|
||||
* come from the host theme contract (--orca-*), theme.css's status roles and code_editor.css's JSON colours. */
|
||||
|
||||
:root {
|
||||
--aa-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
--aa-accent-text: var(--plugin-source-mine-text, #00897b);
|
||||
--aa-btn-bg: var(--btn-bg, #ffffff);
|
||||
--aa-btn-border: var(--btn-border, #cccccc);
|
||||
--aa-btn-hover: var(--btn-hover, #f0f0f0);
|
||||
--aa-menu-bg: var(--ctx-bg, #ffffff);
|
||||
}
|
||||
:root[data-orca-theme="dark"] { --aa-accent-text: #4db6ac; }
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-fg);
|
||||
font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
[hidden] { display: none !important; }
|
||||
button:focus-visible, input:focus-visible { outline: 2px solid var(--sr-accent); outline-offset: 1px; }
|
||||
|
||||
.pane { height: 100%; display: flex; flex-direction: column; container-type: inline-size; container-name: pane; }
|
||||
|
||||
/* ---- toolbar, as the Run Script panel's ---- */
|
||||
.toolbar { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--sr-rule); }
|
||||
.btn {
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
color: var(--sr-fg);
|
||||
background: var(--aa-btn-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 2px 10px;
|
||||
height: 24px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.btn svg { width: 10px; height: 10px; flex: none; }
|
||||
.btn:hover:not(:disabled) { background: var(--aa-btn-hover); }
|
||||
.tsep { width: 1px; height: 16px; background: var(--sr-rule); margin: 0 2px; }
|
||||
.seg { display: inline-flex; border: 1px solid var(--aa-btn-border); border-radius: 4px; overflow: hidden; height: 24px; }
|
||||
.seg button { font: inherit; font-size: 12px; border: 0; background: var(--aa-btn-bg); color: var(--sr-fg); padding: 0 9px; cursor: pointer; }
|
||||
.seg button + button { border-left: 1px solid var(--aa-btn-border); }
|
||||
.seg button[aria-pressed="true"] { background: var(--aa-tint); color: var(--aa-accent-text); font-weight: 600; }
|
||||
.menu-wrap { position: relative; }
|
||||
.menu {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
min-width: 200px;
|
||||
max-width: 280px;
|
||||
background: var(--aa-menu-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
|
||||
padding: 4px;
|
||||
}
|
||||
.menu button {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--sr-fg);
|
||||
padding: 5px 8px;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
text-align: left;
|
||||
}
|
||||
.menu button:hover { background: var(--sr-hover); }
|
||||
.menu .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.menu .mc { margin-left: auto; color: var(--sr-muted); font-variant-numeric: tabular-nums; }
|
||||
.menu .tick { width: 12px; flex: none; color: var(--aa-accent-text); }
|
||||
.menu .icon { color: var(--sr-muted); }
|
||||
.find {
|
||||
height: 24px;
|
||||
width: 150px;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
color: var(--sr-fg);
|
||||
background: var(--sr-bg);
|
||||
border: 1px solid var(--aa-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
.find::placeholder { color: var(--sr-muted); }
|
||||
.status { margin-left: auto; min-width: 0; display: flex; align-items: center; gap: 12px; font-size: 12px; color: var(--sr-muted); white-space: nowrap; }
|
||||
.status .sdot { width: 7px; height: 7px; border-radius: 50%; background: var(--sr-muted); opacity: 0.5; display: inline-block; margin-right: 5px; }
|
||||
.status .is-busy .sdot { background: var(--aa-accent-text); opacity: 1; animation: aa-pulse 1.2s ease-in-out infinite; }
|
||||
.status .who { color: var(--sr-fg); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.status > span:first-child { min-width: 0; display: inline-flex; align-items: center; }
|
||||
.status .nfail {
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--sr-fail);
|
||||
border: 0;
|
||||
background: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
@keyframes aa-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
|
||||
|
||||
.icon { display: inline-flex; }
|
||||
.icon svg { width: 12px; height: 12px; flex: none; }
|
||||
.link {
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--aa-accent-text);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ---- the list ---- */
|
||||
.list-wrap { position: relative; flex: 1; min-height: 0; }
|
||||
.list { position: absolute; inset: 0; overflow: auto; }
|
||||
.empty { margin: 0; padding: 14px 16px; color: var(--sr-muted); }
|
||||
.latest {
|
||||
position: absolute;
|
||||
right: 16px;
|
||||
bottom: 10px;
|
||||
z-index: 2;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--sr-accent);
|
||||
background: var(--sr-bg);
|
||||
color: var(--aa-accent-text);
|
||||
border-radius: 12px;
|
||||
padding: 2px 10px 2px 8px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
.latest svg { width: 10px; height: 10px; }
|
||||
|
||||
/* ---- the step rail, as a list of calls ---- */
|
||||
.step { padding: 0 10px 0 12px; }
|
||||
.step.is-hidden { display: none; }
|
||||
.step::before { left: calc(12px + var(--sr-dot) / 2 - 1px); }
|
||||
.step.is-last::before { display: none; }
|
||||
/* The thread takes the accent once the call has ended, failed or not. */
|
||||
.step.is-ended::before { background: var(--sr-accent); }
|
||||
.dot { font-size: 10.5px; letter-spacing: -0.02em; }
|
||||
.dot .icon svg { width: 11px; height: 11px; }
|
||||
/* A read passed too, but changed nothing: the hollow dot. */
|
||||
.step.is-read.is-done .dot { background: var(--sr-bg); border-color: var(--sr-accent); color: var(--aa-accent-text); }
|
||||
.step.is-running .dot { color: var(--aa-accent-text); }
|
||||
.step.is-dialog .dot { background: var(--aa-tint); border-color: var(--sr-accent); color: var(--aa-accent-text); }
|
||||
.step-head:hover .step-title { text-decoration: underline; text-decoration-color: var(--sr-rule); text-underline-offset: 3px; }
|
||||
.step-what .res.is-run { color: var(--aa-accent-text); }
|
||||
.step-what .pressed {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
color: var(--sr-fg);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
}
|
||||
.failure { margin: 0 0 6px; padding: 5px 8px; font-size: 12px; overflow-wrap: anywhere; }
|
||||
|
||||
/* A read is one quiet line: title and target side by side, no weight. */
|
||||
.step.is-read .dot { margin-top: 2px; }
|
||||
.step.is-read::before { top: calc(2px + var(--sr-dot)); }
|
||||
.step.is-read .step-head { display: flex; align-items: baseline; gap: 8px; padding: 2px 4px 2px 0; min-width: 0; }
|
||||
.step.is-read .step-title { font-weight: 400; color: var(--sr-muted); white-space: nowrap; }
|
||||
.step.is-read .step-what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.step.is-read.is-open .step-what { white-space: normal; }
|
||||
|
||||
.step-side { align-self: start; align-items: center; justify-content: flex-end; gap: 10px; font-size: 12px; color: var(--sr-muted); white-space: nowrap; }
|
||||
.step.is-read .step-side { padding-top: 3px; }
|
||||
.src { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 140px; }
|
||||
.src-name { overflow: hidden; text-overflow: ellipsis; }
|
||||
.src.same .src-name { display: none; }
|
||||
.clock { width: 54px; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.time { width: 50px; text-align: right; }
|
||||
.step.is-running > .step-side .time { color: var(--aa-accent-text); }
|
||||
/* ---- an opened step: its request and its response, as JSON ---- */
|
||||
.kv-head { display: flex; align-items: baseline; gap: 10px; margin: 6px 0 3px; font-weight: 600; }
|
||||
.kv-head .meta { font-weight: 400; color: var(--sr-muted); min-width: 0; overflow-wrap: anywhere; }
|
||||
.kv-head .link { margin-left: auto; }
|
||||
.args { margin: 0; }
|
||||
.args.plain dd { font-family: inherit; font-size: 12px; }
|
||||
.none { margin: 0; color: var(--sr-muted); }
|
||||
/* Long lines wrap: a pane this narrow shows a value whole rather than behind a sideways scroll, whose bar WebKit would
|
||||
paint over the heading below. */
|
||||
.raw { margin: 0; max-height: 240px; line-height: 1.45; color: var(--sr-fg); background: var(--sr-bg); white-space: pre-wrap; overflow-wrap: anywhere; overflow-x: hidden; }
|
||||
.raw.is-note { color: var(--sr-muted); font-family: inherit; white-space: normal; }
|
||||
.raw .j-key { color: var(--code-key); }
|
||||
.raw .j-string { color: var(--code-string); }
|
||||
.raw .j-number { color: var(--code-number); }
|
||||
.raw .j-literal { color: var(--code-keyword); }
|
||||
.raw .j-punct { color: var(--code-punct); }
|
||||
.raw .mask { color: var(--sr-muted); letter-spacing: 0.1em; }
|
||||
.files { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 6px; }
|
||||
.thumb { width: 168px; cursor: pointer; }
|
||||
|
||||
/* ---- a run's own steps, nested under its row as Action Replay lists them ---- */
|
||||
.rail.nested { padding: 0 0 6px; }
|
||||
.rail.nested .step { --sr-dot: 16px; padding-left: 0; padding-right: 0; font-size: 12.5px; }
|
||||
.rail.nested .step::before { left: calc(var(--sr-dot) / 2 - 1px); }
|
||||
.rail.nested .dot { font-size: 9.5px; }
|
||||
.rail.nested .step.is-open { background: transparent; }
|
||||
|
||||
/* A narrow pane (docked right, a small floating window) keeps the rail and drops the extras. */
|
||||
@container pane (max-width: 560px) {
|
||||
.clock, .src-name, .t-opt, .status .counts { display: none !important; }
|
||||
.find { flex: 1 1 90px; width: auto; min-width: 90px; }
|
||||
.status { margin-left: 0; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.status .is-busy .sdot { animation: none; }
|
||||
}
|
||||
|
|
@ -989,6 +989,9 @@ function PrunePermissionDraftBookkeeping(draft) {
|
|||
delete draft.additions[category];
|
||||
}
|
||||
|
||||
// The permissions that are a yes/no switch rather than a list of targets.
|
||||
const BOOLEAN_PERMISSIONS = new Set(["threading", "tools"]);
|
||||
|
||||
// A permission grant can arrive while the tab is open. Merge the latest stored list into the
|
||||
// rows on screen, but keep every unsaved value the user typed and let the draft win a conflict.
|
||||
// Edits are keyed by the original source value, so a grant that adds or reorders rows does not
|
||||
|
|
@ -999,7 +1002,7 @@ function MergePermissionSource(draft, sourcePermissions) {
|
|||
const nextPending = {};
|
||||
|
||||
for (const [category, entries] of Object.entries(sourcePermissions || {})) {
|
||||
if (category === "threading" && typeof entries === "boolean") {
|
||||
if (BOOLEAN_PERMISSIONS.has(category) && typeof entries === "boolean") {
|
||||
nextValues[category] = entries;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -1108,6 +1111,7 @@ function RenderPermissions(plugin) {
|
|||
["network_socket", "permissions_network_socket", "Network sockets"],
|
||||
["process", "permissions_process", "Processes"],
|
||||
["threading", "permissions_threading", "Threading"],
|
||||
["tools", "permissions_tools", "OrcaSlicer tools"],
|
||||
["events", "permissions_events", "Events"]
|
||||
];
|
||||
const categoryGuidance = {
|
||||
|
|
@ -1117,6 +1121,7 @@ function RenderPermissions(plugin) {
|
|||
network_socket: [null, "https://example.com"],
|
||||
process: [T("permissions_process_help", "Executable grants cover all arguments. CommandLine: entries cover only the exact command line."), T("permissions_process_placeholder", "Executable or command name")],
|
||||
threading: [T("permissions_threading_help_short", "Allow this plugin to create threads."), ""],
|
||||
tools: [T("permissions_tools_help_short", "Allow this plugin to call OrcaSlicer's tools, as AI agents do: change your project, presets and files, run post-processing scripts, and answer dialogs, permission requests included."), ""],
|
||||
events: [T("permissions_events_help", "Enter a category and event separated by a colon, such as Socket:socket.__new__."), T("permissions_events_placeholder", "Socket:socket.__new__")]
|
||||
};
|
||||
const placeholder = document.createElement("label");
|
||||
|
|
@ -1196,7 +1201,7 @@ function RenderPermissions(plugin) {
|
|||
{ keys: ["fs_read", "fs_readwrite"], title: T("permissions_group_filesystem", "File system") },
|
||||
{ keys: ["network_http", "network_socket"], title: T("permissions_network_access_title", "Network access"),
|
||||
guidance: T("permissions_network_access_guidance", "Enter a full http:// or https:// URL; only its scheme and host are saved, so the grant covers every port, path, and query on that host. A network socket grant also accepts a bare host name or IP address, with or without a port, and covers every port on that host. Other schemes are not accepted. Grants in either list are checked for HTTP and socket access.") },
|
||||
{ keys: ["process", "threading"], title: T("permissions_group_execution", "Execution") },
|
||||
{ keys: ["process", "threading", "tools"], title: T("permissions_group_execution", "Execution") },
|
||||
{ keys: ["events"], title: T("permissions_group_events", "Audit events") }
|
||||
];
|
||||
const groupBodies = new Map();
|
||||
|
|
@ -1264,7 +1269,7 @@ function RenderPermissions(plugin) {
|
|||
description.appendChild(guidance);
|
||||
}
|
||||
const entries = draft.values[key];
|
||||
const available = key === "threading" ? typeof entries === "boolean" : Array.isArray(entries);
|
||||
const available = BOOLEAN_PERMISSIONS.has(key) ? typeof entries === "boolean" : Array.isArray(entries);
|
||||
if (!available) {
|
||||
const unavailable = document.createElement("p");
|
||||
unavailable.className = "permission-notice";
|
||||
|
|
@ -1274,16 +1279,16 @@ function RenderPermissions(plugin) {
|
|||
continue;
|
||||
}
|
||||
|
||||
const categoryEnabled = installed && (key === "threading"
|
||||
const categoryEnabled = installed && (BOOLEAN_PERMISSIONS.has(key)
|
||||
? typeof plugin.permissions?.[key] === "boolean"
|
||||
: Array.isArray(plugin.permissions?.[key]));
|
||||
if (key === "threading") {
|
||||
if (BOOLEAN_PERMISSIONS.has(key)) {
|
||||
const threadLabel = document.createElement("label");
|
||||
threadLabel.className = "permission-thread-toggle";
|
||||
const threadCheckbox = document.createElement("input");
|
||||
threadCheckbox.type = "checkbox";
|
||||
threadCheckbox.setAttribute("role", "switch");
|
||||
threadCheckbox.id = "permission-thread-toggle";
|
||||
threadCheckbox.id = `permission-${key}-toggle`;
|
||||
threadCheckbox.checked = entries;
|
||||
threadCheckbox.disabled = !categoryEnabled;
|
||||
threadCheckbox.setAttribute("aria-labelledby", heading.id);
|
||||
|
|
|
|||
|
|
@ -49,3 +49,18 @@ test("update control stays hidden when no update is available, even while loadin
|
|||
|
||||
assert.equal(button.hidden, true);
|
||||
});
|
||||
|
||||
test("a permission source's boolean switches reach the draft with their values", () => {
|
||||
const dialog = loadPluginDialog();
|
||||
const draft = { values: {}, edits: {}, additions: {} };
|
||||
|
||||
dialog.MergePermissionSource(draft, { threading: true, tools: false, full_access: false, fs_read: ["/a"] });
|
||||
|
||||
assert.equal(draft.values.threading, true);
|
||||
assert.equal(draft.values.tools, false, "the OrcaSlicer tools switch shows its stored value");
|
||||
assert.deepEqual(Array.from(draft.values.fs_read), ["/a"]);
|
||||
assert.equal(draft.values.full_access, undefined, "full access is its own control, not a permission row");
|
||||
|
||||
dialog.MergePermissionSource(draft, { threading: true, tools: true, fs_read: [] });
|
||||
assert.equal(draft.values.tools, true);
|
||||
});
|
||||
|
|
|
|||
128
resources/web/dialog/RunScript/index.html
Normal file
128
resources/web/dialog/RunScript/index.html
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Run Script</title>
|
||||
<link rel="stylesheet" type="text/css" href="../css/theme.css" />
|
||||
<link rel="stylesheet" type="text/css" href="../js/code_editor.css" />
|
||||
<link rel="stylesheet" type="text/css" href="./style.css" />
|
||||
<script type="text/javascript" src="../../include/i18n.js"></script>
|
||||
<script type="text/javascript" src="../js/globalapi.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ace.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ext-language_tools.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/ext-searchbox.js"></script>
|
||||
<script type="text/javascript" src="../../include/ace/mode-python.js"></script>
|
||||
<script type="text/javascript" src="../js/code_editor.js"></script>
|
||||
<script type="text/javascript" src="./run_script_model.js"></script>
|
||||
<script type="text/javascript" src="./python_editor.js"></script>
|
||||
<script type="text/javascript" src="./run_script.js"></script>
|
||||
</head>
|
||||
<body onload="OnInit()">
|
||||
<div class="panel">
|
||||
<header class="toolbar">
|
||||
<span id="file-chip" class="chip" hidden>
|
||||
<span id="file-name"></span>
|
||||
<span id="file-edited" class="edited" hidden data-i18n="edited">(edited)</span>
|
||||
</span>
|
||||
<button type="button" id="new" class="btn" data-i18n="new">New</button>
|
||||
<span class="menu-wrap">
|
||||
<button type="button" id="open" class="btn" aria-haspopup="menu" aria-expanded="false" aria-controls="open-menu">
|
||||
<span data-i18n="open">Open…</span><span class="caret-d" aria-hidden="true"></span>
|
||||
</button>
|
||||
<div id="open-menu" class="menu" role="menu" hidden>
|
||||
<button type="button" id="open-file" class="menu-item" role="menuitem" data-i18n="open">Open…</button>
|
||||
<div class="menu-label" data-i18n="recent_scripts">Recent scripts</div>
|
||||
<div id="open-recent"></div>
|
||||
<div class="menu-rule" role="separator"></div>
|
||||
<button type="button" id="close-script" class="menu-item" role="menuitem" data-i18n="close_script">Close script</button>
|
||||
</div>
|
||||
</span>
|
||||
<button type="button" id="save" class="btn" data-i18n="save">Save</button>
|
||||
<span class="sep" aria-hidden="true"></span>
|
||||
<button type="button" id="run-all" class="btn primary">
|
||||
<span class="tri" aria-hidden="true"></span><span data-i18n="run_all">Run all</span><span id="run-all-key" class="key"></span>
|
||||
</button>
|
||||
<button type="button" id="run-cell" class="btn">
|
||||
<span class="tri" aria-hidden="true"></span><span data-i18n="run_cell">Run cell</span><span id="run-cell-key" class="key"></span>
|
||||
</button>
|
||||
<button type="button" id="stop" class="btn stop"><span class="sq" aria-hidden="true"></span><span data-i18n="stop">Stop</span></button>
|
||||
<button type="button" id="restart" class="btn" data-i18n="restart">Restart session</button>
|
||||
<span class="menu-wrap">
|
||||
<button type="button" id="cells" class="btn" aria-haspopup="menu" aria-expanded="false" aria-controls="cells-menu">
|
||||
<span class="cells-glyph" aria-hidden="true"></span><span data-i18n="cells">Cells</span><span class="caret-d" aria-hidden="true"></span>
|
||||
</button>
|
||||
<div id="cells-menu" class="menu" role="menu" hidden>
|
||||
<div class="menu-label" data-i18n="show_cells_with">Show cells with</div>
|
||||
<button type="button" class="menu-item" role="menuitemradio" data-style="margin" data-i18n="cells_margin">Margin bars only</button>
|
||||
<button type="button" class="menu-item" role="menuitemradio" data-style="dividers" data-i18n="cells_dividers">Dividers</button>
|
||||
<button type="button" class="menu-item" role="menuitemradio" data-style="bands" data-i18n="cells_bands">Header bands</button>
|
||||
<button type="button" class="menu-item" role="menuitemradio" data-style="shaded" data-i18n="cells_shaded">Shaded cells</button>
|
||||
<div class="menu-rule" role="separator"></div>
|
||||
<button type="button" id="cells-highlight" class="menu-item" role="menuitemcheckbox" data-i18n="cells_highlight">Highlight the cell at the cursor</button>
|
||||
</div>
|
||||
</span>
|
||||
<span id="session" class="session" role="status" aria-live="polite"></span>
|
||||
</header>
|
||||
|
||||
<main id="panes" class="body" data-hidden="">
|
||||
<button type="button" id="editor-strip" class="strip strip-editor" data-i18n-title="show_editor" data-i18n-aria-label="show_editor"
|
||||
title="Show the editor" aria-label="Show the editor">
|
||||
<span class="strip-chev" aria-hidden="true"><svg width="8" height="8" viewBox="0 0 8 8"><path d="M2.5 1 5.5 4l-3 3" /></svg></span>
|
||||
<span id="editor-strip-cells" class="strip-cells" aria-hidden="true"></span>
|
||||
<span id="editor-strip-name" class="strip-label"></span>
|
||||
</button>
|
||||
<section id="editor-col" class="col editor-col">
|
||||
<div id="editor" class="editor"></div>
|
||||
<p id="editor-empty" class="placeholder-text" hidden data-i18n="empty_editor">Open a script, or start a new one.</p>
|
||||
</section>
|
||||
<div id="split" class="split" role="separator" tabindex="0" aria-orientation="vertical" aria-controls="editor-col"
|
||||
aria-valuemin="0" aria-valuemax="100" aria-valuenow="60" data-i18n-title="split_tip" data-i18n-aria-label="split_label"
|
||||
title="Drag to share the width between the editor and the console. Double-click to reset it." aria-label="Width of the editor">
|
||||
<div class="grip">
|
||||
<button type="button" id="hide-editor" data-i18n-title="hide_editor" data-i18n-aria-label="hide_editor"
|
||||
title="Hide the editor" aria-label="Hide the editor">
|
||||
<svg width="8" height="8" viewBox="0 0 8 8" aria-hidden="true"><path d="M5.5 1 2.5 4l3 3" /></svg></button>
|
||||
<button type="button" id="hide-console" data-i18n-title="hide_console" data-i18n-aria-label="hide_console"
|
||||
title="Hide the console" aria-label="Hide the console">
|
||||
<svg width="8" height="8" viewBox="0 0 8 8" aria-hidden="true"><path d="M2.5 1 5.5 4l-3 3" /></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="col side">
|
||||
<div id="console" class="console">
|
||||
<div id="log" class="log" role="log" aria-live="polite"></div>
|
||||
<div class="prompt">
|
||||
<label class="prompt-line" for="prompt-input">
|
||||
<span class="p" aria-hidden="true">>>></span>
|
||||
<input id="prompt-input" type="text" spellcheck="false" autocomplete="off"
|
||||
data-i18n-placeholder="console_placeholder" placeholder="Python, run in the session" />
|
||||
</label>
|
||||
<button type="button" id="clear" class="btn small" data-i18n="clear">Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="start" class="side-msg" hidden>
|
||||
<h3 data-i18n="start_script">Start a script</h3>
|
||||
<p id="start-text"></p>
|
||||
<div class="row">
|
||||
<button type="button" id="start-new" class="btn primary" data-i18n="new_script">New script</button>
|
||||
<button type="button" id="start-open" class="btn" data-i18n="open_script">Open a script…</button>
|
||||
</div>
|
||||
<p class="label-sm" data-i18n="recent_scripts">Recent scripts</p>
|
||||
<ul id="start-recent" class="recent"></ul>
|
||||
<p id="start-no-recent" class="label-sm" data-i18n="no_recent">No recent scripts</p>
|
||||
</div>
|
||||
</section>
|
||||
<button type="button" id="console-strip" class="strip strip-console" title="Show the console" aria-label="Show the console">
|
||||
<span class="strip-chev" aria-hidden="true"><svg width="8" height="8" viewBox="0 0 8 8"><path d="M5.5 1 2.5 4l3 3" /></svg></span>
|
||||
<span class="strip-label" aria-hidden="true" data-i18n="console">Console</span>
|
||||
<span id="console-news" class="news" aria-hidden="true"></span>
|
||||
</button>
|
||||
</main>
|
||||
|
||||
<footer id="status" class="statusline" hidden>
|
||||
<span id="status-main"></span>
|
||||
<span id="status-detail"></span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
78
resources/web/dialog/RunScript/python_editor.js
Normal file
78
resources/web/dialog/RunScript/python_editor.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// The Run Script editor's Python: Ace's Python mode, with a line that starts a cell (`# %%`) as its own token and
|
||||
// Return's indent from pythonNextIndent(), and the suggestions for this build's tools and the orca.host API. The editor is
|
||||
// set up by ../js/code_editor.js; the logic is run_script_model.js's.
|
||||
|
||||
// `linesBefore(line)` gives the text before the line Return splits (`line`, its part before the caret), for the
|
||||
// triple-quoted string open where that line starts.
|
||||
function definePythonMode(linesBefore) {
|
||||
ace.define("ace/mode/orca_python_highlight_rules",
|
||||
["require", "exports", "module", "ace/lib/oop", "ace/mode/python_highlight_rules"], (require, exports) => {
|
||||
const oop = require("ace/lib/oop");
|
||||
const PythonHighlightRules = require("ace/mode/python_highlight_rules").PythonHighlightRules;
|
||||
function OrcaPythonHighlightRules() {
|
||||
PythonHighlightRules.call(this);
|
||||
// Before Python's own comment rule, which would take the line.
|
||||
this.$rules.start.unshift({ token: "cell-marker", regex: "^# %%.*$" });
|
||||
}
|
||||
oop.inherits(OrcaPythonHighlightRules, PythonHighlightRules);
|
||||
exports.OrcaPythonHighlightRules = OrcaPythonHighlightRules;
|
||||
});
|
||||
ace.define("ace/mode/orca_python",
|
||||
["require", "exports", "module", "ace/lib/oop", "ace/mode/python", "ace/mode/orca_python_highlight_rules"], (require, exports) => {
|
||||
const oop = require("ace/lib/oop");
|
||||
const PythonMode = require("ace/mode/python").Mode;
|
||||
function Mode() {
|
||||
PythonMode.call(this);
|
||||
this.HighlightRules = require("ace/mode/orca_python_highlight_rules").OrcaPythonHighlightRules;
|
||||
}
|
||||
oop.inherits(Mode, PythonMode);
|
||||
Mode.prototype.$id = "ace/mode/orca_python";
|
||||
Mode.prototype.getNextLineIndent = (state, line, tab) =>
|
||||
RunScriptModel.pythonNextIndent(line, tab, RunScriptModel.openQuote(linesBefore(line)));
|
||||
// pythonNextIndent() already outdents after a statement that ends a block.
|
||||
Mode.prototype.checkOutdent = () => false;
|
||||
exports.Mode = Mode;
|
||||
});
|
||||
}
|
||||
|
||||
// A tool's arguments for the detail line: each name, with its allowed values when it has some.
|
||||
function toolArgsText(tool) {
|
||||
return Object.entries(tool.args || {})
|
||||
.map(([name, arg]) => (arg.enum ? name + ": " + arg.enum.join(" | ") : name))
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
// The completer the editor gets (code_editor.js's shape): the tools inside tools.call("…"), with their titles and
|
||||
// arguments, and the API one level below an orca.host path, with signatures and summaries. `source` holds the catalog
|
||||
// ({tools}) and the API's entries ({api}) as the host sends them.
|
||||
function pythonCompleter(source) {
|
||||
return {
|
||||
suggestionsAt(text, at) {
|
||||
const lineStart = text.lastIndexOf("\n", at - 1) + 1;
|
||||
const quote = RunScriptModel.openQuote(text.slice(0, Math.max(0, lineStart - 1)));
|
||||
const context = RunScriptModel.suggestContext(text.slice(lineStart, at), quote);
|
||||
if (!context) return null;
|
||||
const from = lineStart + context.from;
|
||||
const to = at + /^\w*/.exec(text.slice(at))[0].length;
|
||||
if (context.kind === "tool")
|
||||
return { kind: "tool", from, to, quote: text[from - 1],
|
||||
items: source.tools.map((tool) => ({ label: tool.name, detail: tool.title, info: toolArgsText(tool) })) };
|
||||
const prefix = context.path + ".";
|
||||
const items = [];
|
||||
for (const entry of source.api) {
|
||||
if (!entry.name.startsWith(prefix)) continue;
|
||||
const rest = entry.name.slice(prefix.length);
|
||||
if (!rest || rest.includes(".")) continue;
|
||||
items.push({ label: rest, detail: entry.kind, info: entry.signature + (entry.summary ? "\n" + entry.summary : "") });
|
||||
}
|
||||
return { kind: "api", from, to, items };
|
||||
},
|
||||
// A tool's name closes its string when nothing does yet.
|
||||
acceptEdit(text, found, item) {
|
||||
const closes = found.kind === "tool" && found.quote && text[found.to] !== found.quote;
|
||||
return { from: found.from, to: found.to, insert: item.label + (closes ? found.quote : ""), back: 0, reopen: false };
|
||||
},
|
||||
identifierRegexps: [/\w/],
|
||||
triggerCharacters: ['"', "'", "."],
|
||||
};
|
||||
}
|
||||
1046
resources/web/dialog/RunScript/run_script.js
Normal file
1046
resources/web/dialog/RunScript/run_script.js
Normal file
File diff suppressed because it is too large
Load diff
317
resources/web/dialog/RunScript/run_script.test.js
Normal file
317
resources/web/dialog/RunScript/run_script.test.js
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
"use strict";
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const model = require("./run_script_model.js");
|
||||
|
||||
test("a file without a marker is one cell", () => {
|
||||
assert.deepEqual(model.splitCells("x = 1\ny = 2\n"), [{ index: 1, start: 1, end: 3, title: "" }]);
|
||||
});
|
||||
|
||||
test("a marker on line 1 starts the first cell, and its text is the cell's title", () => {
|
||||
assert.deepEqual(model.splitCells("# %% Load\nx = 1\n# %%Slice \ny = 2"), [
|
||||
{ index: 1, start: 1, end: 2, title: "Load" },
|
||||
{ index: 2, start: 3, end: 4, title: "Slice" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("lines before the first marker are cell 1, and an indented marker is a comment", () => {
|
||||
assert.deepEqual(model.splitCells("import os\n\n# %% A\nif True:\n # %% not a cell\n x = 1"), [
|
||||
{ index: 1, start: 1, end: 2, title: "" },
|
||||
{ index: 2, start: 3, end: 6, title: "A" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("the cell at a line is the one whose lines hold it", () => {
|
||||
const cells = model.splitCells("a\n# %% B\nb\n# %% C\nc");
|
||||
assert.equal(model.cellAt(cells, 1).index, 1);
|
||||
assert.equal(model.cellAt(cells, 3).index, 2);
|
||||
assert.equal(model.cellAt(cells, 5).index, 3);
|
||||
});
|
||||
|
||||
test("Return indents after a colon or an opening bracket, outdents after a statement that ends a block", () => {
|
||||
const tab = " ";
|
||||
assert.equal(model.pythonNextIndent("def f(): # c", tab), " ");
|
||||
assert.equal(model.pythonNextIndent("x = 1", tab), "");
|
||||
assert.equal(model.pythonNextIndent(" return x", tab), "");
|
||||
assert.equal(model.pythonNextIndent(" pass", tab), "");
|
||||
assert.equal(model.pythonNextIndent("foo(", tab), " ");
|
||||
assert.equal(model.pythonNextIndent('x = "a:"', tab), "");
|
||||
assert.equal(model.pythonNextIndent("# a:", tab), "");
|
||||
assert.equal(model.pythonNextIndent("return", tab), "");
|
||||
assert.equal(model.pythonNextIndent(" if x:", tab), " ");
|
||||
assert.equal(model.pythonNextIndent(" returned = 1", tab), " ");
|
||||
});
|
||||
|
||||
test("suggestions come inside tools.call's string and after orca.host., never inside another string", () => {
|
||||
assert.deepEqual(model.suggestContext('tools.call("sl'), { kind: "tool", from: 12, typed: "sl" });
|
||||
assert.deepEqual(model.suggestContext("orca.host.tools.call('"), { kind: "tool", from: 22, typed: "" });
|
||||
assert.deepEqual(model.suggestContext("orca.host.ui.me"), { kind: "api", path: "orca.host.ui", from: 13, typed: "me" });
|
||||
assert.deepEqual(model.suggestContext("x = orca.host."), { kind: "api", path: "orca.host", from: 14, typed: "" });
|
||||
assert.equal(model.suggestContext('x = "tools.call("'), null);
|
||||
assert.equal(model.suggestContext("# orca.host.ui"), null);
|
||||
});
|
||||
|
||||
test("a traceback's lines in the script are links, other files' and the console's are not", () => {
|
||||
const script = "C:\\scripts\\demo.py";
|
||||
const traceback = 'Traceback (most recent call last):\n' +
|
||||
' File "C:\\scripts\\demo.py", line 7, in <module>\n' +
|
||||
' File "C:\\lib\\helper.py", line 3, in f\n' +
|
||||
' File "<console>", line 1, in <module>\n' +
|
||||
' File "C:\\scripts\\demo.py", line 12\n' +
|
||||
"SyntaxError: invalid syntax\n";
|
||||
const links = model.tracebackLinks(traceback, script);
|
||||
assert.deepEqual(links.map((l) => l.line), [7, 12]);
|
||||
for (const link of links)
|
||||
assert.match(traceback.slice(link.start, link.end), /^File "C:\\scripts\\demo\.py", line \d+$/);
|
||||
});
|
||||
|
||||
test("Run all's margin: every cell ran when it finished", () => {
|
||||
const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc");
|
||||
assert.deepEqual(model.railAfterFile(cells, [0, 1, 2], { status: "finished", error_line: 0, executed: true, cells_reported: true }),
|
||||
["ran", "ran", "ran"]);
|
||||
});
|
||||
|
||||
test("Run all's margin: a raise at a line marks the cells before it ran, its own failed, the rest not run", () => {
|
||||
const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc");
|
||||
const raised = { status: "raised", error_line: 3, executed: true };
|
||||
assert.deepEqual(model.railAfterFile(cells, [0, 1], Object.assign({ cells_reported: true }, raised)), ["ran", "failed", "idle"]);
|
||||
assert.deepEqual(model.railAfterFile(cells, [], Object.assign({ cells_reported: false }, raised)), ["ran", "failed", "idle"]);
|
||||
});
|
||||
|
||||
test("Run all's margin: a syntax error marks its cell failed and none ran", () => {
|
||||
const cells = model.splitCells("a\n# %% b\nb(\n# %% c\nc");
|
||||
assert.deepEqual(model.railAfterFile(cells, [], { status: "raised", error_line: 3, executed: false, cells_reported: false }),
|
||||
["idle", "failed", "idle"]);
|
||||
assert.deepEqual(model.railAfterFile(cells, [], { status: "raised", error_line: 0, executed: false, cells_reported: false }),
|
||||
["idle", "idle", "idle"]);
|
||||
});
|
||||
|
||||
test("Run all's margin: a stop marks the last reported cell, and none without reports", () => {
|
||||
const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc");
|
||||
assert.deepEqual(model.railAfterFile(cells, [0, 1], { status: "cancelled", error_line: 0, executed: true, cells_reported: true }),
|
||||
["ran", "failed", "idle"]);
|
||||
assert.deepEqual(model.railAfterFile(cells, [], { status: "cancelled", error_line: 0, executed: true, cells_reported: false }),
|
||||
["idle", "idle", "idle"]);
|
||||
});
|
||||
|
||||
test("a cell is edited when its text differs from the text that ran", () => {
|
||||
assert.equal(model.edited("x = 1\n", "x = 1\n"), false);
|
||||
assert.equal(model.edited("x = 2\n", "x = 1\n"), true);
|
||||
});
|
||||
|
||||
test("a script's text is compared with the line breaks the editor holds", () => {
|
||||
assert.equal(model.editorText("a = 1\r\nb = 2\r\n"), "a = 1\nb = 2\n");
|
||||
assert.equal(model.editorText("a = 1\rb = 2\n"), "a = 1\nb = 2\n");
|
||||
assert.equal(model.editorText("a = 1\nb = 2\n"), "a = 1\nb = 2\n");
|
||||
});
|
||||
|
||||
test("a triple-quoted string open at a line's start is found from the lines before it", () => {
|
||||
assert.equal(model.openQuote('def f():\n """Doc:'), '"""');
|
||||
assert.equal(model.openQuote("s = '''a\nb"), "'''");
|
||||
assert.equal(model.openQuote('s = """a"""\n# """'), null);
|
||||
assert.equal(model.openQuote('s = "a"\nt = 1'), null);
|
||||
});
|
||||
|
||||
test("Return inside a multi-line string keeps the indent, and code after the string closes is read as code", () => {
|
||||
const tab = " ";
|
||||
assert.equal(model.pythonNextIndent(' """Doc:', tab), " ");
|
||||
assert.equal(model.pythonNextIndent(" return the value", tab, '"""'), " ");
|
||||
assert.equal(model.pythonNextIndent(' return the value"""', tab, '"""'), " ");
|
||||
assert.equal(model.pythonNextIndent(' """ + f(', tab, '"""'), " ");
|
||||
});
|
||||
|
||||
test("no suggestions inside a multi-line string, and suggestions again after it closes", () => {
|
||||
assert.equal(model.suggestContext('tools.call("', '"""'), null);
|
||||
assert.equal(model.suggestContext("orca.host.", "'''"), null);
|
||||
assert.equal(model.suggestContext('"""; tools.call("', '"""').kind, "tool");
|
||||
});
|
||||
|
||||
test("Clear keeps only the blocks a run still writes to: its own and the cell it runs now", () => {
|
||||
assert.deepEqual(model.keptByClear(null), []);
|
||||
assert.deepEqual(model.keptByClear({ kind: "cell", block: "Cell 2" }), ["Cell 2"]);
|
||||
assert.deepEqual(model.keptByClear({ kind: "console", block: ">>> x" }), [">>> x"]);
|
||||
assert.deepEqual(model.keptByClear({ kind: "file", block: "Run all" }), ["Run all"]);
|
||||
assert.deepEqual(model.keptByClear({ kind: "file", block: "Run all", cellBlock: "Cell 3" }), ["Run all", "Cell 3"]);
|
||||
});
|
||||
|
||||
test("the cell view is the saved one, and Dividers with the cell at the cursor highlighted when nothing usable is saved", () => {
|
||||
assert.deepEqual(model.cellView(undefined), { style: "dividers", highlight: true });
|
||||
assert.deepEqual(model.cellView({ style: "", highlight: true }), { style: "dividers", highlight: true });
|
||||
assert.deepEqual(model.cellView({ style: "zebra", highlight: true }), { style: "dividers", highlight: true });
|
||||
assert.deepEqual(model.cellView({ style: "bands", highlight: false }), { style: "bands", highlight: false });
|
||||
for (const style of ["margin", "dividers", "bands", "shaded"]) assert.equal(model.cellView({ style }).style, style);
|
||||
});
|
||||
|
||||
test("Dividers draw a line above every cell but one starting on the first line", () => {
|
||||
const marks = (text) => model.cellMarks(model.splitCells(text), text.split("\n"), { style: "dividers", highlight: false }, 0);
|
||||
assert.deepEqual(marks("x = 1\n# %% B\ny\n# %% C\nz"), [
|
||||
{ from: 1, to: 1, cls: "cell-divider" },
|
||||
{ from: 3, to: 3, cls: "cell-divider" },
|
||||
]);
|
||||
assert.deepEqual(marks("# %% A\nx\n# %% B\ny"), [{ from: 2, to: 2, cls: "cell-divider" }]);
|
||||
assert.deepEqual(marks("x = 1\ny = 2"), []);
|
||||
});
|
||||
|
||||
test("Header bands mark each cell's # %% line, not the lines before the first marker", () => {
|
||||
const marks = (text) => model.cellMarks(model.splitCells(text), text.split("\n"), { style: "bands", highlight: false }, 0);
|
||||
assert.deepEqual(marks("import os\n# %% B\ny"), [{ from: 1, to: 1, cls: "cell-band" }]);
|
||||
assert.deepEqual(marks("# %% A\nx\n# %%\ny"), [
|
||||
{ from: 0, to: 0, cls: "cell-band" },
|
||||
{ from: 2, to: 2, cls: "cell-band" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("Shaded cells shade every second cell, and Margin bars only marks no rows", () => {
|
||||
const text = "# %% A\na\n# %% B\nb\n# %% C\nc\n# %% D\nd";
|
||||
const marks = (style) => model.cellMarks(model.splitCells(text), text.split("\n"), { style, highlight: false }, 0);
|
||||
assert.deepEqual(marks("shaded"), [
|
||||
{ from: 2, to: 3, cls: "cell-shade" },
|
||||
{ from: 6, to: 7, cls: "cell-shade" },
|
||||
]);
|
||||
assert.deepEqual(marks("margin"), []);
|
||||
});
|
||||
|
||||
test("the highlight covers the cell at the cursor in every style, under the style's own lines", () => {
|
||||
const text = "# %% A\na\n# %% B\nb1\nb2\n# %% C\nc";
|
||||
const marks = (style, highlight, current) =>
|
||||
model.cellMarks(model.splitCells(text), text.split("\n"), { style, highlight }, current);
|
||||
assert.deepEqual(marks("margin", true, 2), [{ from: 2, to: 4, cls: "cell-current" }]);
|
||||
assert.deepEqual(marks("dividers", true, 2), [
|
||||
{ from: 2, to: 4, cls: "cell-current" },
|
||||
{ from: 2, to: 2, cls: "cell-divider" },
|
||||
{ from: 5, to: 5, cls: "cell-divider" },
|
||||
]);
|
||||
assert.deepEqual(marks("shaded", true, 2), [
|
||||
{ from: 2, to: 4, cls: "cell-shade" },
|
||||
{ from: 2, to: 4, cls: "cell-current" },
|
||||
]);
|
||||
assert.deepEqual(marks("margin", false, 2), []);
|
||||
assert.deepEqual(marks("margin", true, 0), []);
|
||||
});
|
||||
|
||||
test("a JSON result splits into the tokens its highlight colours, each as Python wrote it", () => {
|
||||
const tokens = model.jsonTokens('{"a": [1.0, true, null, "x, y: z"]}').map((t) => [t.type, t.text]);
|
||||
assert.deepEqual(tokens, [
|
||||
["punct", "{"], ["key", '"a"'], ["punct", ":"], ["space", " "], ["punct", "["], ["number", "1.0"], ["punct", ","],
|
||||
["space", " "], ["literal", "true"], ["punct", ","], ["space", " "], ["literal", "null"], ["punct", ","], ["space", " "],
|
||||
["string", '"x, y: z"'], ["punct", "]"], ["punct", "}"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("a JSON result keeps an array or object on one line while it fits the width", () => {
|
||||
assert.equal(model.formatJson('{"offset": [128, 128, 0], "mirrored": false}'), '{"offset": [128, 128, 0], "mirrored": false}');
|
||||
});
|
||||
|
||||
test("a JSON result past the width takes a line per member, two spaces a level, keeping members that fit whole", () => {
|
||||
const text = '{"objects": [{"index": 0, "name": "3DBenchy", "offset": [128, 128, 0], "rotation": [0, 0, 0]}], "total": 1}';
|
||||
assert.equal(model.formatJson(text, 40), [
|
||||
"{",
|
||||
' "objects": [',
|
||||
" {",
|
||||
' "index": 0,',
|
||||
' "name": "3DBenchy",',
|
||||
' "offset": [128, 128, 0],',
|
||||
' "rotation": [0, 0, 0]',
|
||||
" }",
|
||||
" ],",
|
||||
' "total": 1',
|
||||
"}",
|
||||
].join("\n"));
|
||||
});
|
||||
|
||||
test("a JSON result's numbers, strings and empty members stay as Python wrote them", () => {
|
||||
const text = '[1.0, 12345678901234567890123, -1e-07, "a \\"b\\" [c], {d}: e", "\u00e9", [], {}]';
|
||||
assert.equal(model.formatJson(text, 20), [
|
||||
"[",
|
||||
" 1.0,",
|
||||
" 12345678901234567890123,",
|
||||
" -1e-07,",
|
||||
' "a \\"b\\" [c], {d}: e",',
|
||||
' "\u00e9",',
|
||||
" [],",
|
||||
" {}",
|
||||
"]",
|
||||
].join("\n"));
|
||||
});
|
||||
|
||||
test("text that isn't JSON is shown as it is", () => {
|
||||
assert.equal(model.formatJson("{'a': 1}"), "{'a': 1}");
|
||||
assert.equal(model.formatJson('{"a": [1, 2}'), '{"a": [1, 2}');
|
||||
});
|
||||
|
||||
test("a folded cell shows the last line it printed that has text", () => {
|
||||
assert.equal(model.lastLine("slicing plate 1\nslicing plate 2\n\n"), "slicing plate 2");
|
||||
assert.equal(model.lastLine("a\r\nb\r\n"), "b");
|
||||
assert.equal(model.lastLine("\n \n"), "");
|
||||
});
|
||||
|
||||
test("Add a cell puts a marker after a blank line at the end, with the caret where its title goes", () => {
|
||||
// The script ends with a newline, so its last line is empty.
|
||||
assert.deepEqual(model.addCellEdit(["x = 1", ""]), { at: { row: 1, column: 0 }, text: "\n# %% \n", caret: { row: 2, column: 5 } });
|
||||
assert.deepEqual(model.addCellEdit(["x = 1", "", ""]), { at: { row: 2, column: 0 }, text: "# %% \n", caret: { row: 2, column: 5 } });
|
||||
assert.deepEqual(model.addCellEdit(["x = 1"]), { at: { row: 0, column: 5 }, text: "\n\n# %% \n", caret: { row: 2, column: 5 } });
|
||||
assert.deepEqual(model.addCellEdit(["x = 1", " "]), { at: { row: 1, column: 4 }, text: "\n# %% \n", caret: { row: 2, column: 5 } });
|
||||
assert.deepEqual(model.addCellEdit([""]), { at: { row: 0, column: 0 }, text: "# %% \n", caret: { row: 0, column: 5 } });
|
||||
});
|
||||
|
||||
test("a JSON result whose layout would grow past four times its length stays on one line", () => {
|
||||
// Nested past the width at every level, its layout is mostly indentation.
|
||||
let text = '"' + "x".repeat(80) + '"';
|
||||
for (let level = 0; level < 60; ++level) text = '{"a": ' + text + "}";
|
||||
assert.equal(model.formatJson(text), text);
|
||||
});
|
||||
|
||||
test("the panel's split and hidden side come back as it kept them, and anything else as the default", () => {
|
||||
assert.deepEqual(model.paneLayout(undefined), { split: 0.6, hidden: "" });
|
||||
assert.deepEqual(model.paneLayout({ split: "0.35", hidden: "console" }), { split: 0.35, hidden: "console" });
|
||||
assert.deepEqual(model.paneLayout({ split: 0.7, hidden: "editor" }), { split: 0.7, hidden: "editor" });
|
||||
for (const split of ["", "x", 0, 1, -0.2, 1.5, NaN, null, undefined]) assert.equal(model.paneLayout({ split }).split, 0.6);
|
||||
assert.equal(model.paneLayout({ split: 0.5, hidden: "both" }).hidden, "");
|
||||
});
|
||||
|
||||
test("the divider leaves the editor 220 px and the console 200 px, or their shares of a pane too narrow for both", () => {
|
||||
assert.equal(model.clampSplit(0.1, 1000), 0.22);
|
||||
assert.equal(model.clampSplit(0.9, 1000), 0.8);
|
||||
assert.equal(model.clampSplit(0.5, 1000), 0.5);
|
||||
assert.equal(model.clampSplit(0.1, 300), 0.5238);
|
||||
assert.equal(model.clampSplit(0.9, 300), 0.5238);
|
||||
});
|
||||
|
||||
test("dragging the divider 48 px past a side's smallest width hides that side", () => {
|
||||
assert.deepEqual(model.dragSplit(500, 1000), { split: 0.5, hide: "" });
|
||||
assert.deepEqual(model.dragSplit(172, 1000), { split: 0.22, hide: "" });
|
||||
assert.deepEqual(model.dragSplit(171, 1000), { split: 0.22, hide: "editor" });
|
||||
assert.deepEqual(model.dragSplit(848, 1000), { split: 0.8, hide: "" });
|
||||
assert.deepEqual(model.dragSplit(849, 1000), { split: 0.8, hide: "console" });
|
||||
// A pane too narrow for both: each side hides 48 px past the point the divider stops at.
|
||||
assert.equal(model.dragSplit(157, 300).hide, "");
|
||||
assert.equal(model.dragSplit(100, 300).hide, "editor");
|
||||
assert.equal(model.dragSplit(210, 300).hide, "console");
|
||||
});
|
||||
|
||||
test("the divider's arrows move it a twentieth of the pane, Home and End to a side's smallest width", () => {
|
||||
assert.equal(model.splitByKey(0.6, "ArrowLeft", 1000), 0.55);
|
||||
assert.equal(model.splitByKey(0.6, "ArrowRight", 1000), 0.65);
|
||||
assert.equal(model.splitByKey(0.78, "ArrowRight", 1000), 0.8);
|
||||
assert.equal(model.splitByKey(0.6, "Home", 1000), 0.22);
|
||||
assert.equal(model.splitByKey(0.6, "End", 1000), 0.8);
|
||||
assert.equal(model.splitByKey(0.6, "a", 1000), null);
|
||||
});
|
||||
|
||||
test("the console's strip shows a run going, then new output, and a failed run until the next one", () => {
|
||||
assert.equal(model.consoleNews("", "output"), "fresh");
|
||||
assert.equal(model.consoleNews("", "start"), "running");
|
||||
assert.equal(model.consoleNews("running", "output"), "running");
|
||||
assert.equal(model.consoleNews("running", "finished"), "fresh");
|
||||
assert.equal(model.consoleNews("running", "failed"), "failed");
|
||||
assert.equal(model.consoleNews("failed", "output"), "failed");
|
||||
assert.equal(model.consoleNews("failed", "start"), "running");
|
||||
});
|
||||
|
||||
test("the console's side hides only while it shows the console, not the start page", () => {
|
||||
assert.equal(model.hiddenSide("console", true), "console");
|
||||
assert.equal(model.hiddenSide("console", false), "");
|
||||
assert.equal(model.hiddenSide("editor", false), "editor");
|
||||
assert.equal(model.hiddenSide("editor", true), "editor");
|
||||
assert.equal(model.hiddenSide("", true), "");
|
||||
});
|
||||
379
resources/web/dialog/RunScript/run_script_model.js
Normal file
379
resources/web/dialog/RunScript/run_script_model.js
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
// The Run Script page's pure logic: cells, Python's Return indent, where suggestions go, a traceback's links, the
|
||||
// margin after Run all, what Clear keeps, the rows each cell style marks, a JSON result's tokens and layout, a folded
|
||||
// cell's line, the edit Add a cell makes, and the divider between the editor and the console. Loaded by the page as a
|
||||
// script and by run_script.test.js as a module.
|
||||
(function (root, factory) {
|
||||
"use strict";
|
||||
const api = factory();
|
||||
if (typeof module === "object" && module.exports) module.exports = api;
|
||||
else root.RunScriptModel = api;
|
||||
})(typeof globalThis === "object" ? globalThis : this, function () {
|
||||
"use strict";
|
||||
|
||||
// A line that starts a cell: "# %%" in the first column; the rest of the line is the cell's title.
|
||||
const CELL_MARKER = /^# %%(.*)$/;
|
||||
|
||||
// The cells of `text`, 1-based lines: [{index, start, end, title}]. The lines before the first marker are cell 1.
|
||||
function splitCells(text) {
|
||||
const cells = [];
|
||||
let current = null;
|
||||
text.split("\n").forEach((raw, i) => {
|
||||
const line = i + 1;
|
||||
const marker = CELL_MARKER.exec(raw.replace(/\r$/, ""));
|
||||
if (marker) {
|
||||
if (current) current.end = line - 1;
|
||||
current = { index: cells.length + 1, start: line, end: line, title: marker[1].trim() };
|
||||
cells.push(current);
|
||||
} else if (!current) {
|
||||
current = { index: 1, start: 1, end: line, title: "" };
|
||||
cells.push(current);
|
||||
} else current.end = line;
|
||||
});
|
||||
return cells;
|
||||
}
|
||||
|
||||
// The cell whose lines hold `line`; the last cell for a line past the end.
|
||||
function cellAt(cells, line) {
|
||||
for (const cell of cells)
|
||||
if (line >= cell.start && line <= cell.end) return cell;
|
||||
return cells.length ? cells[cells.length - 1] : null;
|
||||
}
|
||||
|
||||
// Where `line` stands at `end`: in a string (its quote), in a comment, or in code. `quote` is the triple-quoted string
|
||||
// open when the line starts (openQuote()), if any.
|
||||
function stateAt(line, end, quote = null) {
|
||||
for (let i = 0; i < end; ++i) {
|
||||
if (quote) {
|
||||
if (line[i] === "\\") ++i;
|
||||
else if (line.startsWith(quote, i)) {
|
||||
i += quote.length - 1;
|
||||
quote = null;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const c = line[i];
|
||||
if (c === "#") return { quote: null, comment: true, at: i };
|
||||
if (c === '"' || c === "'") {
|
||||
quote = line.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
|
||||
i += quote.length - 1;
|
||||
}
|
||||
}
|
||||
return { quote, comment: false, at: end };
|
||||
}
|
||||
|
||||
// The line's code: what comes before a comment that isn't inside a string.
|
||||
function codeOf(line) {
|
||||
const state = stateAt(line, line.length);
|
||||
return state.comment ? line.slice(0, state.at) : line;
|
||||
}
|
||||
|
||||
// The triple-quoted string open at the end of `text` (the lines before the caret's line), or null: only such a string
|
||||
// runs on past its line.
|
||||
function openQuote(text) {
|
||||
let quote = null;
|
||||
for (const line of text.split("\n")) {
|
||||
const state = stateAt(line, line.length, quote);
|
||||
quote = state.quote && state.quote.length === 3 ? state.quote : null;
|
||||
}
|
||||
return quote;
|
||||
}
|
||||
|
||||
// Where the string `quote` that `line` starts inside closes: the index after its closing quote, or the line's length.
|
||||
function closeOf(line, quote) {
|
||||
for (let i = 0; i < line.length; ++i) {
|
||||
if (line[i] === "\\") ++i;
|
||||
else if (line.startsWith(quote, i)) return i + quote.length;
|
||||
}
|
||||
return line.length;
|
||||
}
|
||||
|
||||
// The indent Return gives the next line: the line's own, one level (`tab`) more when its code ends with a colon or an
|
||||
// opening bracket, one level less (not below none) when its statement ends a block (return, pass, raise, break,
|
||||
// continue). `quote` is the triple-quoted string open when the line starts: its text up to where it closes isn't code,
|
||||
// and a line that ends inside one keeps its indent.
|
||||
function pythonNextIndent(lineBeforeCaret, tab, quote = null) {
|
||||
const indent = /^\s*/.exec(lineBeforeCaret)[0];
|
||||
const end = stateAt(lineBeforeCaret, lineBeforeCaret.length, quote);
|
||||
if (end.quote && end.quote.length === 3) return indent;
|
||||
const code = codeOf(quote ? lineBeforeCaret.slice(closeOf(lineBeforeCaret, quote)) : lineBeforeCaret).trimEnd();
|
||||
if (/[:([{]$/.test(code)) return indent + tab;
|
||||
if (/^(return|pass|raise|break|continue)\b/.test(code.trim())) return indent.slice(0, Math.max(0, indent.length - tab.length));
|
||||
return indent;
|
||||
}
|
||||
|
||||
// What suggestions go at the end of `lineBeforeCaret`: the tools inside the string tools.call( opens, or the API one
|
||||
// level below an orca.host path; null in another string, in a comment or anywhere else. `quote` is the triple-quoted
|
||||
// string open when the line starts.
|
||||
function suggestContext(lineBeforeCaret, quote = null) {
|
||||
const tool = /((?:\w+\.)*tools\.call\(\s*)(["'])(\w*)$/.exec(lineBeforeCaret);
|
||||
if (tool) {
|
||||
const state = stateAt(lineBeforeCaret, tool.index, quote);
|
||||
if (state.quote || state.comment) return null;
|
||||
return { kind: "tool", from: lineBeforeCaret.length - tool[3].length, typed: tool[3] };
|
||||
}
|
||||
const api = /\b(orca\.host(?:\.\w+)*)\.(\w*)$/.exec(lineBeforeCaret);
|
||||
if (api) {
|
||||
const state = stateAt(lineBeforeCaret, api.index, quote);
|
||||
if (state.quote || state.comment) return null;
|
||||
return { kind: "api", path: api[1], from: lineBeforeCaret.length - api[2].length, typed: api[2] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// The spans of `traceback` that name a line of the script (File "<scriptFile>", line N), with that line.
|
||||
function tracebackLinks(traceback, scriptFile) {
|
||||
const links = [];
|
||||
const pattern = /File "([^"]*)", line (\d+)/g;
|
||||
let m;
|
||||
while ((m = pattern.exec(traceback)))
|
||||
if (m[1] === scriptFile) links.push({ start: m.index, end: m.index + m[0].length, line: Number(m[2]) });
|
||||
return links;
|
||||
}
|
||||
|
||||
// The margin after Run all, one state per cell ("ran", "failed", "idle"), from the cells the run reported (0-based
|
||||
// indexes, in order) and how it ended. Finished: every cell ran. Raised at a line once the code started: the cells
|
||||
// before that line's cell ran, it failed. Raised before the code started (a syntax error, dependencies that didn't
|
||||
// install): only a syntax error's cell is marked, failed. Stopped, or raised at no line of the file: the cells before the
|
||||
// last one reported ran, that one failed; none without reports.
|
||||
function railAfterFile(cells, reportedCells, outcome) {
|
||||
const states = cells.map(() => "idle");
|
||||
if (outcome.status === "finished") return states.fill("ran");
|
||||
if (outcome.status === "raised") {
|
||||
const at = outcome.error_line > 0 ? cellAt(cells, outcome.error_line) : null;
|
||||
if (!outcome.executed) {
|
||||
if (at) states[at.index - 1] = "failed";
|
||||
return states;
|
||||
}
|
||||
if (at) {
|
||||
for (let i = 0; i < at.index - 1; ++i) states[i] = "ran";
|
||||
states[at.index - 1] = "failed";
|
||||
return states;
|
||||
}
|
||||
} else if (outcome.status !== "cancelled" && outcome.status !== "timed_out") return states;
|
||||
if (reportedCells.length) {
|
||||
const last = Math.min(reportedCells[reportedCells.length - 1], states.length - 1);
|
||||
for (let i = 0; i < last; ++i) states[i] = "ran";
|
||||
states[last] = "failed";
|
||||
}
|
||||
return states;
|
||||
}
|
||||
|
||||
// Whether a cell's text has changed since it ran.
|
||||
function edited(cellText, ranText) { return cellText !== ranText; }
|
||||
|
||||
// A script's text with the line breaks the editor holds (LF), whatever the file has, so a CRLF file isn't edited as
|
||||
// it opens.
|
||||
function editorText(text) { return text.replace(/\r\n?/g, "\n"); }
|
||||
|
||||
// The console blocks Clear keeps, in order: the ones the run going still writes to, its own block and, in Run all, the
|
||||
// block of the cell it runs now. None when nothing runs.
|
||||
function keptByClear(run) { return run ? [run.block, run.cellBlock].filter(Boolean) : []; }
|
||||
|
||||
// How the editor shows cells, from the Cells menu: a style, and whether the cell at the cursor is highlighted.
|
||||
const CELL_STYLES = ["margin", "dividers", "bands", "shaded"];
|
||||
|
||||
// The cell view to draw from what the host saved: a missing or unknown style is Dividers, and the highlight is on unless
|
||||
// it was turned off.
|
||||
function cellView(saved) {
|
||||
const style = saved && CELL_STYLES.includes(saved.style) ? saved.style : "dividers";
|
||||
return { style, highlight: !saved || saved.highlight !== false };
|
||||
}
|
||||
|
||||
// The rows `view` marks behind the text of `cells` (0-based, inclusive, one class each), in the order they are drawn:
|
||||
// Shaded cells' shade on every second cell, the highlight on cell `current` (its index, 0 for none), then the style's
|
||||
// lines on top, a divider above each cell that doesn't start the file or a band on each cell's "# %%" line.
|
||||
function cellMarks(cells, lines, view, current) {
|
||||
const marks = [];
|
||||
const add = (from, to, cls) => marks.push({ from, to, cls });
|
||||
if (view.style === "shaded")
|
||||
for (const cell of cells) if (cell.index % 2 === 0) add(cell.start - 1, cell.end - 1, "cell-shade");
|
||||
if (view.highlight)
|
||||
for (const cell of cells) if (cell.index === current) add(cell.start - 1, cell.end - 1, "cell-current");
|
||||
for (const cell of cells) {
|
||||
const row = cell.start - 1;
|
||||
if (view.style === "dividers" && row > 0) add(row, row, "cell-divider");
|
||||
else if (view.style === "bands" && CELL_MARKER.test((lines[row] || "").replace(/\r$/, ""))) add(row, row, "cell-band");
|
||||
}
|
||||
return marks;
|
||||
}
|
||||
|
||||
// ---- a result that is JSON: the host sends it compact, as json.dumps writes it -------------------------------------
|
||||
|
||||
const JSON_TOKEN = /\s+|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\],:]/y;
|
||||
|
||||
// `text`'s tokens, {type: "key" | "string" | "number" | "literal" | "punct" | "space", text}, each as written, so a
|
||||
// number keeps every digit Python wrote; null when something in it is no JSON token.
|
||||
function jsonTokens(text) {
|
||||
const tokens = [];
|
||||
const re = new RegExp(JSON_TOKEN.source, "y");
|
||||
for (let at = 0; at < text.length;) {
|
||||
re.lastIndex = at;
|
||||
const match = re.exec(text);
|
||||
if (!match) return null;
|
||||
const t = match[0];
|
||||
const first = t[0];
|
||||
const type = /\s/.test(first) ? "space" : first === '"' ? "string" : first === "-" || (first >= "0" && first <= "9") ? "number"
|
||||
: first >= "a" && first <= "z" ? "literal" : "punct";
|
||||
tokens.push({ type, text: t });
|
||||
at += t.length;
|
||||
}
|
||||
// A string before a colon is a key.
|
||||
for (let i = 0; i < tokens.length; ++i) {
|
||||
if (tokens[i].type !== "string") continue;
|
||||
let next = i + 1;
|
||||
while (tokens[next] && tokens[next].type === "space") ++next;
|
||||
if (tokens[next] && tokens[next].text === ":") tokens[i].type = "key";
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
// How much longer than the host's one-line JSON its layout may be: deep nesting is mostly indentation, which would hold
|
||||
// the console far past what the runner's output allowance counted.
|
||||
const JSON_MAX_GROWTH = 4;
|
||||
|
||||
// `text` laid out to read: an array or object whose one-line form fits in `width` with its indent stays on one line,
|
||||
// any other takes a line per member, indented two spaces a level. Numbers and strings stay as written. Text that isn't
|
||||
// one JSON value, or whose layout would be more than JSON_MAX_GROWTH times as long, comes back as it is.
|
||||
function formatJson(text, width = 72) {
|
||||
const tokens = jsonTokens(text);
|
||||
if (!tokens) return text;
|
||||
const items = tokens.filter((t) => t.type !== "space");
|
||||
let at = 0;
|
||||
// A value: a scalar's text, or {open, close, members: [{key, value}]}, with key null in an array.
|
||||
const value = () => {
|
||||
const t = items[at++];
|
||||
if (!t || t.type === "key" || (t.type === "punct" && t.text !== "{" && t.text !== "[")) throw new SyntaxError();
|
||||
if (t.type !== "punct") return t.text;
|
||||
const node = { open: t.text, close: t.text === "{" ? "}" : "]", members: [] };
|
||||
if (items[at] && items[at].text === node.close) return ++at, node;
|
||||
for (;;) {
|
||||
let key = null;
|
||||
if (node.open === "{") {
|
||||
key = items[at++];
|
||||
if (!key || key.type !== "key" || !items[at] || items[at++].text !== ":") throw new SyntaxError();
|
||||
key = key.text;
|
||||
}
|
||||
node.members.push({ key, value: value() });
|
||||
const next = items[at++];
|
||||
if (next && next.text === node.close) return node;
|
||||
if (!next || next.text !== ",") throw new SyntaxError();
|
||||
}
|
||||
};
|
||||
let root;
|
||||
try {
|
||||
root = value();
|
||||
} catch (e) {
|
||||
return text;
|
||||
}
|
||||
if (at !== items.length) return text;
|
||||
const lead = (member) => (member.key === null ? "" : member.key + ": ");
|
||||
// The length of a value's one-line form, kept on the node.
|
||||
const size = (node) => {
|
||||
if (typeof node === "string") return node.length;
|
||||
if (node.size === undefined)
|
||||
node.size = 2 + node.members.reduce((n, m, i) => n + (i ? 2 : 0) + lead(m).length + size(m.value), 0);
|
||||
return node.size;
|
||||
};
|
||||
const flat = (node) => (typeof node === "string" ? node : node.open + node.members.map((m) => lead(m) + flat(m.value)).join(", ") + node.close);
|
||||
const lay = (node, indent, before) => {
|
||||
if (typeof node === "string" || indent.length + before.length + size(node) <= width) return flat(node);
|
||||
const inner = indent + " ";
|
||||
return node.open + "\n" + node.members.map((m) => inner + lead(m) + lay(m.value, inner, lead(m))).join(",\n") + "\n" + indent + node.close;
|
||||
};
|
||||
const laid = lay(root, "", "");
|
||||
return laid.length > JSON_MAX_GROWTH * text.length ? text : laid;
|
||||
}
|
||||
|
||||
// ---- Run all's folded cells and Add a cell --------------------------------------------------------------------------
|
||||
|
||||
// The last line of `text` that has more than spaces, without its line break: what a folded cell shows.
|
||||
function lastLine(text) {
|
||||
const lines = text.split("\n");
|
||||
for (let i = lines.length - 1; i >= 0; --i) {
|
||||
const line = lines[i].replace(/\r$/, "");
|
||||
if (line.trim()) return line;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// The edit Add a cell makes to the editor's `lines`: a "# %% " line at the end, a blank line before it unless the script
|
||||
// is empty, the file still ending with a line break, and the caret after the marker, where the cell's title goes.
|
||||
function addCellEdit(lines) {
|
||||
const last = lines.length - 1;
|
||||
const line = lines[last];
|
||||
const before = last > 0 ? lines[last - 1] : "";
|
||||
let text;
|
||||
if (line === "") text = last === 0 || !before.trim() ? "# %% \n" : "\n# %% \n";
|
||||
else text = line.trim() ? "\n\n# %% \n" : "\n# %% \n";
|
||||
const breaks = text.indexOf("#");
|
||||
return { at: { row: last, column: line.length }, text, caret: { row: last + breaks, column: 5 } };
|
||||
}
|
||||
|
||||
// ---- the divider between the editor and the console ----------------------------------------------------------------
|
||||
|
||||
// The editor's share of the panel's width, which the panel keeps as a share so a pane resized keeps its proportions;
|
||||
// the smallest widths the divider leaves each side; and how far past one a drag goes to hide that side.
|
||||
const SPLIT_DEFAULT = 0.6;
|
||||
const MIN_EDITOR = 220;
|
||||
const MIN_CONSOLE = 200;
|
||||
const HIDE_PAST = 48;
|
||||
const HIDDEN_SIDES = ["editor", "console"];
|
||||
|
||||
// The layout the panel kept, {split, hidden}: a split that is not a share strictly between 0 and 1 is the default, and
|
||||
// a hidden side that is neither side is none. The host keeps the split as text.
|
||||
function paneLayout(saved) {
|
||||
const split = saved && saved.split !== null && saved.split !== "" ? Number(saved.split) : NaN;
|
||||
return {
|
||||
split: split > 0 && split < 1 ? split : SPLIT_DEFAULT,
|
||||
hidden: saved && HIDDEN_SIDES.includes(saved.hidden) ? saved.hidden : "",
|
||||
};
|
||||
}
|
||||
|
||||
// Where the divider can be in a panel `width` px wide, as shares: from the editor's smallest width to the console's.
|
||||
// A panel too narrow for both stops the divider where the two smallest widths' shares meet.
|
||||
function splitBounds(width) {
|
||||
const low = MIN_EDITOR / width, high = (width - MIN_CONSOLE) / width;
|
||||
if (low <= high) return { low, high };
|
||||
const meet = MIN_EDITOR / (MIN_EDITOR + MIN_CONSOLE);
|
||||
return { low: meet, high: meet };
|
||||
}
|
||||
|
||||
// `split` within the bounds, to four places: the value the host keeps.
|
||||
function clampSplit(split, width) {
|
||||
const { low, high } = splitBounds(width);
|
||||
return Math.round(Math.min(Math.max(split, low), high) * 10000) / 10000;
|
||||
}
|
||||
|
||||
// The divider dragged to `x` px from the panel's left: where it goes, and the side to hide when the drag ends there,
|
||||
// which is the one it went more than HIDE_PAST px past the bound of.
|
||||
function dragSplit(x, width) {
|
||||
const { low, high } = splitBounds(width);
|
||||
const hide = x < low * width - HIDE_PAST ? "editor" : x > high * width + HIDE_PAST ? "console" : "";
|
||||
return { split: clampSplit(x / width, width), hide };
|
||||
}
|
||||
|
||||
// The divider's keys, as a window splitter's: the arrows move it a twentieth of the width, Home and End to a bound.
|
||||
// Null for any other key.
|
||||
function splitByKey(split, key, width) {
|
||||
const to = { ArrowLeft: split - 0.05, ArrowRight: split + 0.05, Home: 0, End: 1 }[key];
|
||||
return to === undefined ? null : clampSplit(to, width);
|
||||
}
|
||||
|
||||
// The side hidden as the panel draws it, from the side the layout hides. The console's side hides only while it shows
|
||||
// the console (`consoleShown`): with no script open it holds the start page, which stays in sight.
|
||||
function hiddenSide(hidden, consoleShown) { return hidden === "console" && !consoleShown ? "" : hidden; }
|
||||
|
||||
// What the hidden console's strip shows after `event` (start, output, finished, failed), from what it shows now
|
||||
// (nothing, running, fresh, failed): a run going, then that there is output not seen, red from a failed run until the
|
||||
// next run starts. Output while a run goes or after one failed changes nothing.
|
||||
function consoleNews(news, event) {
|
||||
if (event === "start") return "running";
|
||||
if (event === "finished") return "fresh";
|
||||
if (event === "failed") return "failed";
|
||||
return news || "fresh";
|
||||
}
|
||||
|
||||
return { splitCells, cellAt, pythonNextIndent, suggestContext, tracebackLinks, railAfterFile, edited, stateAt, editorText,
|
||||
openQuote, keptByClear, cellView, cellMarks, jsonTokens, formatJson, lastLine, addCellEdit, paneLayout, clampSplit,
|
||||
dragSplit, splitByKey, hiddenSide, consoleNews };
|
||||
});
|
||||
415
resources/web/dialog/RunScript/style.css
Normal file
415
resources/web/dialog/RunScript/style.css
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
/* The Run Script panel. Colours come from the host theme contract (--orca-*) and theme.css's status roles, so the
|
||||
* page follows the app in light and dark; the editor's own colours are code_editor.css's. The distinctive element is
|
||||
* the margin: a bar per cell beside the line numbers that shows what ran in this session. */
|
||||
|
||||
:root {
|
||||
--rs-bg: var(--orca-bg, #ffffff);
|
||||
--rs-fg: var(--orca-fg, #262e30);
|
||||
--rs-muted: var(--orca-muted, #6b7478);
|
||||
--rs-rule: var(--border, #dcdfe1);
|
||||
--rs-accent: var(--orca-accent, #009688);
|
||||
--rs-accent-fg: var(--orca-accent-fg, #ffffff);
|
||||
--rs-accent-text: #00796b;
|
||||
--rs-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
--rs-ring: rgba(0, 150, 136, 0.25);
|
||||
--rs-ring-soft: rgba(0, 150, 136, 0.08);
|
||||
--rs-fail: var(--plugin-status-danger, #b42318);
|
||||
--rs-chrome: var(--footer-bg, #f3f4f5);
|
||||
--rs-console: #fbfcfc;
|
||||
--rs-btn-bg: var(--btn-bg, #ffffff);
|
||||
--rs-btn-border: var(--btn-border, #cccccc);
|
||||
--rs-btn-hover: var(--btn-hover, #f0f0f0);
|
||||
--rs-pop-bg: var(--ctx-bg, #ffffff);
|
||||
--rs-pop-shadow: 0 6px 20px rgba(20, 30, 35, 0.16);
|
||||
--rs-mono: var(--code-font);
|
||||
/* The Cells menu's styles, drawn behind the editor's text. */
|
||||
--rs-cell-divider: #c3c9cc;
|
||||
--rs-cell-current: rgba(0, 150, 136, 0.07);
|
||||
--rs-cell-band: #eef1f2;
|
||||
--rs-cell-shade: rgba(38, 46, 48, 0.04);
|
||||
}
|
||||
:root[data-orca-theme="dark"] {
|
||||
--rs-accent-text: #4db6ac;
|
||||
--rs-accent-tint: rgba(0, 150, 136, 0.22);
|
||||
--rs-ring: rgba(0, 150, 136, 0.45);
|
||||
--rs-ring-soft: rgba(0, 150, 136, 0.15);
|
||||
--rs-console: #262629;
|
||||
--rs-pop-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
|
||||
--rs-cell-divider: #55555d;
|
||||
--rs-cell-current: rgba(0, 150, 136, 0.14);
|
||||
--rs-cell-band: #36363b;
|
||||
--rs-cell-shade: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
background: var(--rs-bg);
|
||||
color: var(--rs-fg);
|
||||
font: 13px/1.45 var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
}
|
||||
[hidden] { display: none !important; }
|
||||
:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 1px; }
|
||||
|
||||
.panel { height: 100%; display: flex; flex-direction: column; min-height: 0; }
|
||||
|
||||
/* ---- toolbar ---- */
|
||||
.toolbar { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--rs-rule); flex-wrap: wrap; flex: none; }
|
||||
.btn {
|
||||
font: 12.5px var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
color: var(--rs-fg);
|
||||
background: var(--rs-btn-bg);
|
||||
border: 1px solid var(--rs-btn-border);
|
||||
border-radius: 4px;
|
||||
padding: 3px 11px;
|
||||
white-space: nowrap;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover:not(:disabled) { background: var(--rs-btn-hover); }
|
||||
.btn.primary { color: var(--rs-accent-fg); background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--rs-accent); }
|
||||
.btn.stop:not(:disabled) { color: var(--rs-fail); border-color: var(--rs-fail); }
|
||||
.btn:disabled { opacity: 0.42; cursor: default; }
|
||||
.btn .key { font-size: 11px; opacity: 0.7; }
|
||||
.caret-d { width: 0; height: 0; border-top: 4.5px solid currentColor; border-left: 4px solid transparent; border-right: 4px solid transparent; opacity: 0.7; }
|
||||
.tri { width: 0; height: 0; border-left: 7px solid currentColor; border-top: 4.5px solid transparent; border-bottom: 4.5px solid transparent; }
|
||||
.sq { width: 8px; height: 8px; background: currentColor; border-radius: 1px; }
|
||||
.sep { width: 1px; height: 20px; background: var(--rs-rule); margin: 0 3px; }
|
||||
.chip { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 4px; background: var(--rs-accent-tint); font-size: 12px; white-space: nowrap; max-width: 280px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.chip .edited { color: var(--rs-muted); }
|
||||
|
||||
.menu-wrap { position: relative; display: inline-flex; }
|
||||
.menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 3px);
|
||||
left: 0;
|
||||
z-index: 20;
|
||||
min-width: 240px;
|
||||
max-width: 420px;
|
||||
padding: 4px 0;
|
||||
background: var(--rs-pop-bg);
|
||||
border: 1px solid var(--rs-rule);
|
||||
border-radius: 6px;
|
||||
box-shadow: var(--rs-pop-shadow);
|
||||
}
|
||||
.menu-item {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 10px;
|
||||
align-items: baseline;
|
||||
padding: 4px 12px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--rs-fg);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.menu-item:hover, .menu-item:focus-visible { background: var(--rs-accent-tint); outline: none; }
|
||||
.menu-item:disabled { opacity: 0.42; cursor: default; }
|
||||
.menu-item .d { color: var(--rs-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.menu-label { padding: 6px 12px 2px; font-size: 11.5px; color: var(--rs-muted); }
|
||||
.menu-rule { height: 1px; margin: 4px 0; background: var(--rs-rule); }
|
||||
.menu.right { left: auto; right: 0; }
|
||||
/* The Cells menu: a dot on the style in use, a check on the highlight. */
|
||||
.menu-item[role="menuitemradio"]::before, .menu-item[role="menuitemcheckbox"]::before {
|
||||
content: "";
|
||||
flex: none;
|
||||
width: 12px;
|
||||
text-align: center;
|
||||
color: var(--rs-accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
.menu-item[role="menuitemradio"][aria-checked="true"]::before { content: "●"; font-size: 9px; }
|
||||
.menu-item[role="menuitemcheckbox"][aria-checked="true"]::before { content: "✓"; }
|
||||
.cells-glyph {
|
||||
width: 12px;
|
||||
height: 11px;
|
||||
flex: none;
|
||||
border-top: 2px solid currentColor;
|
||||
border-bottom: 2px solid currentColor;
|
||||
background: linear-gradient(currentColor, currentColor) center / 100% 1.5px no-repeat;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
/* The session line: its items, each on its own, apart. */
|
||||
.session { margin-left: auto; display: inline-flex; align-items: center; gap: 7px; font-size: 12px; color: var(--rs-muted); white-space: nowrap; }
|
||||
.session .dot { width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--rs-muted); flex: none; }
|
||||
.session.live .dot { border: 0; background: var(--rs-accent); box-shadow: 0 0 0 3px var(--rs-accent-tint); }
|
||||
.session.busy { color: var(--rs-accent); }
|
||||
.session.busy .dot { border: 0; background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; }
|
||||
.session .item + .item { padding-left: 7px; border-left: 1px solid var(--rs-rule); }
|
||||
.session .item.lead { color: var(--rs-fg); }
|
||||
|
||||
/* ---- body: editor and console side by side, the editor's share of the width set by the divider ---- */
|
||||
.body { flex: 1; display: flex; min-height: 0; }
|
||||
.col { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
|
||||
.editor-col { flex: 0 0 var(--split, 60%); }
|
||||
.side { flex: 1 1 0; }
|
||||
.body.dragging { cursor: col-resize; user-select: none; }
|
||||
/* Dragged far enough past a side's smallest width, the side fades: the drag ending there hides it. */
|
||||
.body[data-pending="editor"] .editor-col, .body[data-pending="console"] .side { opacity: 0.35; }
|
||||
|
||||
/* The divider: a line, a strip either side of it to grab, the accent while it can be dragged. */
|
||||
.split { position: relative; z-index: 8; flex: none; width: 1px; background: var(--rs-rule); cursor: col-resize; touch-action: none; }
|
||||
.split:focus-visible { outline: none; }
|
||||
.split::before { content: ""; position: absolute; top: 0; bottom: 0; left: -4px; right: -4px; }
|
||||
.split::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: -1px;
|
||||
width: 3px;
|
||||
background: var(--rs-accent);
|
||||
opacity: 0;
|
||||
transition: opacity 0.1s 0.15s;
|
||||
pointer-events: none;
|
||||
}
|
||||
.split:hover::after, .split:focus-visible::after, .body.dragging .split::after { opacity: 1; transition-delay: 0s; }
|
||||
/* Its grip: each arrow pushes the divider over the side it points at, which hides. */
|
||||
.grip {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 3px 1px;
|
||||
background: var(--rs-bg);
|
||||
border: 1px solid var(--rs-rule);
|
||||
border-radius: 9px;
|
||||
cursor: default;
|
||||
}
|
||||
.grip button { width: 16px; height: 18px; padding: 0; border: 0; border-radius: 6px; display: grid; place-items: center; background: none; color: var(--rs-muted); cursor: pointer; }
|
||||
.grip button:hover, .grip button:focus-visible { background: var(--rs-accent); color: var(--rs-accent-fg); outline: none; }
|
||||
.grip path, .strip-chev path { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||
|
||||
/* A hidden side leaves a strip at its edge, which brings it back. */
|
||||
.strip {
|
||||
flex: none;
|
||||
width: 28px;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 0 10px;
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
background: var(--rs-chrome);
|
||||
color: var(--rs-muted);
|
||||
font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
cursor: pointer;
|
||||
}
|
||||
.strip-editor { border-right: 1px solid var(--rs-rule); }
|
||||
.strip-console { border-left: 1px solid var(--rs-rule); }
|
||||
.strip:hover { color: var(--rs-fg); }
|
||||
.strip:focus-visible { outline-offset: -2px; }
|
||||
.strip-chev { flex: none; width: 20px; height: 20px; border-radius: 4px; display: grid; place-items: center; }
|
||||
.strip:hover .strip-chev, .strip:focus-visible .strip-chev { background: var(--rs-accent); color: var(--rs-accent-fg); }
|
||||
/* Read from the panel's edge inwards: up the left strip, down the right one. */
|
||||
.strip-label { writing-mode: vertical-rl; white-space: nowrap; min-height: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.strip-editor .strip-label { transform: rotate(180deg); }
|
||||
.body[data-hidden="editor"] .strip-editor, .body[data-hidden="console"] .strip-console { display: flex; }
|
||||
.body[data-hidden="editor"] .editor-col, .body[data-hidden="editor"] .split,
|
||||
.body[data-hidden="console"] .side, .body[data-hidden="console"] .split { display: none; }
|
||||
.body[data-hidden="console"] .editor-col { flex: 1 1 0; }
|
||||
/* The hidden editor's strip: a bar per cell in the margin's colours, so what ran and what failed stays in sight. */
|
||||
.strip-cells { flex: none; display: flex; flex-direction: column; gap: 3px; max-height: 50%; overflow: hidden; }
|
||||
.strip-cells i { flex: none; width: 4px; height: 12px; border-radius: 2px; background: var(--rs-rule); }
|
||||
.strip-cells i.ran { background: var(--rs-accent); }
|
||||
.strip-cells i.edited { background: repeating-linear-gradient(180deg, var(--rs-accent) 0 4px, transparent 4px 7px); }
|
||||
.strip-cells i.failed { background: var(--rs-fail); }
|
||||
.strip-cells i.running { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; }
|
||||
/* The hidden console's strip: a dot while a run goes, for output not seen, red after a run failed. */
|
||||
.news { flex: none; width: 8px; height: 8px; border-radius: 50%; }
|
||||
.news.running { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; }
|
||||
.news.fresh { background: var(--rs-accent); box-shadow: 0 0 0 3px var(--rs-accent-tint); }
|
||||
.news.failed { background: var(--rs-fail); box-shadow: 0 0 0 3px rgba(180, 35, 24, 0.18); }
|
||||
.editor { flex: 1; min-height: 0; font-size: 12.5px; }
|
||||
.editor.is-readonly .ace_content { opacity: 0.6; }
|
||||
.placeholder-text { margin: 0; color: var(--rs-muted); padding: 14px 18px; }
|
||||
|
||||
/* The margin: one bar per cell, drawn on the gutter rows of its lines. */
|
||||
.editor .ace_gutter-cell { padding-left: 12px; }
|
||||
.editor .ace_gutter-cell[class*="rail-"]::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 4px;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 4px;
|
||||
background: var(--rs-rule);
|
||||
}
|
||||
.editor .ace_gutter-cell.rail-first::before { top: 3px; border-top-left-radius: 2px; border-top-right-radius: 2px; }
|
||||
.editor .ace_gutter-cell.rail-last::before { bottom: 3px; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; }
|
||||
.editor .ace_gutter-cell.rail-ran::before { background: var(--rs-accent); }
|
||||
.editor .ace_gutter-cell.rail-edited::before { background: repeating-linear-gradient(180deg, var(--rs-accent) 0 5px, transparent 5px 9px); }
|
||||
.editor .ace_gutter-cell.rail-failed::before { background: var(--rs-fail); }
|
||||
.editor .ace_gutter-cell.rail-running::before { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; }
|
||||
.editor .ace_gutter-cell.rail-current::before { left: 3px; width: 6px; }
|
||||
.editor .ace_cell-marker { color: var(--code-comment); font-weight: 600; }
|
||||
|
||||
/* The Cells menu's styles: full-line markers behind the text (RunScriptModel.cellMarks()). */
|
||||
.editor .ace_marker-layer .cell-divider { position: absolute; border-top: 1px solid var(--rs-cell-divider); }
|
||||
.editor .ace_marker-layer .cell-band { position: absolute; background: var(--rs-cell-band); border-top: 1px solid var(--rs-cell-divider); }
|
||||
.editor .ace_marker-layer .cell-shade { position: absolute; background: var(--rs-cell-shade); }
|
||||
.editor .ace_marker-layer .cell-current { position: absolute; background: var(--rs-cell-current); }
|
||||
.editor.cells-bands .ace_cell-marker { color: var(--rs-fg); }
|
||||
|
||||
/* Add a cell: the + in the margin a row below the last line, and on hover where the cell goes. Drawn in the accent as
|
||||
* text, which the dark theme lightens to read on its background. */
|
||||
.editor .add-cell {
|
||||
position: absolute;
|
||||
z-index: 6;
|
||||
left: 3px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: none;
|
||||
color: var(--rs-accent-text);
|
||||
font: 700 16px/1 var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
cursor: pointer;
|
||||
}
|
||||
.editor .add-cell:hover, .editor .add-cell:focus-visible { background: var(--rs-accent); color: var(--rs-accent-fg); }
|
||||
.editor .add-hint {
|
||||
position: absolute;
|
||||
z-index: 6;
|
||||
right: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
visibility: hidden;
|
||||
font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
color: var(--rs-accent-text);
|
||||
}
|
||||
.editor .add-hint::after { content: ""; flex: 1; border-top: 1px dashed var(--rs-accent-text); opacity: 0.6; }
|
||||
.editor .add-cell:hover + .add-hint, .editor .add-cell:focus-visible + .add-hint { visibility: visible; }
|
||||
@keyframes pulse { 0%, 100% { box-shadow: 0 0 0 1px var(--rs-ring); } 50% { box-shadow: 0 0 0 4px var(--rs-ring-soft); } }
|
||||
|
||||
/* ---- console ---- */
|
||||
.console { flex: 1; min-height: 0; display: flex; flex-direction: column; font: 12px/1.55 var(--rs-mono); background: var(--rs-console); }
|
||||
.log { flex: 1; min-height: 0; overflow: auto; padding: 4px 0; }
|
||||
.block + .block { margin-top: 4px; border-top: 1px dashed var(--rs-rule); }
|
||||
.run-head { display: flex; gap: 8px; align-items: baseline; font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif); padding: 5px 12px 2px; }
|
||||
.run-head b { font-weight: 600; }
|
||||
.run-head .t { color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.run-head .code { font-family: var(--rs-mono); color: var(--rs-muted); white-space: pre; overflow: hidden; text-overflow: ellipsis; }
|
||||
.run-head .d { margin-left: auto; color: var(--rs-muted); white-space: nowrap; }
|
||||
.run-head.failed b { color: var(--rs-fail); }
|
||||
.run-head.busy b, .run-head.busy .d { color: var(--rs-accent); }
|
||||
.out { padding: 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.out.muted { color: var(--rs-muted); }
|
||||
.out.err { color: var(--rs-fail); }
|
||||
.out a.link { color: var(--rs-fail); text-decoration: underline; text-underline-offset: 2px; cursor: pointer; }
|
||||
/* Run all's block: a row per cell, folded to its heading, which shows what the cell showed last. The bar at a row's left
|
||||
* is the cell's bar in the margin, in the same state. */
|
||||
.run-head .expand-all {
|
||||
font: inherit;
|
||||
font-size: 11.5px;
|
||||
color: var(--rs-muted);
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
text-decoration: underline dotted;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.run-head .expand-all:hover { color: var(--rs-fg); text-decoration-style: solid; }
|
||||
.cells { padding-bottom: 4px; }
|
||||
.cell-row { position: relative; }
|
||||
.cell-row::before { content: ""; position: absolute; left: 14px; top: 4px; bottom: 4px; width: 3px; border-radius: 2px; background: var(--rs-accent); }
|
||||
.cell-row.failed::before { background: var(--rs-fail); }
|
||||
.cell-row.running::before { animation: pulse 1.4s ease-in-out infinite; }
|
||||
.cell-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 3px 12px 3px 24px;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--rs-fg);
|
||||
font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cell-head:hover { background: var(--rs-cell-current); }
|
||||
.cell-head .chev {
|
||||
flex: none;
|
||||
align-self: center;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 5px solid currentColor;
|
||||
border-top: 3.5px solid transparent;
|
||||
border-bottom: 3.5px solid transparent;
|
||||
opacity: 0.55;
|
||||
transition: transform 0.12s;
|
||||
}
|
||||
.cell-row.open .chev { transform: rotate(90deg); }
|
||||
.cell-head b { flex: none; font-weight: 600; }
|
||||
.cell-head .t { flex: 0 1 auto; max-width: 45%; color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cell-head .peek { flex: 1 1 0; min-width: 0; font: 11.5px var(--rs-mono); color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cell-head .peek.err { color: var(--rs-fail); }
|
||||
.cell-row.open .peek { visibility: hidden; }
|
||||
.cell-head .d { flex: none; margin-left: auto; color: var(--rs-muted); white-space: nowrap; }
|
||||
.cell-head.busy b, .cell-head.busy .d { color: var(--rs-accent); }
|
||||
.cell-head.failed b { color: var(--rs-fail); }
|
||||
.cell-body { padding: 1px 0 5px; }
|
||||
.cell-body .out { padding-left: 37px; }
|
||||
/* A result JSON holds, in the editor's own JSON colours. */
|
||||
.out.json .j-key { color: var(--code-key); }
|
||||
.out.json .j-string { color: var(--code-string); }
|
||||
.out.json .j-number { color: var(--code-number); }
|
||||
.out.json .j-literal { color: var(--code-keyword); }
|
||||
.out.json .j-punct { color: var(--code-punct); }
|
||||
.divider { margin: 6px 12px; font: 11.5px var(--orca-font, "Segoe UI", system-ui, sans-serif); color: var(--rs-muted); display: flex; align-items: center; gap: 8px; }
|
||||
.divider::before, .divider::after { content: ""; flex: 1; height: 1px; background: var(--rs-rule); }
|
||||
/* The prompt line, with Clear at its end; Clear stays usable while the line is off. */
|
||||
.prompt { display: flex; align-items: center; border-top: 1px solid var(--rs-rule); background: var(--rs-bg); flex: none; }
|
||||
.prompt-line { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 5px 12px; }
|
||||
.prompt .p { color: var(--rs-accent); font-weight: 700; }
|
||||
.prompt input { flex: 1; min-width: 0; border: 0; outline: none; background: transparent; color: var(--rs-fg); font: 12px var(--rs-mono); }
|
||||
.prompt input::placeholder { color: var(--rs-muted); font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif); }
|
||||
.prompt-line:focus-within { box-shadow: inset 0 0 0 1px var(--rs-accent); }
|
||||
.prompt-line.off { opacity: 0.5; }
|
||||
.btn.small { font-size: 12px; padding: 1px 9px; margin-right: 8px; }
|
||||
|
||||
/* ---- the side's other views: no script, Python off ---- */
|
||||
.side-msg { flex: 1; padding: 18px 20px; overflow: auto; }
|
||||
.side-msg h3 { font-size: 14px; font-weight: 600; margin: 0 0 6px; }
|
||||
.side-msg p { margin: 0 0 12px; color: var(--rs-muted); max-width: 52ch; }
|
||||
.side-msg code { font: 12px var(--rs-mono); background: var(--rs-accent-tint); border-radius: 3px; padding: 0 4px; }
|
||||
.side-msg .row { display: flex; gap: 8px; margin-bottom: 18px; }
|
||||
.recent { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--rs-rule); }
|
||||
.recent li { border-bottom: 1px solid var(--rs-rule); }
|
||||
.recent button { display: flex; width: 100%; gap: 10px; align-items: baseline; padding: 6px 2px; border: 0; background: none; color: var(--rs-fg); font: inherit; text-align: left; cursor: pointer; }
|
||||
.recent button:hover { background: var(--rs-accent-tint); }
|
||||
.recent .f { font-weight: 600; white-space: nowrap; }
|
||||
.recent .d { color: var(--rs-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.label-sm { font-size: 12px; color: var(--rs-muted); margin: 0 0 6px; }
|
||||
|
||||
/* ---- status line, while a run goes ---- */
|
||||
.statusline { display: flex; align-items: center; gap: 10px; padding: 4px 10px; border-top: 1px solid var(--rs-rule); background: var(--rs-chrome); font-size: 12px; color: var(--rs-muted); flex: none; }
|
||||
#status-main { font-weight: 600; color: var(--rs-accent); }
|
||||
.statusline.is-error #status-main { color: var(--rs-fail); }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.session.busy .dot, .editor .ace_gutter-cell.rail-running::before, .cell-row.running::before, .strip-cells i.running, .news.running {
|
||||
animation: none;
|
||||
box-shadow: 0 0 0 2px var(--rs-ring);
|
||||
}
|
||||
.cell-head .chev, .split::after { transition: none; }
|
||||
}
|
||||
|
|
@ -99,7 +99,7 @@ var searchNeedle = "";
|
|||
var searchTokens = [];
|
||||
var searchTokenRes = [];
|
||||
|
||||
// Palette phase: 'commands' (one unified search over actions/commands/settings, recents on empty
|
||||
// The Speed Dial's phase: 'commands' (one unified search over actions/commands/settings, recents on empty
|
||||
// query), 'percent' ("Go to layer" second phase: enter a 0-100 percentage), 'tab' ("Go to tab..."
|
||||
// second phase: pick a notebook tab).
|
||||
var phase = "commands";
|
||||
|
|
@ -794,10 +794,12 @@ window.HandleStudio = function (payload) {
|
|||
RECENTS = next.recent;
|
||||
USER_MODE = next.userMode;
|
||||
TOOLTIP_EXPANDED = next.tooltipExpanded;
|
||||
// A fresh payload re-opens the main phase; C++ never rehydrates the transient phase/query state.
|
||||
// A fresh payload re-opens the main phase; C++ never rehydrates the transient phase/query state. It comes a
|
||||
// moment after the dial shows, so a query can be typed before it, by a person or a call: the field holds only
|
||||
// that, as "closed" empties it when an open ends, and it is kept and filters the new list.
|
||||
phase = "commands";
|
||||
tabOptions = [];
|
||||
query = "";
|
||||
query = qEl ? qEl.value : "";
|
||||
sel = { zone: "list", i: 0 };
|
||||
resetHover();
|
||||
// why: builtKey caches phase|query so renderCommandsList can skip a rebuild on arrow-nav.
|
||||
|
|
@ -805,12 +807,20 @@ window.HandleStudio = function (payload) {
|
|||
// empty-query key would skip the rebuild and leave stale list content.
|
||||
builtKey = "";
|
||||
if (qEl) {
|
||||
qEl.value = "";
|
||||
qEl.value = query;
|
||||
qEl.placeholder = T("sd_search", "Search actions");
|
||||
syncClearButton();
|
||||
}
|
||||
render({ resize: true, resetScroll: true });
|
||||
focusInput();
|
||||
} else if (payload.command === "closed") {
|
||||
// An open ended: the next one starts with an empty field.
|
||||
query = "";
|
||||
if (qEl) {
|
||||
qEl.value = "";
|
||||
syncClearButton();
|
||||
}
|
||||
render({ resize: true, resetScroll: true });
|
||||
} else if (payload.command === "tab_results") {
|
||||
tabOptions = payload.tabs || [];
|
||||
if (sel.zone === "list")
|
||||
|
|
@ -822,6 +832,11 @@ window.HandleStudio = function (payload) {
|
|||
if (fid && FAVS.indexOf(fid) !== -1) FAVS.splice(FAVS.indexOf(fid), 1);
|
||||
render({ resize: true, keepScroll: true });
|
||||
flashHint(T("sd_favs_full", "Favorites are full (%s max)", (payload.limit || K_FAV_LIMIT)));
|
||||
} else if (payload.command === "favourites") {
|
||||
// The bar as C++ now shows it, sent after each pin, unpin and reorder: it settles the click's optimistic
|
||||
// change, and an unpin can bring a pin past the tenth onto the bar, which the page alone cannot know.
|
||||
FAVS = payload.favourites || [];
|
||||
render({ resize: true, keepScroll: true });
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -1471,13 +1486,14 @@ function toggleFav(id) {
|
|||
}
|
||||
|
||||
// Fire a command/plugin action; C++ owns the run-confirm (native dialog) + suppression, then
|
||||
// closes the popup + toasts.
|
||||
// closes the popup + toasts. A plain pick passes no arguments: a command then does what a person's
|
||||
// pick does, asking in its dialog where it has one.
|
||||
function run(a) {
|
||||
if (!a) return;
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, param: "" });
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, args: {} });
|
||||
}
|
||||
|
||||
// Activate an entry in the main phase. Two-phase commands switch the palette to their input phase
|
||||
// Activate an entry in the main phase. Two-phase commands switch the Speed Dial to their input phase
|
||||
// instead of running; everything else (including a setting jump, which is a plain action now) runs.
|
||||
function activateEntry(a) {
|
||||
if (!a) return;
|
||||
|
|
@ -1507,13 +1523,13 @@ function runJumpToLayer(pct) {
|
|||
if (!isFinite(n) || n < 0 || n > 100) return;
|
||||
var a = findActionByInput("percent");
|
||||
if (!a) return;
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, param: String(n) });
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, args: { percent: n } });
|
||||
}
|
||||
|
||||
function jumpToTab(t) {
|
||||
var a = findActionByInput("tab");
|
||||
if (!a || !t) return;
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, param: t.id });
|
||||
SendMessage({ command: "run_action", id: a.id, title: a.title, args: { tab: t.id } });
|
||||
}
|
||||
|
||||
// Clear the shared query/cursor state when entering or leaving a phase. Callers set the
|
||||
|
|
@ -1553,6 +1569,11 @@ function exitPhase() {
|
|||
qEl.focus();
|
||||
}
|
||||
|
||||
function onQueryInput() {
|
||||
query = qEl.value; sel = { zone: "list", i: 0 }; syncClearButton();
|
||||
render({ resize: true, resetScroll: true });
|
||||
}
|
||||
|
||||
function focusInput() { setTimeout(function () { if (qEl) qEl.focus(); }, 0); }
|
||||
|
||||
// ---- init --------------------------------------------------------------------
|
||||
|
|
@ -1574,10 +1595,7 @@ function OnInit() {
|
|||
render({ resize: true, resetScroll: true });
|
||||
qEl.focus();
|
||||
};
|
||||
qEl.addEventListener("input", function () {
|
||||
query = qEl.value; sel = { zone: "list", i: 0 }; syncClearButton();
|
||||
render({ resize: true, resetScroll: true });
|
||||
});
|
||||
qEl.addEventListener("input", onQueryInput);
|
||||
// Caret moves without a value change (click / arrow keys) can enable or invalidate the ghost.
|
||||
qEl.addEventListener("keyup", updateGhost);
|
||||
qEl.addEventListener("click", updateGhost);
|
||||
|
|
|
|||
|
|
@ -495,6 +495,52 @@ assert.deepEqual(ctx.visibleFavourites(["b", "a", "b"], [{ id: "a" }, { id: "b"
|
|||
assert.deepEqual(ctx.visibleFavourites([], [{ id: "a" }]), [], "no pins renders an empty quick-bar");
|
||||
assert.deepEqual(ctx.visibleFavourites(["a"], []), [], "a stale config with no actions renders nothing");
|
||||
|
||||
// The bar C++ sends after a pin, an unpin or a reorder replaces the page's: an unpin can bring a pin past the
|
||||
// tenth onto the bar. Rendering needs the DOM, which this test has not, so it is stubbed.
|
||||
var renderBefore = ctx.render, favsBefore = ctx.FAVS;
|
||||
ctx.render = function () {};
|
||||
ctx.FAVS = ["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"];
|
||||
ctx.HandleStudio({ command: "favourites", favourites: ["p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11"] });
|
||||
assert.deepEqual(ctx.FAVS, ["p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9", "p10", "p11"],
|
||||
"the bar C++ sends replaces the page's, a pin past the tenth promoted onto it");
|
||||
ctx.HandleStudio(JSON.stringify({ command: "favourites", favourites: [] }));
|
||||
assert.deepEqual(ctx.FAVS, [], "an empty bar, sent as text, empties the page's");
|
||||
ctx.render = renderBefore;
|
||||
ctx.FAVS = favsBefore;
|
||||
|
||||
// The list C++ sends with each open runs a moment after the dial shows: a query typed by then, by a person or a call,
|
||||
// is kept and filters the new list, and the field is empty otherwise, as C++'s "closed" at the end of an open empties
|
||||
// it. Rendering and focusing need the DOM, so they are stubbed, and the field is a stand-in.
|
||||
var listBefore = { render: ctx.render, focusInput: ctx.focusInput, qEl: ctx.qEl, actions: ctx.ACTIONS };
|
||||
ctx.render = function () {};
|
||||
ctx.focusInput = function () {};
|
||||
ctx.qEl = { value: "", placeholder: "" };
|
||||
var listPayload = { command: "list_actions", actions: duplicateActions, favourites: [], recent: [] };
|
||||
ctx.qEl.value = "rep";
|
||||
ctx.onQueryInput();
|
||||
ctx.HandleStudio(listPayload);
|
||||
assert.equal(ctx.qEl.value, "rep", "a query typed before the open's list arrives stays in the field");
|
||||
assert.equal(ctx.query, "rep", "and is the query");
|
||||
assert.deepEqual(ctx.currentList(), ctx.commandList(duplicateActions, [], "rep"), "which filters the new list");
|
||||
ctx.HandleStudio({ command: "closed" });
|
||||
ctx.HandleStudio(listPayload);
|
||||
assert.equal(ctx.qEl.value, "", "the next open's list finds the field the last open left empty");
|
||||
assert.equal(ctx.query, "", "and its query");
|
||||
// A search, the dial closed, and a query typed in the next open before its list arrives: the field holds only what
|
||||
// was typed in that open, since closing empties it, and the list keeps it.
|
||||
ctx.qEl.value = "shell";
|
||||
ctx.onQueryInput();
|
||||
ctx.HandleStudio({ command: "closed" });
|
||||
ctx.qEl.value += "fillet";
|
||||
ctx.onQueryInput();
|
||||
ctx.HandleStudio(listPayload);
|
||||
assert.equal(ctx.qEl.value, "fillet", "a query typed after a reopen, before its list, is that open's alone");
|
||||
assert.equal(ctx.query, "fillet", "and is the query");
|
||||
ctx.render = listBefore.render;
|
||||
ctx.focusInput = listBefore.focusInput;
|
||||
ctx.qEl = listBefore.qEl;
|
||||
ctx.ACTIONS = listBefore.actions;
|
||||
|
||||
// actionIcon: the SVG base name for a tile's pictogram, or "" when the action has none (blank tile).
|
||||
assert.equal(ctx.actionIcon({ id: "x", title: "Slice", icon: "media_play" }), "media_play",
|
||||
"an action's icon base name is returned verbatim");
|
||||
|
|
@ -604,6 +650,28 @@ assert.equal(ctx.stateFromPayload({ tooltip_expanded: true }).tooltipExpanded, t
|
|||
assert.equal(ctx.resultCountText(100, 3, "lay"), "Matching actions: 3", "a search reports the shown match count only");
|
||||
assert.equal(ctx.resultCountText(100, 100, ""), "Actions: 100", "an empty query reports the total");
|
||||
|
||||
// run_action: a pick sends the command's arguments as an object, none for a plain pick, and the value
|
||||
// of the second phase for Go to layer and Go to tab.
|
||||
var sent = [];
|
||||
var actionsBefore = ctx.ACTIONS;
|
||||
ctx.SendWXMessage = function (text) { sent.push(JSON.parse(text)); };
|
||||
ctx.ACTIONS = [{ id: "layer", title: "Go to layer", input: "percent" }, { id: "tab", title: "Go to tab...", input: "tab" }];
|
||||
function lastRun() {
|
||||
var m = sent[sent.length - 1];
|
||||
return { command: m.command, id: m.id, title: m.title, args: m.args };
|
||||
}
|
||||
ctx.run({ id: "undo", title: "Undo" });
|
||||
assert.deepStrictEqual(lastRun(), { command: "run_action", id: "undo", title: "Undo", args: {} }, "a plain pick sends no arguments");
|
||||
ctx.runJumpToLayer("50");
|
||||
assert.deepStrictEqual(lastRun(), { command: "run_action", id: "layer", title: "Go to layer", args: { percent: 50 } },
|
||||
"the percent phase sends the percent as a number");
|
||||
ctx.jumpToTab({ id: "preview", title: "Preview" });
|
||||
assert.deepStrictEqual(lastRun(), { command: "run_action", id: "tab", title: "Go to tab...", args: { tab: "preview" } },
|
||||
"the tab phase sends the tab's id");
|
||||
assert.equal(sent.length, 3, "each pick sends one message");
|
||||
delete ctx.SendWXMessage;
|
||||
ctx.ACTIONS = actionsBefore;
|
||||
|
||||
// ---- hover preview commit timing ---------------------------------------------------------
|
||||
// The footer preview commits only after the pointer rests on a row, so a pointer crossing the rows
|
||||
// between a rested row and the footer must not preview them (style.css rows are 44px). The timing
|
||||
|
|
@ -614,7 +682,8 @@ var fakeNow = 0;
|
|||
var fakeTimers = [];
|
||||
var nextTimerId = 1;
|
||||
ctx.document = { body: null }; // requestResize stops at the missing body
|
||||
ctx.Date.now = function () { return fakeNow; };
|
||||
// Date is a built-in of the context, not a property of the sandbox object, so it is reached by evaluation.
|
||||
vm.runInContext("Date", ctx).now = function () { return fakeNow; };
|
||||
ctx.setTimeout = function (fn, ms) {
|
||||
var t = { id: nextTimerId++, at: fakeNow + Math.max(0, ms || 0), fn: fn };
|
||||
fakeTimers.push(t);
|
||||
|
|
|
|||
139
resources/web/dialog/css/step_rail.css
Normal file
139
resources/web/dialog/css/step_rail.css
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
/* The step rail that Action Replay and Agent Activity draw a list of calls with: a numbered dot per step on a
|
||||
* thread that takes the accent as steps pass, the step's title and target, its time at the side, and its detail
|
||||
* when opened. Colours come from the host theme contract (--orca-*) and theme.css's status roles, so it follows the
|
||||
* app in light and dark. A page links it after theme.css and before its own style.css. */
|
||||
|
||||
:root {
|
||||
--sr-bg: var(--orca-bg, #ffffff);
|
||||
--sr-fg: var(--orca-fg, #262e30);
|
||||
--sr-muted: var(--orca-muted, #6b7478);
|
||||
--sr-rule: var(--border, #dcdfe1);
|
||||
--sr-accent: var(--orca-accent, #009688);
|
||||
--sr-accent-fg: var(--orca-accent-fg, #ffffff);
|
||||
--sr-pass: var(--plugin-status-ok, #137333);
|
||||
--sr-fail: var(--plugin-status-danger, #b42318);
|
||||
--sr-fail-bg: var(--plugin-status-danger-bg, rgba(180, 35, 24, 0.12));
|
||||
--sr-warn: var(--plugin-status-warn, #a15c00);
|
||||
--sr-warn-bg: var(--plugin-status-warn-bg, rgba(199, 122, 22, 0.12));
|
||||
--sr-hover: var(--row-hover, #f7f9fb);
|
||||
--sr-ring: rgba(0, 150, 136, 0.25);
|
||||
--sr-ring-soft: rgba(0, 150, 136, 0.1);
|
||||
--sr-mono: var(--code-font);
|
||||
--sr-dot: 20px;
|
||||
}
|
||||
|
||||
.rail { list-style: none; margin: 0; padding: 6px 0 10px; }
|
||||
.step {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-columns: var(--sr-dot) minmax(0, 1fr) auto;
|
||||
column-gap: 10px;
|
||||
padding: 0 12px 0 14px;
|
||||
}
|
||||
/* The thread from this step's dot down to the next one; it takes the accent once the step passed. */
|
||||
.step::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: calc(14px + var(--sr-dot) / 2 - 1px);
|
||||
top: calc(6px + var(--sr-dot));
|
||||
bottom: -6px;
|
||||
width: 2px;
|
||||
background: var(--sr-rule);
|
||||
transition: background-color 240ms ease;
|
||||
}
|
||||
.step:last-child::before { display: none; }
|
||||
.step.is-done::before, .step.is-warn::before { background: var(--sr-accent); }
|
||||
.dot {
|
||||
margin-top: 6px;
|
||||
width: var(--sr-dot);
|
||||
height: var(--sr-dot);
|
||||
border-radius: 50%;
|
||||
border: 1.5px solid var(--sr-rule);
|
||||
background: var(--sr-bg);
|
||||
color: var(--sr-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.step.is-done .dot { background: var(--sr-accent); border-color: var(--sr-accent); color: var(--sr-accent-fg); }
|
||||
.step.is-warn .dot { background: var(--sr-warn); border-color: var(--sr-warn); color: #ffffff; }
|
||||
.step.is-fail .dot, .step.is-stopped .dot { background: var(--sr-fail); border-color: var(--sr-fail); color: #ffffff; }
|
||||
.step.is-running .dot { border-color: var(--sr-accent); color: var(--sr-accent); animation: sr-ring 1.4s ease-in-out infinite; }
|
||||
@keyframes sr-ring {
|
||||
0%, 100% { box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
50% { box-shadow: 0 0 0 5px var(--sr-ring-soft); }
|
||||
}
|
||||
|
||||
.step-main { min-width: 0; }
|
||||
.step-head {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 6px 4px 6px 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.step-title { font-weight: 600; }
|
||||
.step-what, .step-args { display: block; color: var(--sr-muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.step-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
padding: 0 6px;
|
||||
border-radius: 3px;
|
||||
color: var(--sr-warn);
|
||||
background: var(--sr-warn-bg);
|
||||
}
|
||||
.tag.is-check { color: var(--sr-muted); background: none; border: 1px solid var(--sr-rule); }
|
||||
|
||||
.step-side { display: flex; align-items: flex-start; gap: 6px; padding-top: 7px; }
|
||||
.time { font-size: 12px; color: var(--sr-muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.step.is-running .time { color: var(--sr-accent); }
|
||||
|
||||
/* ---- an opened step ---- */
|
||||
.step-detail { padding: 2px 0 10px; font-size: 12px; }
|
||||
.step.is-open { background: var(--sr-hover); }
|
||||
.args { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 12px; margin: 0 0 6px; }
|
||||
.args dt { color: var(--sr-muted); }
|
||||
.args dd { margin: 0; font-family: var(--sr-mono); font-size: 11.5px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.failure {
|
||||
margin: 4px 0 6px;
|
||||
padding: 6px 8px;
|
||||
border-left: 2px solid var(--sr-fail);
|
||||
border-radius: 0 3px 3px 0;
|
||||
background: var(--sr-fail-bg);
|
||||
}
|
||||
.step.is-warn .failure { border-left-color: var(--sr-warn); background: var(--sr-warn-bg); }
|
||||
.failure-detail { display: block; margin-top: 3px; color: var(--sr-muted); overflow-wrap: anywhere; }
|
||||
.thumb {
|
||||
display: block;
|
||||
width: 160px;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.raw {
|
||||
margin: 6px 0 0;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--sr-rule);
|
||||
border-radius: 3px;
|
||||
font-family: var(--sr-mono);
|
||||
font-size: 11px;
|
||||
white-space: pre;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.step.is-running .dot { animation: none; box-shadow: 0 0 0 2px var(--sr-ring); }
|
||||
.step::before { transition: none; }
|
||||
}
|
||||
127
resources/web/dialog/js/code_editor.css
Normal file
127
resources/web/dialog/js/code_editor.css
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
/* The code editors' theme, ace-orca (code_editor.js applies it as an object, so Ace loads no theme file). Its colours
|
||||
* come from the host theme contract (--orca-*) and the tokens below, which follow the app into dark mode through
|
||||
* theme.css's data-orca-theme, as the rest of a page does. The syntax colours stay apart from the status colours, so a
|
||||
* string never reads as a warning. A page sets the editor's size and border; this sets what is inside it. */
|
||||
|
||||
:root {
|
||||
--code-bg: var(--orca-bg, #ffffff);
|
||||
--code-fg: var(--orca-fg, #262e30);
|
||||
--code-muted: var(--orca-muted, #6b7478);
|
||||
--code-rule: var(--border, #dcdfe1);
|
||||
--code-accent: var(--orca-accent, #009688);
|
||||
--code-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12));
|
||||
--code-gutter: #f6f7f8;
|
||||
--code-selection: rgba(0, 150, 136, 0.22);
|
||||
--code-font: "Cascadia Code", Consolas, "SF Mono", Menlo, "DejaVu Sans Mono", monospace;
|
||||
--code-key: #00796b;
|
||||
--code-string: #8a4b08;
|
||||
--code-number: #6639ba;
|
||||
--code-punct: #8a9397;
|
||||
--code-comment: #7d8589;
|
||||
--code-keyword: #1f5f99;
|
||||
--code-builtin: #00796b;
|
||||
--code-pop-bg: var(--ctx-bg, #ffffff);
|
||||
--code-pop-border: var(--ctx-border, #cccccc);
|
||||
--code-pop-shadow: 0 6px 20px rgba(20, 30, 35, 0.16);
|
||||
}
|
||||
:root[data-orca-theme="dark"] {
|
||||
--code-gutter: #28282c;
|
||||
--code-selection: rgba(0, 150, 136, 0.35);
|
||||
--code-key: #4db6ac;
|
||||
--code-string: #d9a35f;
|
||||
--code-number: #b79af0;
|
||||
--code-punct: #7f858b;
|
||||
--code-comment: #858a90;
|
||||
--code-keyword: #7cb4f0;
|
||||
--code-builtin: #4db6ac;
|
||||
--code-pop-shadow: 0 6px 20px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.ace-orca {
|
||||
background: var(--code-bg);
|
||||
color: var(--code-fg);
|
||||
font-family: var(--code-font);
|
||||
}
|
||||
.ace-orca .ace_gutter {
|
||||
background: var(--code-gutter);
|
||||
color: var(--code-muted);
|
||||
border-right: 1px solid var(--code-rule);
|
||||
}
|
||||
.ace-orca .ace_gutter-active-line { background: transparent; }
|
||||
.ace-orca .ace_cursor { color: var(--code-fg); }
|
||||
.ace-orca .ace_marker-layer .ace_selection { background: var(--code-selection); }
|
||||
.ace-orca .ace_marker-layer .ace_selected-word { border: 1px solid var(--code-selection); }
|
||||
/* The bracket matching the one at the caret. */
|
||||
.ace-orca .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid var(--code-accent); }
|
||||
.ace-orca .ace_placeholder { color: var(--code-muted); font-family: inherit; }
|
||||
.ace-orca .ace_fold { background: var(--code-accent-tint); border-color: var(--code-accent); }
|
||||
.ace-orca .ace_indent-guide { background: none; box-shadow: inset -1px 0 0 var(--code-rule); }
|
||||
.ace-orca .ace_invisible { color: var(--code-rule); }
|
||||
|
||||
/* Tokens: a replay's keys, strings, ${…}, numbers and literals; Python's keywords and built-ins. */
|
||||
.ace-orca .ace_comment { color: var(--code-comment); font-style: italic; }
|
||||
.ace-orca .ace_variable { color: var(--code-key); }
|
||||
.ace-orca .ace_string { color: var(--code-string); }
|
||||
.ace-orca .ace_orca_var { color: var(--code-accent); background: var(--code-accent-tint); border-radius: 2px; }
|
||||
.ace-orca .ace_constant.ace_numeric,
|
||||
.ace-orca .ace_constant.ace_language { color: var(--code-number); }
|
||||
.ace-orca .ace_paren,
|
||||
.ace-orca .ace_punctuation,
|
||||
.ace-orca .ace_keyword.ace_operator { color: var(--code-punct); }
|
||||
.ace-orca .ace_keyword { color: var(--code-keyword); }
|
||||
.ace-orca .ace_support.ace_function { color: var(--code-builtin); }
|
||||
|
||||
/* The suggestion list and its detail, which Ace draws with the editor's theme. */
|
||||
.ace-orca.ace_autocomplete {
|
||||
background: var(--code-pop-bg);
|
||||
color: var(--code-fg);
|
||||
border: 1px solid var(--code-pop-border);
|
||||
border-radius: 6px;
|
||||
box-shadow: var(--code-pop-shadow);
|
||||
}
|
||||
.ace-orca.ace_autocomplete .ace_marker-layer .ace_active-line,
|
||||
.ace-orca.ace_autocomplete .ace_selected { background: var(--code-accent-tint); }
|
||||
.ace-orca.ace_autocomplete .ace_line-hover { background: var(--code-accent-tint); border: 0; }
|
||||
.ace-orca.ace_autocomplete .ace_completion-highlight { color: var(--code-accent); font-weight: 600; text-shadow: none; }
|
||||
.ace-orca.ace_autocomplete .ace_completion-meta { color: var(--code-muted); opacity: 1; }
|
||||
.ace_tooltip.ace_doc-tooltip {
|
||||
background: var(--code-pop-bg);
|
||||
color: var(--code-muted);
|
||||
border: 1px solid var(--code-pop-border);
|
||||
border-radius: 6px;
|
||||
box-shadow: var(--code-pop-shadow);
|
||||
font-family: var(--code-font);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
/* The search box (Ctrl+F). */
|
||||
.ace-orca .ace_search {
|
||||
background: var(--code-pop-bg);
|
||||
color: var(--code-fg);
|
||||
border-color: var(--code-pop-border);
|
||||
box-shadow: var(--code-pop-shadow);
|
||||
}
|
||||
.ace-orca .ace_search_field {
|
||||
background: var(--code-bg);
|
||||
color: var(--code-fg);
|
||||
border-color: var(--code-rule);
|
||||
}
|
||||
.ace-orca .ace_search_field:focus,
|
||||
.ace-orca .ace_searchbtn:focus-visible,
|
||||
.ace-orca .ace_button:focus-visible { outline: 2px solid var(--code-accent); outline-offset: -1px; }
|
||||
.ace-orca .ace_searchbtn,
|
||||
.ace-orca .ace_button {
|
||||
background: var(--code-bg);
|
||||
color: var(--code-fg);
|
||||
border-color: var(--code-rule);
|
||||
}
|
||||
.ace-orca .ace_searchbtn:hover,
|
||||
.ace-orca .ace_button:hover { background: var(--code-accent-tint); }
|
||||
.ace-orca .ace_button.checked { border-color: var(--code-accent); color: var(--code-accent); opacity: 1; }
|
||||
.ace-orca .ace_search_counter { color: var(--code-muted); }
|
||||
.ace-orca .ace_searchbtn_close { filter: none; }
|
||||
:root[data-orca-theme="dark"] .ace-orca .ace_searchbtn_close { filter: invert(0.8); }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ace-orca .ace_cursor { animation: none !important; transition: none !important; }
|
||||
}
|
||||
268
resources/web/dialog/js/code_editor.js
Normal file
268
resources/web/dialog/js/code_editor.js
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
// The code editor of the bundled pages: Ace, vendored unmodified in resources/web/include/ace and loaded before this
|
||||
// file by script tags, since the pages are file:// URLs. Everything an editor uses is vendored, so nothing here may make
|
||||
// Ace fetch a file: workers are off, snippets are off, completers are passed as arrays (`true` would add Ace's snippet and
|
||||
// keyword completers), the theme is an object (code_editor.css holds its colours), modes are objects, and the default
|
||||
// commands that would load an extension the repo doesn't vendor are removed. Ace's own text (the search box, the
|
||||
// suggestion list, the read-only note, folding, the ARIA labels) comes from the page's strings under "code_editor"
|
||||
// (WebViewHostDialog::code_editor_strings()).
|
||||
|
||||
// Ace's default commands that load a file the repo doesn't vendor (the settings menu, the error marker, the prompt behind
|
||||
// Go to line, the command palette and the mode list).
|
||||
const UNVENDORED_COMMANDS = ["showSettingsMenu", "goToNextError", "goToPreviousError", "gotoline", "openCommandPalette",
|
||||
"openCommandPallete", "modeSelect"];
|
||||
|
||||
// How long after Ace's own undo, redo or select all the same action forwarded by the host is the same key press.
|
||||
const FORWARDED_KEY_WINDOW_MS = 150;
|
||||
|
||||
const IS_MAC = typeof navigator !== "undefined" && /Mac/.test(navigator.platform || navigator.userAgent);
|
||||
|
||||
let codeEditorConfigured = false;
|
||||
|
||||
// Ace's messages from the page's strings: each %s, in order, becomes Ace's $0, $1.
|
||||
function configureCodeEditor() {
|
||||
if (codeEditorConfigured) return;
|
||||
codeEditorConfigured = true;
|
||||
const strings = typeof ORCA_UI_STRINGS !== "undefined" && ORCA_UI_STRINGS && ORCA_UI_STRINGS.code_editor;
|
||||
if (!strings) return;
|
||||
const messages = {};
|
||||
for (const [key, text] of Object.entries(strings)) {
|
||||
let n = 0;
|
||||
messages[key] = String(text).replace(/%s/g, () => "$" + n++);
|
||||
}
|
||||
ace.config.setMessages(messages);
|
||||
}
|
||||
|
||||
function pageIsDark() { return document.documentElement.getAttribute("data-orca-theme") === "dark"; }
|
||||
|
||||
function setEditorDark(editor, dark) { editor.setTheme({ cssClass: "ace-orca", isDark: !!dark, cssText: "" }); }
|
||||
|
||||
// A position in the text as an offset, and back.
|
||||
function indexOf(editor, pos) { return editor.session.doc.positionToIndex(pos); }
|
||||
function positionOf(editor, index) { return editor.session.doc.indexToPosition(index); }
|
||||
|
||||
// Writes `edit` ({from, to, insert, back}, offsets in the text) as one change, the caret `back` characters before the end
|
||||
// of what was inserted.
|
||||
function applyEditorEdit(editor, edit) {
|
||||
const Range = ace.require("ace/range").Range;
|
||||
const start = positionOf(editor, edit.from);
|
||||
const end = positionOf(editor, edit.to);
|
||||
editor.session.replace(new Range(start.row, start.column, end.row, end.column), edit.insert);
|
||||
editor.selection.moveToPosition(positionOf(editor, edit.from + edit.insert.length - (edit.back || 0)));
|
||||
editor.renderer.scrollCursorIntoView();
|
||||
}
|
||||
|
||||
// A page's completer ({suggestionsAt, acceptEdit, identifierRegexps, triggerCharacters}) as an Ace completer. The list
|
||||
// shows what suggestionsAt() finds at the caret, in its order; accepting an item finds the range again at the caret,
|
||||
// since Ace keeps the list open and filters it while more is typed without asking again, and writes acceptEdit()'s edit.
|
||||
function aceCompleter(completer) {
|
||||
const adapted = {
|
||||
identifierRegexps: completer.identifierRegexps,
|
||||
triggerCharacters: completer.triggerCharacters,
|
||||
getCompletions(editor, session, pos, prefix, callback) {
|
||||
// Ctrl+Space opens the list as asked for; typing opens it on its own (autoShown).
|
||||
const explicit = !(editor.completer && editor.completer.autoShown);
|
||||
const found = completer.suggestionsAt(editor.getValue(), indexOf(editor, pos), explicit);
|
||||
if (!found || !found.items.length) return callback(null, []);
|
||||
const count = found.items.length;
|
||||
// Each completion names its completer, whose insertMatch() Ace then calls.
|
||||
callback(null, found.items.map((item, i) => ({ caption: item.label, value: item.label, meta: item.detail || "", score: count - i, item,
|
||||
completer: adapted })));
|
||||
},
|
||||
getDocTooltip(completion) {
|
||||
if (completion.item && completion.item.info && !completion.docText) completion.docText = completion.item.info;
|
||||
},
|
||||
insertMatch(editor, data) {
|
||||
const text = editor.getValue();
|
||||
const found = completer.suggestionsAt(text, indexOf(editor, editor.getCursorPosition()), true);
|
||||
if (!found) return;
|
||||
const edit = completer.acceptEdit(text, found, data.item);
|
||||
applyEditorEdit(editor, edit);
|
||||
// After the list has closed for this acceptance.
|
||||
if (edit.reopen) setTimeout(() => editor.execCommand("startAutocomplete"), 0);
|
||||
},
|
||||
};
|
||||
return adapted;
|
||||
}
|
||||
|
||||
// An editor in `element`: options = {mode (an Ace mode id), tabSize, placeholder, completer, onChange(text), commands}.
|
||||
// Each command is {name, bindKey: {win, mac}, exec(editor), readOnly}; one that doesn't edit the text is readOnly, since
|
||||
// Ace refuses any other in a read-only editor. onChange runs once per batch of changes, from the session's change event,
|
||||
// so the host's copy is never behind (Ace's own input event comes later).
|
||||
function createCodeEditor(element, options) {
|
||||
configureCodeEditor();
|
||||
const completers = options.completer ? [aceCompleter(options.completer)] : false;
|
||||
const editor = ace.edit(element, {
|
||||
useWorker: false,
|
||||
enableSnippets: false,
|
||||
enableBasicAutocompletion: completers,
|
||||
enableLiveAutocompletion: completers,
|
||||
useSoftTabs: true,
|
||||
tabSize: options.tabSize || 2,
|
||||
showPrintMargin: false,
|
||||
fixedWidthGutter: true,
|
||||
highlightActiveLine: false,
|
||||
fontSize: "12px",
|
||||
placeholder: options.placeholder || "",
|
||||
});
|
||||
editor.session.setNewLineMode("unix");
|
||||
const Mode = ace.require(options.mode).Mode;
|
||||
editor.session.setMode(new Mode());
|
||||
setEditorDark(editor, pageIsDark());
|
||||
new MutationObserver(() => setEditorDark(editor, pageIsDark()))
|
||||
.observe(document.documentElement, { attributes: true, attributeFilter: ["data-orca-theme"] });
|
||||
|
||||
for (const name of UNVENDORED_COMMANDS) editor.commands.removeCommand(name);
|
||||
// Shift+Enter is the page's (Run cell) even while the suggestion list is open.
|
||||
if (completers) ace.require("ace/autocomplete").Autocomplete.for(editor).keyboardHandler.removeCommand("Shift-Return");
|
||||
editor.$orcaCommands = new Set();
|
||||
for (const command of options.commands || []) {
|
||||
editor.commands.addCommand(command);
|
||||
editor.$orcaCommands.add(command.name);
|
||||
}
|
||||
|
||||
editor.$orcaOwnAt = {};
|
||||
editor.commands.on("afterExec", (e) => {
|
||||
if (!editor.$orcaForwarding) editor.$orcaOwnAt[e.command.name] = Date.now();
|
||||
});
|
||||
document.addEventListener("keydown", (e) => recordFieldKey(editor, e), true);
|
||||
let reported = false;
|
||||
editor.session.on("change", () => {
|
||||
if (editor.$orcaQuiet || reported || !options.onChange) return;
|
||||
reported = true;
|
||||
queueMicrotask(() => {
|
||||
reported = false;
|
||||
options.onChange(editor.getValue());
|
||||
});
|
||||
});
|
||||
return editor;
|
||||
}
|
||||
|
||||
// Replaces the text without reporting it as an edit, with no undo history and the caret at the start.
|
||||
function setEditorText(editor, text) {
|
||||
editor.$orcaQuiet = true;
|
||||
try {
|
||||
editor.session.setValue(text);
|
||||
} finally {
|
||||
editor.$orcaQuiet = false;
|
||||
}
|
||||
editor.session.getUndoManager().reset();
|
||||
editor.clearSelection();
|
||||
editor.moveCursorTo(0, 0);
|
||||
editor.renderer.scrollToRow(0);
|
||||
}
|
||||
|
||||
function closeEditorSuggestions(editor) {
|
||||
if (editor.completer && editor.completer.activated) editor.completer.detach();
|
||||
}
|
||||
|
||||
// ---- keys -------------------------------------------------------------------------------------------------------
|
||||
|
||||
// KeyChord::to_string()'s special key names and Ace's.
|
||||
const CHORD_TO_ACE_KEYS = { Backspace: "Backspace", Tab: "Tab", Enter: "Return", Esc: "Esc", Space: "Space", Del: "Delete",
|
||||
Ins: "Insert", Home: "Home", End: "End", PgUp: "PageUp", PgDn: "PageDown", Left: "Left",
|
||||
Right: "Right", Up: "Up", Down: "Down" };
|
||||
const ACE_TO_CHORD_KEYS = { backspace: "Backspace", tab: "Tab", return: "Enter", enter: "Enter", esc: "Esc", escape: "Esc",
|
||||
space: "Space", delete: "Del", del: "Del", insert: "Ins", home: "Home", end: "End",
|
||||
pageup: "PgUp", pagedown: "PgDn", left: "Left", right: "Right", up: "Up", down: "Down" };
|
||||
|
||||
// A chord in KeyChord::to_string()'s canonical form ("Ctrl+Shift+R", Ctrl being ⌘ on macOS) in Ace's ("Ctrl-Shift-R" off
|
||||
// macOS, "Command-Shift-R" on it). Never the translated text the menus show.
|
||||
function aceKey(chord) {
|
||||
const parts = chord.length > 1 && chord.endsWith("+") ? [...chord.slice(0, -2).split("+").filter(Boolean), "+"] : chord.split("+");
|
||||
const key = parts.pop();
|
||||
const name = CHORD_TO_ACE_KEYS[key] || key;
|
||||
const win = [];
|
||||
const mac = [];
|
||||
for (const modifier of parts) {
|
||||
if (modifier === "Ctrl") { win.push("Ctrl"); mac.push("Command"); }
|
||||
else if (modifier === "Shift") { win.push("Shift"); mac.push("Shift"); }
|
||||
else if (modifier === "Alt") { win.push("Alt"); mac.push("Option"); }
|
||||
else if (modifier === "RawCtrl") mac.push("Ctrl");
|
||||
}
|
||||
return { win: [...win, name].join("-"), mac: [...mac, name].join("-") };
|
||||
}
|
||||
|
||||
// An Ace key binding on this platform ("Ctrl-Shift-K", "Command-Alt-Up") in KeyChord's canonical form, or "" for one it
|
||||
// can't name (a key chain, a numpad key).
|
||||
function chordOf(binding) {
|
||||
if (/\s/.test(binding)) return "";
|
||||
const parts = binding.endsWith("--") ? [...binding.slice(0, -2).split("-").filter(Boolean), "-"] : binding.split("-");
|
||||
const key = parts.pop();
|
||||
const mods = new Set();
|
||||
for (const part of parts) {
|
||||
const p = part.toLowerCase();
|
||||
const control = p === "ctrl" || p === "control";
|
||||
// Ace's Ctrl is the Control key on macOS, where KeyChord's Ctrl is Command.
|
||||
if (p === "command" || p === "cmd" || (control && !IS_MAC)) mods.add("Ctrl");
|
||||
else if (control) mods.add("RawCtrl");
|
||||
else if (p === "shift") mods.add("Shift");
|
||||
else if (p === "alt" || p === "option") mods.add("Alt");
|
||||
else return "";
|
||||
}
|
||||
const name = ACE_TO_CHORD_KEYS[key.toLowerCase()] || (/^f\d+$/i.test(key) ? key.toUpperCase() : key.length === 1 ? key.toUpperCase() : "");
|
||||
if (!name) return "";
|
||||
return ["Ctrl", "Shift", "Alt", "RawCtrl"].filter((m) => mods.has(m)).map((m) => m + "+").join("") + name;
|
||||
}
|
||||
|
||||
// The chords Ace's own commands bind on this platform, in KeyChord's canonical form, leaving out the page's commands
|
||||
// (Save, Run, the toggle are the app's): what the host disables in its menus while the editor has the focus. Ace's own
|
||||
// bindings never change, so the list doesn't change with a rebinding.
|
||||
function editorChords(editor) {
|
||||
const platform = editor.commands.platform;
|
||||
const chords = new Set();
|
||||
for (const [name, command] of Object.entries(editor.commands.commands)) {
|
||||
if (editor.$orcaCommands.has(name) || !command.bindKey) continue;
|
||||
const binding = typeof command.bindKey === "string" ? command.bindKey : command.bindKey[platform];
|
||||
if (!binding) continue;
|
||||
for (const one of binding.split("|")) {
|
||||
const chord = chordOf(one.trim());
|
||||
if (chord) chords.add(chord);
|
||||
}
|
||||
}
|
||||
return [...chords];
|
||||
}
|
||||
|
||||
// The editor's own text input, where its commands take the keys. Ace's search box sits inside the editor too, but its
|
||||
// fields are text fields of their own.
|
||||
function isEditorText(editor, el) { return !!el && el === editor.textInput.getElement(); }
|
||||
|
||||
// A text field other than the editor's text (a console prompt, Ace's search fields), which does its own undo, redo and
|
||||
// select all.
|
||||
function isOtherTextField(editor, el) {
|
||||
return !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA") && !isEditorText(editor, el);
|
||||
}
|
||||
|
||||
// Whether the page's own `name` command (an editor command, or a key the page handled itself) ran within
|
||||
// FORWARDED_KEY_WINDOW_MS: the same key press the host then forwards from its menu.
|
||||
function ownKeyRan(editor, name) { return Date.now() - (editor.$orcaOwnAt[name] || 0) < FORWARDED_KEY_WINDOW_MS; }
|
||||
|
||||
// A key pressed in such a field: its undo, redo or select all is recorded as the editor's own commands are, so the same
|
||||
// press forwarded by the host's menu does nothing more.
|
||||
function recordFieldKey(editor, e) {
|
||||
if (!isOtherTextField(editor, e.target) || !(IS_MAC ? e.metaKey : e.ctrlKey) || e.altKey) return;
|
||||
const key = (e.key || "").toLowerCase();
|
||||
const name = key === "a" && !e.shiftKey ? "selectall" : key === "z" ? (e.shiftKey ? "redo" : "undo") : key === "y" && !e.shiftKey ? "redo" : "";
|
||||
if (name) editor.$orcaOwnAt[name] = Date.now();
|
||||
}
|
||||
|
||||
// Runs a forwarded "undo", "redo" or "select_all" (the host's Edit menu) unless the same action ran by its own key within
|
||||
// FORWARDED_KEY_WINDOW_MS, so one press acts once whichever way it reached the page. A focused text field outside the
|
||||
// editor takes it; otherwise the editor does.
|
||||
function runEditorAction(editor, action) {
|
||||
const name = { undo: "undo", redo: "redo", select_all: "selectall" }[action];
|
||||
if (!name || ownKeyRan(editor, name)) return;
|
||||
const field = document.activeElement;
|
||||
if (isOtherTextField(editor, field)) {
|
||||
if (name === "selectall") field.select();
|
||||
else document.execCommand(name);
|
||||
return;
|
||||
}
|
||||
editor.$orcaForwarding = true;
|
||||
try {
|
||||
editor.execCommand(name);
|
||||
} finally {
|
||||
editor.$orcaForwarding = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof module !== "undefined") module.exports = { runEditorAction, recordFieldKey, ownKeyRan, isEditorText, IS_MAC };
|
||||
90
resources/web/dialog/js/code_editor.test.js
Normal file
90
resources/web/dialog/js/code_editor.test.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// The shared code editor's forwarded actions, run with `node --test`. Ace isn't loaded: the editor and the page are
|
||||
// stand-ins with the parts these functions touch.
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { runEditorAction, recordFieldKey, ownKeyRan, isEditorText, IS_MAC } = require("./code_editor.js");
|
||||
|
||||
// Undo pressed in a field: Cmd+Z on macOS, Ctrl+Z elsewhere, as the page reads it on the platform running the test.
|
||||
function undoPress(target) {
|
||||
return { target, key: "z", ctrlKey: !IS_MAC, metaKey: IS_MAC, shiftKey: false, altKey: false };
|
||||
}
|
||||
|
||||
function page() {
|
||||
const editorText = { tagName: "TEXTAREA" }; // Ace's hidden textarea, inside the editor
|
||||
const prompt = { tagName: "INPUT", selected: 0, select() { this.selected++; } };
|
||||
const button = { tagName: "BUTTON" };
|
||||
// Ace's search box sits inside the editor's container, but its fields are text fields of their own.
|
||||
const search = { tagName: "INPUT", selected: 0, select() { this.selected++; } };
|
||||
const editor = {
|
||||
container: { contains: (el) => el === editorText || el === search },
|
||||
textInput: { getElement: () => editorText },
|
||||
$orcaOwnAt: {},
|
||||
ran: [],
|
||||
execCommand(name) { this.ran.push(name); },
|
||||
};
|
||||
const doc = { activeElement: editorText, ran: [], execCommand(name) { this.ran.push(name); return true; } };
|
||||
global.document = doc;
|
||||
return { editor, doc, editorText, prompt, button, search };
|
||||
}
|
||||
|
||||
test("a forwarded undo or redo with a text field focused acts on the field, not the script", () => {
|
||||
const p = page();
|
||||
p.doc.activeElement = p.prompt;
|
||||
runEditorAction(p.editor, "undo");
|
||||
runEditorAction(p.editor, "redo");
|
||||
assert.deepEqual(p.doc.ran, ["undo", "redo"]);
|
||||
assert.deepEqual(p.editor.ran, []);
|
||||
});
|
||||
|
||||
test("a forwarded select all with a text field focused selects the field's text", () => {
|
||||
const p = page();
|
||||
p.doc.activeElement = p.prompt;
|
||||
runEditorAction(p.editor, "select_all");
|
||||
assert.equal(p.prompt.selected, 1);
|
||||
assert.deepEqual(p.editor.ran, []);
|
||||
});
|
||||
|
||||
test("a forwarded action with the editor or a button focused acts on the script", () => {
|
||||
const p = page();
|
||||
runEditorAction(p.editor, "undo");
|
||||
p.doc.activeElement = p.button;
|
||||
runEditorAction(p.editor, "select_all");
|
||||
assert.deepEqual(p.editor.ran, ["undo", "selectall"]);
|
||||
assert.deepEqual(p.doc.ran, []);
|
||||
});
|
||||
|
||||
test("a field's own undo key is recorded, so the same press forwarded by the host does nothing more", () => {
|
||||
const p = page();
|
||||
p.doc.activeElement = p.prompt;
|
||||
recordFieldKey(p.editor, undoPress(p.prompt));
|
||||
runEditorAction(p.editor, "undo");
|
||||
assert.deepEqual(p.doc.ran, []);
|
||||
assert.deepEqual(p.editor.ran, []);
|
||||
});
|
||||
|
||||
test("a key in the editor is left to the editor's own commands", () => {
|
||||
const p = page();
|
||||
recordFieldKey(p.editor, undoPress(p.editorText));
|
||||
assert.deepEqual(p.editor.$orcaOwnAt, {});
|
||||
});
|
||||
|
||||
test("Ace's search field takes the forwarded actions itself, as a field outside the editor does", () => {
|
||||
const p = page();
|
||||
p.doc.activeElement = p.search;
|
||||
runEditorAction(p.editor, "undo");
|
||||
runEditorAction(p.editor, "select_all");
|
||||
assert.deepEqual(p.doc.ran, ["undo"]);
|
||||
assert.equal(p.search.selected, 1);
|
||||
assert.deepEqual(p.editor.ran, []);
|
||||
assert.equal(isEditorText(p.editor, p.search), false);
|
||||
assert.equal(isEditorText(p.editor, p.editorText), true);
|
||||
});
|
||||
|
||||
test("a forwarded Save right after the page's own is the same key press", () => {
|
||||
const p = page();
|
||||
p.editor.$orcaOwnAt.save = Date.now();
|
||||
assert.equal(ownKeyRan(p.editor, "save"), true);
|
||||
p.editor.$orcaOwnAt.save = Date.now() - 1000;
|
||||
assert.equal(ownKeyRan(p.editor, "save"), false);
|
||||
assert.equal(ownKeyRan(p.editor, "saveAs"), false);
|
||||
});
|
||||
|
|
@ -74,6 +74,20 @@ function BuildCustomConfigDocument(html, config, context) {
|
|||
|
||||
window.addEventListener("message", function (event) {
|
||||
if (!event.data) return;
|
||||
// The MCP server's page agent (resources/web/mcp/page_agent.js) can't read this sandboxed
|
||||
// frame, so the parent page's agent relays its calls here and this frame runs its own copy.
|
||||
if (event.data.__orca === "mcp") {
|
||||
if (event.source !== parent) return;
|
||||
var d = event.data, reply;
|
||||
try {
|
||||
if (!(window.__orcaMcp && window.__orcaMcp.v === d.v)) (new Function("V", "SRC", d.src))(d.v, d.src);
|
||||
reply = window.__orcaMcp.call(d.req);
|
||||
} catch (e) {
|
||||
reply = { error: String(e && e.message || e), code: "relay" };
|
||||
}
|
||||
parent.postMessage({ __orca: "mcp_reply", id: d.id, reply: reply }, "*");
|
||||
return;
|
||||
}
|
||||
if (event.data.__orca === "theme") { applyTheme(event.data.theme); return; }
|
||||
if (event.data.__orca !== "config") return;
|
||||
current = event.data.config || {};
|
||||
|
|
|
|||
24
resources/web/include/ace/LICENSE
Normal file
24
resources/web/include/ace/LICENSE
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
Copyright (c) 2010, Ajax.org B.V.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of Ajax.org B.V. nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
23
resources/web/include/ace/ace.js
Normal file
23
resources/web/include/ace/ace.js
Normal file
File diff suppressed because one or more lines are too long
8
resources/web/include/ace/ext-language_tools.js
Normal file
8
resources/web/include/ace/ext-language_tools.js
Normal file
File diff suppressed because one or more lines are too long
8
resources/web/include/ace/ext-searchbox.js
Normal file
8
resources/web/include/ace/ext-searchbox.js
Normal file
File diff suppressed because one or more lines are too long
8
resources/web/include/ace/mode-json.js
Normal file
8
resources/web/include/ace/mode-json.js
Normal file
File diff suppressed because one or more lines are too long
8
resources/web/include/ace/mode-python.js
Normal file
8
resources/web/include/ace/mode-python.js
Normal file
File diff suppressed because one or more lines are too long
2124
resources/web/mcp/page_agent.js
Normal file
2124
resources/web/mcp/page_agent.js
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -2,36 +2,42 @@
|
|||
|
||||
Everything here supports the parametric Design tab (`src/libslic3r/CAD/`,
|
||||
`src/slic3r/GUI/CAD/`). Nothing here is needed to build or run OrcaSlicer — these
|
||||
are the development and verification tools for that one feature.
|
||||
are the development and verification tools for that one feature. The kernel's own unit
|
||||
tests are not here: they are part of `libslic3r_tests` and run under `ctest` like any
|
||||
other suite.
|
||||
|
||||
The verb in the name is the role:
|
||||
## Checks against a running app
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `build-…` | produce a binary |
|
||||
| `start-…` | bring something up and leave it running |
|
||||
| `run-…` | run a suite and report pass/fail |
|
||||
| `check-…` | one specific assertion, usually driving a live app |
|
||||
Three checks drive the Design tab through the app's MCP server, with the same Design commands an
|
||||
agent calls, and compare what the app reports with arithmetic. Each needs a running
|
||||
OrcaSlicer with the MCP server on (`--mcp`, or "MCP server" under AI features in
|
||||
Preferences) and the CAD feature on (Preferences > Features, which takes effect after a restart).
|
||||
`tools/mcp/orca_mcp.py launch --cad` starts one with both. A check finds the app through
|
||||
its data directory, where the server writes its port and token: the one passed to the check,
|
||||
else `$ORCA_DATADIR`, else the platform's own (`tools/mcp/README.md` describes attaching).
|
||||
They run on Windows, macOS and Linux, and exit 0 when every assertion held.
|
||||
|
||||
## Verification
|
||||
|
||||
| Script | What it proves | Needs |
|
||||
| Check | What it proves | Run it |
|
||||
|---|---|---|
|
||||
| `run-kernel-tests.sh` | The CAD kernel builds and the Catch2 `[CadDocument]` tags pass — every case builds a document, recomputes it and asserts on real geometry. **Exit 0 is the verification contract.** | Docker only. No display. |
|
||||
| `run-all-checks.sh` | Every check below, in one command. The gate before pushing a Design-tab change. | Docker + the GUI container |
|
||||
| `check-sketch-engine.py` | A ladder of 2D sketches of increasing complexity, judged on loop count, closure and void attribution rather than on area. | Kernel only |
|
||||
| `check-sketch-engine-corpus.py` | The same ladder graded against a systematic sample of real drawings instead of shapes we chose. | Kernel + corpus |
|
||||
| `check-gui-sketching.py` | The same profiles drawn the way a person draws them — synthetic mouse gestures and typed values. | Headless GUI |
|
||||
| `check-gui-context-menu.py` | That right-click is the pivot of the design gesture, and adapts to what was clicked. | Headless GUI |
|
||||
| `check-mcp-sketch.py` | The sketch layer driven over the MCP socket, asserting what decides whether a profile is buildable. | Headless GUI + `ORCA_CAD_MCP` |
|
||||
| `check-mcp-sketch.py` | The sketch layer, asserting what decides whether a profile is buildable: closed loops, offsets that survive, a circle read as a void rather than a second body. | `python3 scripts/CAD/check-mcp-sketch.py [datadir]` |
|
||||
| `check-sketch-engine.py` | A ladder of 2D sketches of increasing complexity, judged on vertices, lengths, radii, tangency, symmetry and closure rather than on area. | `python3 scripts/CAD/check-sketch-engine.py [datadir]` |
|
||||
| `check-sketch-engine-corpus.py` | The same ladder graded against real drawings: a systematic sample of the StudyCadCam sheets, each judged against its own vector geometry. | `python3 scripts/CAD/check-sketch-engine-corpus.py --corpus DIR [--datadir DIR] [--step N] [--limit N] [--scale] [--budget S]` |
|
||||
|
||||
**`run-kernel-tests.sh` is the only one CI can run.** The rest need a live
|
||||
application with an OpenGL canvas and synthetic input, which hosted runners do not
|
||||
have. The kernel suite itself is already in CI by an ordinary route: the cases are
|
||||
registered in `tests/libslic3r/CMakeLists.txt` under `if (SLIC3R_CAD)`, so they are
|
||||
part of `libslic3r_tests` and run under `ctest` on every platform like any other
|
||||
unit test. This script exists for the local loop, where it is a two-minute round
|
||||
trip instead of a full application build.
|
||||
For example:
|
||||
|
||||
python3 tools/mcp/orca_mcp.py launch --cad --datadir <datadir>
|
||||
python3 scripts/CAD/check-sketch-engine.py <datadir>
|
||||
python3 tools/mcp/orca_mcp.py stop
|
||||
|
||||
The corpus check takes the folder of `MPD*.pdf` sheets, which is not in the repository, and
|
||||
reads them with poppler's `pdftocairo` and `pdfinfo`, which must be on the PATH. It grades
|
||||
every 20th sheet by default (`--step`); `--scale` grades the largest drawings instead, each
|
||||
round trip within `--budget` seconds.
|
||||
|
||||
The Design tab's GUI tests, which draw on the canvas with the mouse and keyboard as a person
|
||||
does, are MCP harness tests in `tools/mcp/` (`test_cad_sketching.py` and
|
||||
`test_cad_context_menu.py`); `tools/mcp/test-entries/design.md` says
|
||||
what they check, and `tools/mcp/README.md` how to run them.
|
||||
|
||||
## Generated sources
|
||||
|
||||
|
|
@ -40,29 +46,35 @@ compiled against it cannot drift apart:
|
|||
|
||||
| Generator | Source | Output |
|
||||
|---|---|---|
|
||||
| `gen_offer_table.py` | `tool_atlas.json` — every offer verb with its row, key, icon, accepted selections and refusal string | `src/slic3r/GUI/CAD/DesignOffer.hpp` |
|
||||
| `mate-glyph/emit_glyph_table.py` | `mate-glyph/bear_outline.json`, measured off `mate-glyph/bear.step` by `extract_outline.py` (needs FreeCAD) | the `kBear…` tables in `DesignSketchTool.cpp` |
|
||||
| `gen_offer_table.py` | `tool_atlas.json` — the Design tab's table: every offer verb with its row, key, icon, accepted selections and refusal string, and every Design command's silent form (a `tool` block) | `src/slic3r/GUI/CAD/DesignOffer.hpp` |
|
||||
| `mate-glyph/emit_glyph_table.py` | `mate-glyph/bear_outline.json`, measured off `mate-glyph/bear.step` by `extract_outline.py` | the `kBear…` tables in `DesignSketchTool.cpp` |
|
||||
|
||||
The atlas's `verbs` are one table for three things: the right-click menu (a verb with a `slot` has an
|
||||
item there), the Speed Dial's Design tab actions and the Design commands. Every verb but a folded or a
|
||||
greyed item (`fold`; `pat_curve`, `align_to`) is a command whose key is its `id`. A verb with a handler
|
||||
(`action`) does what its menu item does when called
|
||||
with no arguments, in the mode the item belongs to, and has an action of its own in the Speed Dial; one
|
||||
with a `tool` block also runs silently
|
||||
with arguments, and the block holds what that form takes and does: its `access` (`read`, `change` or
|
||||
`sketch`, which decides what a busy Design tab lets through), `ok_false` (it reports a rejected rebuild
|
||||
in its reply), a `summary` of one sentence,
|
||||
`details`, its `params` (each with `name`, `type`, `unit`, `default`, limits `min`, `exclusive_min` and
|
||||
`max`, `enum` and `description`; one with no default is required, and one whose default is null also takes
|
||||
null, unless `nullable` is false, which marks a param whose function reads a null as given), one to three
|
||||
`examples` and `ids`
|
||||
(it takes or gives face and edge ids). Entries with no `slot` and no handler are commands only, and
|
||||
`modal` marks a verb whose handler opens a dialog. `src/slic3r/GUI/Mcp/Tools/Design*.cpp` bind each block
|
||||
to the function that runs it (`silent_forms()`), and a unit test fails when a block has no function or a
|
||||
function no block. The generator refuses an entry with no slot that has neither a handler nor a block.
|
||||
|
||||
`python3 scripts/CAD/gen_offer_table.py` rewrites the header and `--check` proves the
|
||||
checked-in one matches the atlas — `run-all-checks.sh` runs the check as its first rung,
|
||||
which is what makes the header's "GENERATED — DO NOT EDIT" enforceable. Edit the atlas,
|
||||
never the header.
|
||||
checked-in one matches the atlas. The "Check CAD offer table" workflow
|
||||
(`.github/workflows/check_cad_offer_table.yml`) runs the check on every push and pull
|
||||
request that touches the atlas, the generator or the header, which is what makes the
|
||||
header's "GENERATED — DO NOT EDIT" enforceable. Edit the atlas, never the header.
|
||||
|
||||
## Build and run
|
||||
|
||||
| Script | Purpose |
|
||||
|---|---|
|
||||
| `build-gui.sh` | Build the GUI binary in a throwaway container, writing into the build-cache volume the long-lived GUI container reads. |
|
||||
| `build-gui-incremental.sh` | Incremental build against the deps-baked image, for a fast edit/compile loop. |
|
||||
| `start-headless-gui.sh` | Bring the app up on a headless X display (Xvfb + a window manager), ready to drive or attach to over VNC. |
|
||||
|
||||
Two constraints that are not obvious and have each cost a session:
|
||||
|
||||
- **Never build inside the GUI container.** Its baked source tree silently
|
||||
reconfigures the shared build directory and this fork's targets vanish.
|
||||
- **A window manager is required.** Without one, windows are never focused, and an
|
||||
unfocused GTK app ignores synthetic keys — which looks exactly like a code bug.
|
||||
|
||||
`scripts/CAD/rig_build_traps.md` documents these and three more, with symptoms and exact
|
||||
recovery commands. Read it before debugging a configure or link failure one of
|
||||
these scripts reports.
|
||||
`mate-glyph/` holds the bear connector the mate glyph is drawn from. `extract_outline.py`
|
||||
runs in FreeCAD's Python (it reads the STEP with `Part`) and writes `bear_outline.json`.
|
||||
`emit_glyph_table.py` runs in plain Python and simplifies that outline into the C++ tables,
|
||||
printing them and writing them to `bear_glyph_table.h` beside it; `DesignSketchTool.cpp`
|
||||
holds them as emitted.
|
||||
|
|
|
|||
|
|
@ -1,81 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Incremental slicer build against the orcacad-deps base image.
|
||||
#
|
||||
# The deps-baked image (built from scripts/Dockerfile.deps) carries the pinned
|
||||
# dependencies at /OrcaSlicer/deps/build/destdir. This script mounts the LIVE source
|
||||
# tree and resources over the baked copy so code/CMake edits apply immediately, and
|
||||
# persists /OrcaSlicer/build in a named volume so ninja recompiles only what changed.
|
||||
#
|
||||
# Result: edit -> rebuild in seconds-to-minutes instead of a full Docker rebuild.
|
||||
#
|
||||
# Usage (run on the build host, e.g. behemoth, from anywhere):
|
||||
# scripts/CAD/build-gui-incremental.sh
|
||||
# IMAGE=orcacad-deps scripts/CAD/build-gui-incremental.sh
|
||||
#
|
||||
# On success the binary is inside the persistent volume at
|
||||
# /OrcaSlicer/build/package/bin/orca-slicer (copy it out with a follow-up
|
||||
# `docker run --rm -v orcacad_buildcache:/b alpine cp ...` or via this script's tail).
|
||||
# Rig build traps already paid for once each (stale project, NLopt cache, pybind11, OCCT_LIBS, SLIC3R_CAD gate): scripts/CAD/rig_build_traps.md
|
||||
set -euo pipefail
|
||||
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# orcacad-deps, NOT snapmaker-deps: see the note in run-kernel-tests.sh — the wrong image
|
||||
# fails at CMake configure, not at link time.
|
||||
IMAGE="${IMAGE:-orcacad-deps}"
|
||||
BUILD_VOL="${BUILD_VOL:-orcacad_buildcache}"
|
||||
|
||||
echo "REPO=$REPO IMAGE=$IMAGE BUILD_VOL=$BUILD_VOL"
|
||||
|
||||
# The root CMakeLists.txt and cmake/ must be mounted too, not taken from the baked image:
|
||||
# they carry the build-time gates (e.g. SLIC3R_CAD -> add_definitions(-DSLIC3R_CAD)) that the
|
||||
# mounted headers are compiled against. With a stale baked copy the gate silently stays off and
|
||||
# the build fails with "class GLCanvas3D has no member named set_design_sketch_tool".
|
||||
#
|
||||
# build_linux.sh must be mounted for the same reason, and here the stale copy is guaranteed
|
||||
# wrong rather than merely risky: orcacad-deps is layered on snapmaker-deps, so the baked script
|
||||
# is the OTHER fork's and builds `--target Snapmaker_Orca`. This fork's target is `OrcaSlicer`,
|
||||
# so without this mount configure succeeds and then ninja dies on "unknown target".
|
||||
# scripts/ likewise: build_linux.sh's packaging step sources scripts/appimage_lib_policy.sh,
|
||||
# which the baked Snapmaker tree does not have, so a fully successful link still exited
|
||||
# non-zero with "missing AppImage helper" and the binary check never ran.
|
||||
|
||||
# ---- OOM guard (2026-08-21) -------------------------------------------------------------
|
||||
# Two of these builds ran at once on 2026-08-21, each with ninja -j$(nproc)=16: ~36 cc1plus
|
||||
# holding 42 GB of a 62 GB box -> global OOM at 21:05, a 2h28m kill storm, ssh unreachable,
|
||||
# lightdm destroyed. Neither build produced a single object. scripts/CAD/build-gui.sh grew the
|
||||
# bounds first; every script that starts a compile needs the same three, or the guard is only
|
||||
# as strong as the script you happened not to use.
|
||||
# flock — the lock path is SHARED with build-gui.sh and the other fork on purpose, so
|
||||
# concurrent builds serialise instead of summing.
|
||||
# -j — bounded parallelism; ~1.17 GB per cc1plus was the measured average.
|
||||
# --memory — the actual guarantee: a runaway build dies in its own cgroup instead of taking
|
||||
# the host down. --memory-swap equal to --memory forbids swap, which is what made
|
||||
# ssh hang.
|
||||
JOBS="${JOBS:-12}"
|
||||
MEM="${MEM:-40g}"
|
||||
LOCK=/tmp/orca-rig-build.lock
|
||||
|
||||
exec 9>"$LOCK"
|
||||
if ! flock -n 9; then
|
||||
echo "another build holds $LOCK — waiting (this is the OOM guard, not a hang)"
|
||||
flock 9
|
||||
fi
|
||||
|
||||
docker run --rm \
|
||||
--memory="$MEM" --memory-swap="$MEM" \
|
||||
-v "$REPO/src":/OrcaSlicer/src \
|
||||
-v "$REPO/resources":/OrcaSlicer/resources \
|
||||
-v "$REPO/CMakeLists.txt":/OrcaSlicer/CMakeLists.txt \
|
||||
-v "$REPO/cmake":/OrcaSlicer/cmake \
|
||||
-v "$REPO/deps_src":/OrcaSlicer/deps_src \
|
||||
-v "$REPO/build_linux.sh":/OrcaSlicer/build_linux.sh \
|
||||
-v "$REPO/scripts":/OrcaSlicer/scripts \
|
||||
-v "$BUILD_VOL":/OrcaSlicer/build \
|
||||
"$IMAGE" \
|
||||
bash -lc "cd /OrcaSlicer && ./build_linux.sh -sr -j $JOBS"
|
||||
|
||||
# src/CMakeLists.txt:151 renames the OrcaSlicer target's output to "orca-slicer" — not
|
||||
# "snapmaker-orca", which is the other fork's binary name.
|
||||
echo "=== build finished; checking for binary ==="
|
||||
docker run --rm -v "$BUILD_VOL":/b "$IMAGE" \
|
||||
bash -lc 'ls -lh /b/package/bin/orca-slicer 2>/dev/null && file /b/package/bin/orca-slicer || echo "NO BINARY"'
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Rebuild the GUI binary the design rig launches — in a THROWAWAY container, writing into the
|
||||
# same build-cache volume the rig's long-lived GUI container reads from.
|
||||
#
|
||||
# NEVER build inside the GUI container (snapmaker-gui / orcacad-gui). Its baked /OrcaSlicer tree
|
||||
# is the Jun-13 Snapmaker-derived source, so a `cmake .` in there silently reconfigures the
|
||||
# shared build dir as project(Snapmaker_Orca) and this fork's targets vanish. That is Trap 1 of
|
||||
# five; all of them, with symptoms and exact recovery commands, are in scripts/CAD/rig_build_traps.md.
|
||||
# Read that file before debugging a configure or link failure this script reports.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/CAD/build-gui.sh # configure + build the fork's GUI target
|
||||
# DRY_RUN=1 scripts/CAD/build-gui.sh # print the resolved fork identity and exit, no container
|
||||
set -euo pipefail
|
||||
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
# Fork identity is DERIVED from the repo, never hardcoded, so this file is byte-identical in
|
||||
# both forks and cannot be mirrored into the wrong one. Pointing a fork at the other fork's
|
||||
# image or volume is not a slow failure: with the wrong image CMake dies at configure, and with
|
||||
# the wrong volume the two forks silently trade build artefacts.
|
||||
PROJECT="$(sed -n 's/^project(\([A-Za-z_0-9]*\)).*/\1/p' "$REPO/CMakeLists.txt" | head -1)"
|
||||
case "$PROJECT" in
|
||||
Snapmaker_Orca) PREFIX=snapmaker; BIN=snapmaker-orca ;;
|
||||
OrcaSlicer) PREFIX=orcacad; BIN=orca-slicer ;;
|
||||
*) echo "FATAL: unrecognised project($PROJECT) in $REPO/CMakeLists.txt" >&2; exit 2 ;;
|
||||
esac
|
||||
TARGET="$PROJECT"
|
||||
IMAGE="${PREFIX}-deps"
|
||||
BUILD_VOL="${PREFIX}_buildcache"
|
||||
|
||||
echo "REPO=$REPO PROJECT=$PROJECT IMAGE=$IMAGE BUILD_VOL=$BUILD_VOL TARGET=$TARGET BIN=$BIN"
|
||||
|
||||
if [ -n "${DRY_RUN:-}" ]; then
|
||||
echo "DRY_RUN: resolution only, no container started"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Three memory bounds. On 2026-08-21 both forks ran this script at the same time, each with
|
||||
# ninja -j$(nproc)=16: ~36 cc1plus holding 42 GB of a 62 GB box -> global OOM at 21:05, a
|
||||
# 2h28m kill storm, ssh unreachable, lightdm destroyed, 2946 session kill events. Neither
|
||||
# build produced a single object. The bounds, weakest to strongest:
|
||||
# flock — the lock path is shared by both forks on purpose, so they SERIALISE instead of
|
||||
# summing. Peak is one build's worth no matter who else starts one.
|
||||
# -j12 — measured 1.17 GB average per cc1plus in the incident dump, so 12 in flight
|
||||
# is ~14 GB typical and leaves the box usable. JOBS=n overrides.
|
||||
# --memory — the actual guarantee. A runaway build hits its own cgroup limit and dies alone;
|
||||
# the host never reaches global OOM again, whatever -j or flock do.
|
||||
# --memory-swap equal to --memory forbids swap, which is what made ssh hang.
|
||||
JOBS="${JOBS:-12}"
|
||||
MEM="${MEM:-40g}"
|
||||
LOCK=/tmp/orca-rig-build.lock
|
||||
|
||||
exec 9>"$LOCK"
|
||||
if ! flock -n 9; then
|
||||
echo "another fork's build-gui holds $LOCK — waiting (this is the OOM guard, not a hang)"
|
||||
flock 9
|
||||
fi
|
||||
|
||||
# Every one of these mounts covers a trap, none is decorative:
|
||||
# CMakeLists.txt + cmake/ carry the SLIC3R_CAD gate — inherit the baked copies and the cache
|
||||
# says SLIC3R_CAD=ON while -DSLIC3R_CAD is never defined, so every #ifdef block compiles out.
|
||||
# deps_src/ carries pybind11, which the image predates.
|
||||
# src/, resources/, localization/, version.inc are the code under test.
|
||||
rc=0
|
||||
docker run --rm \
|
||||
--memory="$MEM" --memory-swap="$MEM" \
|
||||
-v "$REPO/src":/OrcaSlicer/src \
|
||||
-v "$REPO/resources":/OrcaSlicer/resources \
|
||||
-v "$REPO/cmake":/OrcaSlicer/cmake \
|
||||
-v "$REPO/deps_src":/OrcaSlicer/deps_src \
|
||||
-v "$REPO/localization":/OrcaSlicer/localization \
|
||||
-v "$REPO/CMakeLists.txt":/OrcaSlicer/CMakeLists.txt \
|
||||
-v "$REPO/version.inc":/OrcaSlicer/version.inc \
|
||||
-v "$BUILD_VOL":/OrcaSlicer/build \
|
||||
"$IMAGE" bash -lc "
|
||||
cd /OrcaSlicer/build || exit 1
|
||||
cmake . > /tmp/cfg.log 2>&1 || { echo 'CONFIGURE FAILED'; tail -25 /tmp/cfg.log; exit 1; }
|
||||
# Twice, deliberately. src/libslic3r/CMakeLists.txt publishes OCCT_LIBS as CACHE INTERNAL
|
||||
# at the END of its own configure, so a first pass after that list changes links the
|
||||
# PREVIOUS one and drops TKBool/TKOffset — a wall of TopOpeBRepBuild undefined references
|
||||
# that reads as a broken OCCT install and is not. Trap 4.
|
||||
cmake . > /tmp/cfg2.log 2>&1 || { echo 'RECONFIGURE FAILED'; tail -25 /tmp/cfg2.log; exit 1; }
|
||||
ninja -f build-Release.ninja -j$JOBS $TARGET > /tmp/bld.log 2>&1
|
||||
rc=\$?
|
||||
echo \"EXIT=\$rc\"
|
||||
grep -n 'error:' /tmp/bld.log | head -20
|
||||
tail -4 /tmp/bld.log
|
||||
ls -la /OrcaSlicer/build/src/Release/$BIN 2>/dev/null
|
||||
exit \$rc
|
||||
" || rc=$?
|
||||
|
||||
# A target-only build writes src/Release/, but this fork's start-headless-gui.sh may default BIN to the
|
||||
# PACKAGED path that only build_linux.sh refreshes — launching with the default would then run a
|
||||
# stale binary. Pass BIN explicitly. See scripts/CAD/rig_build_traps.md.
|
||||
echo "=== launch the rig on the binary just built ==="
|
||||
echo " docker exec -e BIN=/OrcaSlicer/build/src/Release/$BIN ${PREFIX}-gui /OrcaSlicer/scripts/CAD/start-headless-gui.sh"
|
||||
exit "$rc"
|
||||
|
|
@ -1,664 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""The click-edit contract: a value field that opens must accept what is TYPED into it.
|
||||
|
||||
WHY THIS EXISTS SEPARATELY FROM check-gui-sketching.py. That ladder draws geometry and grades the
|
||||
result, and to make its values land it calls focus_field() — one synthetic click INTO the field
|
||||
before typing. Its own docstring says why:
|
||||
|
||||
WITHOUT THIS THE TYPED VALUE IS SILENTLY DISCARDED. The field is shown and raised but the
|
||||
window manager does not give it the keyboard, so xdotool's digits go to the canvas and Return
|
||||
commits the value the field opened with — the pre-filled as-drawn number.
|
||||
|
||||
That click is a workaround for a defect, and a suite that performs it can never see the defect
|
||||
again. A user cannot be told to click the field first; when they do not, they get the as-drawn
|
||||
number and report "the label value is not editable". So this ladder types IMMEDIATELY after the
|
||||
field opens, exactly as a person does, and fails if the prefill is what gets committed.
|
||||
|
||||
WHAT IT GRADES. The app emits one line per event under ORCA_CAD_UXTRACE=1:
|
||||
|
||||
[UX] open title=Length prefill=154.76
|
||||
[UX] commit title=Length typed=80 value=80.0000
|
||||
[UX] refused title=Length typed=8O
|
||||
[UX] cancel title=Length
|
||||
|
||||
For every field the driver opens it asserts: a commit arrived, what the field received is what we
|
||||
typed, the parsed value equals it, and it differs from the prefill. The last clause is the one
|
||||
that matters — a field that is on screen but deaf commits its prefill, and every other signal
|
||||
(the field is visible, a constraint is created, the solve succeeds) looks perfectly healthy.
|
||||
|
||||
scripts/CAD/check-gui-click-edit.py --display :10 --bin build/src/Release/orca-slicer
|
||||
|
||||
With --attach it drives an already-running app instead of launching one; the app must have been
|
||||
started with ORCA_CAD_UXTRACE=1 and its stderr redirected to --trace.
|
||||
Exit 0 = every field took what was typed.
|
||||
"""
|
||||
import argparse, json, os, re, shutil, signal, socket, subprocess, sys, tempfile, time
|
||||
|
||||
AP = argparse.ArgumentParser()
|
||||
AP.add_argument("--display", default=os.environ.get("DISPLAY", ":10"))
|
||||
AP.add_argument("--bin", default="build/src/Release/orca-slicer")
|
||||
AP.add_argument("--datadir", default="")
|
||||
AP.add_argument("--trace", default="")
|
||||
AP.add_argument("--sock", default="/tmp/mcp-uxcheck.sock",
|
||||
help="the app's MCP socket: the oracle for whether a sketch is really open")
|
||||
AP.add_argument("--attach", action="store_true", help="drive a running app; do not launch one")
|
||||
AP.add_argument("--keep", action="store_true", help="leave the app running afterwards")
|
||||
AP.add_argument("--no-defocus", action="store_true",
|
||||
help="do NOT take focus off the field before typing (weakens the gate; see below)")
|
||||
AP.add_argument("--seed-from", default=os.path.expanduser("~/.config/OrcaCAD/OrcaSlicer.conf"),
|
||||
help="an existing OrcaSlicer.conf to copy presets/settings from")
|
||||
A = AP.parse_args()
|
||||
|
||||
DISP = A.display
|
||||
TRACE = A.trace or os.path.join(tempfile.gettempdir(), "ux-click-edit.log")
|
||||
_fail = 0
|
||||
_checks = 0
|
||||
|
||||
|
||||
_n = 0
|
||||
|
||||
|
||||
def call(method, **params):
|
||||
"""One MCP request over the app's unix socket. The socket is the only witness that cannot
|
||||
lie about sketch state: the keytrace says a key ARRIVED, a screenshot says something is on
|
||||
screen, and neither distinguishes an open sketch from sketch mode with the plane offer up."""
|
||||
global _n
|
||||
_n += 1
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(30)
|
||||
s.connect(A.sock)
|
||||
s.sendall((json.dumps({"jsonrpc": "2.0", "id": _n, "method": method,
|
||||
"params": params}) + "\n").encode())
|
||||
buf = b""
|
||||
while b"\n" not in buf:
|
||||
d = s.recv(65536)
|
||||
if not d:
|
||||
break
|
||||
buf += d
|
||||
r = json.loads(buf.decode().strip())
|
||||
if "error" in r:
|
||||
raise RuntimeError(f"{method}: {r['error']['message']}")
|
||||
return r["result"]
|
||||
|
||||
|
||||
def try_call(method, **params):
|
||||
try:
|
||||
return call(method, **params)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def sh(cmd):
|
||||
# bash -c, NOT -lc: a login shell sources the profile on every xdotool call, and this driver
|
||||
# makes hundreds. On a GNOME box that meant im-config running per call, thousands of journal
|
||||
# lines, and a window poll slow enough to time out before the app had finished starting.
|
||||
return subprocess.run(["bash", "-c", cmd], capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def xdo(args):
|
||||
sh(f"DISPLAY={DISP} xdotool {args}")
|
||||
|
||||
|
||||
def key(k, pause=0.35, window=None):
|
||||
xdo(f"key {'--window ' + str(window) + ' ' if window else ''}{k}")
|
||||
time.sleep(pause)
|
||||
|
||||
|
||||
def typ(s, pause=0.35, window=None):
|
||||
# --clearmodifiers so a modifier left down by an earlier synthetic key cannot turn digits
|
||||
# into something else; --delay 60 because ImGui reads one character per frame.
|
||||
#
|
||||
# `window` targets a specific window with XSendEvent instead of following the input focus.
|
||||
# That is the whole gate: see type_into_open_field.
|
||||
tgt = f"--window {window} " if window else ""
|
||||
xdo(f"type {tgt}--clearmodifiers --delay 60 -- '{s}'")
|
||||
time.sleep(pause)
|
||||
|
||||
|
||||
def die(msg):
|
||||
print(f"FATAL {msg}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the app
|
||||
|
||||
_proc = None
|
||||
|
||||
|
||||
def seed_datadir(datadir):
|
||||
"""The Design tab does not exist unless enable_cad_feature is on, and it needs a RESTART.
|
||||
|
||||
A fresh datadir has it off, so a driver that just points the app at an empty directory gets
|
||||
Prepare/Preview/Device/Project, no Design tab, and every rung fails for a reason that has
|
||||
nothing to do with what is being tested. Seed the flag before the first launch.
|
||||
"""
|
||||
os.makedirs(datadir, exist_ok=True)
|
||||
conf = os.path.join(datadir, "OrcaSlicer.conf")
|
||||
data = {}
|
||||
if os.path.exists(A.seed_from):
|
||||
try:
|
||||
with open(A.seed_from) as f:
|
||||
data = json.load(f)
|
||||
except Exception:
|
||||
data = {}
|
||||
app = data.setdefault("app", {})
|
||||
app["enable_cad_feature"] = True
|
||||
# Deterministic starting state for the rungs that follow: the bed drawn, loops welded as the
|
||||
# ~90% case expects. A ladder whose result depends on the developer's own preferences is not
|
||||
# a gate.
|
||||
app["auto_close_sketch_loops"] = True
|
||||
app["design_show_bed"] = True
|
||||
# SILENCE THE NETWORK PLUGIN PROMPT. Without this, GUI_App::post_init() re-raises "Bambu
|
||||
# Network Plug-in Required" from an IDLE event — after any modal sweep this driver does at
|
||||
# startup — and ShowModal() then runs a nested event loop. The app is alive, its window is
|
||||
# there, and the MCP socket answers nothing: indistinguishable from a hang, and it was
|
||||
# investigated as one, with gdb, twice. `installed_networking` false stops the whole
|
||||
# networking-plugin path, so m_networking_need_update is never set and the dialog never
|
||||
# exists to be swept.
|
||||
app["installed_networking"] = False
|
||||
with open(conf, "w") as f:
|
||||
json.dump(data, f, indent=1)
|
||||
for sub in ("user", "system", "presets", "vendor"):
|
||||
src = os.path.join(os.path.dirname(A.seed_from), sub)
|
||||
dst = os.path.join(datadir, sub)
|
||||
if os.path.isdir(src) and not os.path.exists(dst):
|
||||
shutil.copytree(src, dst)
|
||||
|
||||
|
||||
def launch():
|
||||
global _proc
|
||||
datadir = A.datadir or os.path.join(tempfile.gettempdir(), "orcacad-uxcheck")
|
||||
seed_datadir(datadir)
|
||||
env = dict(os.environ)
|
||||
# WAYLAND_DISPLAY MUST GO, and GDK_BACKEND must say x11. GTK prefers Wayland whenever
|
||||
# WAYLAND_DISPLAY is set and ignores DISPLAY entirely, so a driver launched from a systemd
|
||||
# user unit (which inherits it) started the app on the DESKTOP session instead of the rig:
|
||||
# the process was alive, `xdotool search` on the rig display found nothing, and the window
|
||||
# was sitting on the user's own screen. Silent, and it drives a stray app at someone's face.
|
||||
env.pop("WAYLAND_DISPLAY", None)
|
||||
env.update(DISPLAY=DISP, GDK_BACKEND="x11", ORCA_CAD_UXTRACE="1",
|
||||
LIBGL_ALWAYS_SOFTWARE="1", GALLIUM_DRIVER="llvmpipe",
|
||||
# The rig's Xvfb has no input-method daemon, and a dead ibus context makes a
|
||||
# GtkEntry drop every character while the app looks fine. It cannot affect the
|
||||
# in-canvas field (ImGui needs no IM) but the app has other text fields, and a
|
||||
# display full of IBUS warnings has cost a whole misdiagnosis before.
|
||||
GTK_IM_MODULE="gtk-im-context-simple", XMODIFIERS="@im=none",
|
||||
# The key tracer is this driver's only positive signal that a keystroke reached
|
||||
# the Design panel at all. Without it "the field never opened" is indistinguishable
|
||||
# from "we never got into sketch mode", and the first run of this ladder reported
|
||||
# seven product failures that were really one driver racing a still-loading app.
|
||||
ORCA_CAD_KEYTRACE="1", ORCA_CAD_MCP=A.sock,
|
||||
SSL_CERT_FILE="/etc/ssl/certs/ca-certificates.crt",
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER="1", WEBKIT_DISABLE_COMPOSITING_MODE="1")
|
||||
if os.path.exists(A.sock):
|
||||
os.unlink(A.sock) # a stale socket from a dead run answers nothing, slowly
|
||||
log = open(TRACE, "wb")
|
||||
_proc = subprocess.Popen([A.bin, "--datadir", datadir], env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=log)
|
||||
for _ in range(120):
|
||||
if win_id():
|
||||
return
|
||||
time.sleep(1)
|
||||
die("the app never showed a window on " + DISP)
|
||||
|
||||
|
||||
def window_pid(w):
|
||||
"""_NET_WM_PID for a window, or 0. The property is how we tell a live app from its ghost."""
|
||||
out = sh(f"DISPLAY={DISP} xprop -id {w} _NET_WM_PID 2>/dev/null")
|
||||
m = re.search(r"= *(\d+)", out)
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def pid_alive(pid):
|
||||
return pid > 0 and os.path.isdir(f"/proc/{pid}")
|
||||
|
||||
|
||||
def win_id():
|
||||
"""The main window: OURS if we launched it, otherwise the biggest LIVE top-level.
|
||||
|
||||
Two rules here, each paid for.
|
||||
|
||||
By PID, not by size, whenever we launched the app. An X window outlives its client if the
|
||||
connection is not torn down cleanly, and a killed OrcaSlicer can leave a full-screen ghost
|
||||
mapped on the display. It answers geometry queries exactly like the real thing, it wins "the
|
||||
biggest window" every time, and every synthetic keystroke sent to it goes nowhere. That is
|
||||
indistinguishable, from the driver's side, from an app that ignores the keyboard — which is
|
||||
the very defect this ladder exists to measure. One run reported the entire contract broken
|
||||
while the real app sat beside the ghost, untouched.
|
||||
|
||||
Never by title: a saved project renames the main window.
|
||||
"""
|
||||
if _proc is not None:
|
||||
for w in sh(f"DISPLAY={DISP} xdotool search --pid {_proc.pid} --onlyvisible --name '.'").split():
|
||||
g = dict(l.split("=", 1) for l in
|
||||
sh(f"DISPLAY={DISP} xdotool getwindowgeometry --shell {w}").strip().splitlines()
|
||||
if "=" in l)
|
||||
if "WIDTH" in g and int(g["WIDTH"]) * int(g["HEIGHT"]) > 400 * 400:
|
||||
return (w, int(g["X"]), int(g["Y"]), int(g["WIDTH"]), int(g["HEIGHT"]))
|
||||
return None
|
||||
best = None
|
||||
for w in sh(f"DISPLAY={DISP} xdotool search --onlyvisible --name '.'").split():
|
||||
g = dict(l.split("=", 1) for l in
|
||||
sh(f"DISPLAY={DISP} xdotool getwindowgeometry --shell {w}").strip().splitlines()
|
||||
if "=" in l)
|
||||
if "WIDTH" not in g:
|
||||
continue
|
||||
if not pid_alive(window_pid(w)): # a ghost: no client is behind it any more
|
||||
continue
|
||||
a = int(g["WIDTH"]) * int(g["HEIGHT"])
|
||||
if a > 400 * 400 and (best is None or a > best[0]):
|
||||
best = (a, w, int(g["X"]), int(g["Y"]), int(g["WIDTH"]), int(g["HEIGHT"]))
|
||||
return best[1:] if best else None
|
||||
|
||||
|
||||
_win = None
|
||||
|
||||
|
||||
def win():
|
||||
global _win
|
||||
if _win is None:
|
||||
w = win_id()
|
||||
if w is None:
|
||||
die("no app window on " + DISP)
|
||||
sh(f"DISPLAY={DISP} xdotool windowactivate --sync {w[0]}")
|
||||
sh(f"DISPLAY={DISP} xdotool windowsize {w[0]} 1920 1080")
|
||||
sh(f"DISPLAY={DISP} xdotool windowmove {w[0]} 0 0")
|
||||
time.sleep(1.0)
|
||||
_win = (w[0], 0, 0, 1920, 1080)
|
||||
return _win
|
||||
|
||||
|
||||
def click(px, py, pause=0.5, btn=1):
|
||||
_, X, Y, _, _ = win()
|
||||
xdo(f"mousemove {X+int(px)} {Y+int(py)} click --delay 120 {btn}")
|
||||
time.sleep(pause)
|
||||
|
||||
|
||||
def visible_windows():
|
||||
"""(id, name, w, h) for every MAPPED top-level, main window included.
|
||||
|
||||
`--onlyvisible` is what makes this usable. Without it xdotool also returns the app's unmapped
|
||||
helper windows — a 10x10 and a 200x200 that exist for the whole session — and a caller that
|
||||
tries to reason about "extra windows" from that list is reasoning about furniture.
|
||||
"""
|
||||
out = []
|
||||
for w in sh(f"DISPLAY={DISP} xdotool search --onlyvisible --name '.'").split():
|
||||
g = dict(l.split("=", 1) for l in
|
||||
sh(f"DISPLAY={DISP} xdotool getwindowgeometry --shell {w}").strip().splitlines()
|
||||
if "=" in l)
|
||||
if "WIDTH" not in g:
|
||||
continue
|
||||
if not pid_alive(window_pid(w)): # see win_id(): a ghost cannot be closed, only ignored
|
||||
continue
|
||||
n = sh(f"DISPLAY={DISP} xdotool getwindowname {w}").strip()
|
||||
out.append((w, n, int(g["WIDTH"]), int(g["HEIGHT"])))
|
||||
return out
|
||||
|
||||
|
||||
def dismiss_modals(timeout=30):
|
||||
"""Close every modal over the main window, and PROVE none is left.
|
||||
|
||||
This is the rung that decides whether any of the others mean anything. A fresh datadir opens
|
||||
"Bambu Network Plug-in Required" — 440x259, centred at 742,450 — which sits exactly on top of
|
||||
the point every drawing gesture in TOOLS starts from. The whole ladder then reports eleven
|
||||
product failures, all of them the driver clicking a dialog.
|
||||
|
||||
The old version pressed Escape and moved on. This dialog ignores Escape, so it "dismissed"
|
||||
nothing and said so to no one; the run that found this was red for a reason that had nothing
|
||||
to do with the contract under test. Escape is still tried first because it is the gentlest
|
||||
thing that works on the wizard, then WM_DELETE_WINDOW, and then the function asserts what it
|
||||
was supposed to have achieved instead of assuming it.
|
||||
"""
|
||||
# NEVER run without knowing which window to spare. The first version took `keep = main[0] if
|
||||
# main else None`, so a win_id() that raced the app's mapping made keep None and every visible
|
||||
# window a modal — this function then sent WM_DELETE to the app's own main window. The app
|
||||
# survived as a process, printed "GdkWindow unexpectedly destroyed", and answered nothing
|
||||
# afterwards; the ladder reported "no sketch opened" for 180s. Losing the main window is not a
|
||||
# state to recover from silently.
|
||||
deadline = time.time() + timeout
|
||||
keep = None
|
||||
while keep is None and time.time() < deadline:
|
||||
main = win_id()
|
||||
keep = main[0] if main else None
|
||||
if keep is None:
|
||||
time.sleep(0.5)
|
||||
if keep is None:
|
||||
die(f"no main window to protect after {timeout}s — refusing to close anything")
|
||||
scr = sh(f"DISPLAY={DISP} xdotool getdisplaygeometry").split()
|
||||
full = int(scr[0]) * int(scr[1]) if len(scr) == 2 else 1920 * 1080
|
||||
while time.time() < deadline:
|
||||
# A modal is small. Anything covering half the screen is the app, whatever id win_id()
|
||||
# happened to return this instant — a second belt on the rule above, because the cost of
|
||||
# being wrong here is an app that looks alive and answers nothing.
|
||||
extra = [x for x in visible_windows() if x[0] != keep and x[2] * x[3] < full * 0.5]
|
||||
if not extra:
|
||||
return
|
||||
for (w, n, _, _) in extra:
|
||||
sh(f"DISPLAY={DISP} xdotool windowactivate {w}")
|
||||
time.sleep(0.4)
|
||||
key("Escape", 0.4)
|
||||
if any(x[0] == w for x in visible_windows()):
|
||||
sh(f"DISPLAY={DISP} xdotool windowclose {w}")
|
||||
time.sleep(0.6)
|
||||
time.sleep(0.5)
|
||||
left = [f"{n!r} ({w}x{h})" for (i, n, w, h) in visible_windows()
|
||||
if i != keep and w * h < full * 0.5]
|
||||
die("a modal is still covering the canvas after " + str(timeout) + "s: " + ", ".join(left) +
|
||||
" — every drawing gesture would land in it, so nothing below this line could be trusted")
|
||||
|
||||
|
||||
def dismiss_first_run():
|
||||
dismiss_modals()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the trace
|
||||
|
||||
def trace_lines():
|
||||
try:
|
||||
with open(TRACE, "r", errors="replace") as f:
|
||||
return [l.strip() for l in f if l.startswith("[UX] ")]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def trace_mark():
|
||||
return len(trace_lines())
|
||||
|
||||
|
||||
def parse(line):
|
||||
m = re.match(r"\[UX\] (\w+) title=(.*?) (.*)$", line)
|
||||
if not m:
|
||||
return None
|
||||
ev, title, rest = m.group(1), m.group(2), m.group(3)
|
||||
kv = dict(re.findall(r"(\w+)=(\S*)", rest))
|
||||
return ev, title, kv
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- grading
|
||||
|
||||
def check(cond, what):
|
||||
"""Returns the verdict so a caller can abandon a rung whose precondition failed."""
|
||||
global _fail, _checks
|
||||
_checks += 1
|
||||
if cond:
|
||||
print(f" ok {what}")
|
||||
else:
|
||||
print(f" FAIL {what}", file=sys.stderr)
|
||||
_fail += 1
|
||||
return bool(cond)
|
||||
|
||||
|
||||
def type_into_open_field(value, mark):
|
||||
"""Type `value` into whatever field is open, WITHOUT clicking it first, and grade the pair.
|
||||
|
||||
No click: the click is the workaround this ladder exists to refuse. If the field cannot take
|
||||
the keyboard on its own, `typed` will be the prefill and this fails — which is the report.
|
||||
"""
|
||||
# POLL for the field. It opens from a CallAfter that runs after a re-solve, so on llvmpipe it
|
||||
# is simply not there yet when a fast driver looks — and "no field opened" is the same message
|
||||
# whether the product never opened one or the driver asked too early. Wait, then decide.
|
||||
opens = []
|
||||
deadline = time.time() + 8.0
|
||||
while time.time() < deadline:
|
||||
opens = [e for e in (parse(l) for l in trace_lines()[mark:]) if e and e[0] == "open"]
|
||||
if opens:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
if not opens:
|
||||
check(False, f"a value field opened (nothing did; cannot type {value})")
|
||||
return mark
|
||||
title = opens[-1][1]
|
||||
prefill = opens[-1][2].get("prefill", "")
|
||||
m2 = trace_mark()
|
||||
# TYPE NORMALLY. NOTHING TO DEFOCUS ANY MORE.
|
||||
#
|
||||
# The value field is drawn INSIDE the GL canvas by ImGui, so it is not a window: there is no
|
||||
# second toplevel for a window manager to grant or refuse the keyboard, and the keystrokes go
|
||||
# to the app's one window exactly as a person's would. That is the entire point of the design
|
||||
# — the WM has no say — and it is why this ladder no longer tries to manufacture the failing
|
||||
# condition.
|
||||
#
|
||||
# When the field WAS a floating wxFrame, this spot held two attempts to reproduce
|
||||
# "field open, keyboard elsewhere", and both are recorded here so neither is tried again:
|
||||
# - XSetInputFocus onto the main window (`xdotool windowfocus`): the field's own re-focus
|
||||
# CallAfter wins the race every time; four retries all lost, and the ladder passed twice
|
||||
# against a binary with the fix compiled out.
|
||||
# - XSendEvent at the main window (`xdotool type --window`): GTK discards synthetic key
|
||||
# events, so NEITHER build received anything and every run was red regardless of the code.
|
||||
# A run that used the second of those is what produced "the app never saw a digit" — a
|
||||
# property of xdotool, not of the product.
|
||||
#
|
||||
# For the in-canvas field the honest gate is simply: type, and see whether the value the app
|
||||
# commits is the value that was typed.
|
||||
diag = sh(f"DISPLAY={DISP} xdotool getwindowfocus").strip()
|
||||
typ(str(value), 0.4)
|
||||
key("Return", 0.9)
|
||||
after, commits, refused, commit_at = [], [], [], None
|
||||
deadline = time.time() + 5.0
|
||||
while time.time() < deadline:
|
||||
after = [parse(l) for l in trace_lines()[m2:]]
|
||||
commits = [(i, e) for i, e in enumerate(after) if e and e[0] == "commit"]
|
||||
refused = [e for e in after if e and e[0] == "refused"]
|
||||
if commits:
|
||||
commit_at = m2 + commits[-1][0]
|
||||
commits = [e for _, e in commits]
|
||||
if commits or refused:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
if refused and not commits:
|
||||
check(False, f"{title}: field REFUSED {value!r} (typed={refused[-1][2].get('typed')!r})")
|
||||
key("Escape", 0.5)
|
||||
return trace_mark()
|
||||
if not commits:
|
||||
check(False, f"{title}: typed {value} but nothing committed — the field took no keys")
|
||||
key("Escape", 0.5)
|
||||
return trace_mark()
|
||||
typed = commits[-1][2].get("typed", "")
|
||||
got = commits[-1][2].get("value", "")
|
||||
check(typed == str(value),
|
||||
f"{title}: field received what was typed (typed={typed!r} wanted={value!r}"
|
||||
f"{' <-- it committed its PREFILL, so it never got the keyboard' if typed == prefill else ''})")
|
||||
# A value that will not parse is a FAILED CHECK, never an exception. An unguarded float()
|
||||
# here met a locale-formatted "61,0000" and took the whole run down immediately after the
|
||||
# first check in the ladder's history had passed — the seven rungs below it were never tried
|
||||
# and the report read as a total failure.
|
||||
try:
|
||||
ok_val = abs(float(got) - float(value)) < 1e-6
|
||||
except (TypeError, ValueError):
|
||||
ok_val = False
|
||||
check(ok_val, f"{title}: committed value is {got!r} (wanted {value})")
|
||||
check(str(value) != prefill, f"{title}: the test value differs from the prefill {prefill!r}")
|
||||
# RESUME JUST AFTER THE COMMIT, not at the end of the trace. A queued chain opens its next
|
||||
# field from the commit callback, so by the time trace_mark() is read here that "open" line
|
||||
# is already written — and the next call, searching only after this mark, never sees it. The
|
||||
# rectangle's Height, the slot's Radius and the label reopen all failed as "nothing did"
|
||||
# while the trace plainly showed the field open and waiting.
|
||||
return (commit_at + 1) if commit_at is not None else trace_mark()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the ladder
|
||||
|
||||
def enter_sketch(timeout=180):
|
||||
"""Open a real sketch on a real plane, and PROVE it with the socket before drawing anything.
|
||||
|
||||
THE SEQUENCE MATTERS AND IT IS NOT OBVIOUS. The reference planes are hidden until Shift+S,
|
||||
with nothing picked, brings them up to choose from, so the plane is clicked AFTER it. That
|
||||
click opens the session on the plane and pops the tool offer, and a click outside a popup
|
||||
menu only closes it, so the spot is clicked twice, apart: the second click closes the offer,
|
||||
and inside the session it is empty canvas. No Escape — with no offer up, Escape in an empty
|
||||
sketch leaves it. Then a tool letter arms the tool. check-gui-sketching.py does the same
|
||||
steps. This ladder once did two of them — Design tab, then Shift+S — and went straight to
|
||||
the tool letters.
|
||||
|
||||
That intermediate state is the trap. `is_sketching` reads 1, every tool key is accepted and
|
||||
traced, and not one click draws anything, because there is no plane under them. The ladder
|
||||
then reports eleven product failures, all of them "a value field opened (nothing did)", and
|
||||
every one is the driver's. Two whole runs were spent on it.
|
||||
|
||||
So the gate is the ORACLE, not the keytrace: sketch_describe answers only when a sketch is
|
||||
genuinely open. Waiting on a mode flag is what allowed the wrong state to pass for the right
|
||||
one in the first place.
|
||||
"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
click(132, 53) # Design tab
|
||||
time.sleep(2.0)
|
||||
dismiss_modals()
|
||||
key("shift+s", 1.0) # nothing picked: the reference planes come up
|
||||
click(*PLANE_PX, pause=0.8) # picks the plane IN THE VIEWPORT: session open, offer up...
|
||||
click(*PLANE_PX) # ...and this closes the offer
|
||||
key("p", 0.6) # arms Point in the session
|
||||
if try_call("sketch_describe") is not None:
|
||||
# NO Escape here. Every rung already opens with one to drop whatever tool the last
|
||||
# one left armed, and Escape in the Design tab walks a LIFO: first press drops the
|
||||
# armed tool, second LEAVES THE SKETCH. Pressing it here made that second press the
|
||||
# rung's own, so the ladder exited the sketch before drawing anything and then
|
||||
# reported all eleven checks failed with "nothing opened" — the tools were arming
|
||||
# into an empty Feature-mode document.
|
||||
return
|
||||
die("no sketch opened after Shift+S + plane click within "
|
||||
f"{timeout}s — sketch_describe never answered on {A.sock} (trace {TRACE})")
|
||||
|
||||
|
||||
# tool key, the clicks that draw it, and one distinct value per queued field. The values are
|
||||
# deliberately nothing like the as-drawn size, so a committed prefill cannot coincide with them.
|
||||
# Where the plane label sits in the viewport once Shift+S has brought the planes up. Same
|
||||
# constant the gesture ladder uses; it is a label on the 3D view, not a widget, so it moves only
|
||||
# if the camera does.
|
||||
PLANE_PX = (913, 359)
|
||||
|
||||
# Every coordinate below stays inside 1000..1400 x 500..760 — the box check-gui-sketching.py's
|
||||
# calibration probes land four Points in, i.e. the region PROVEN to be live canvas on a 1920x1080
|
||||
# window. Earlier values started at x=950, which is left of that box and also, on a fresh datadir,
|
||||
# underneath the "Bambu Network Plug-in Required" modal.
|
||||
TOOLS = [
|
||||
("L", "Line", [(1030, 540), (1360, 540)], [61]),
|
||||
("R", "Rectangle", [(1030, 540), (1360, 730)], [62, 43]),
|
||||
("C", "Circle", [(1180, 620), (1330, 620)], [64]),
|
||||
("S", "Slot", [(1030, 580), (1300, 580), (1300, 640)], [66]),
|
||||
("G", "Polygon", [(1180, 620), (1320, 620)], [67]),
|
||||
("E", "Ellipse", [(1180, 620), (1370, 620), (1180, 720)], [68]),
|
||||
("A", "Arc", [(1040, 660), (1340, 660), (1190, 560)], [69]),
|
||||
]
|
||||
|
||||
|
||||
def rung_tool(k, name, clicks, values):
|
||||
print(f" {name}")
|
||||
key("Escape", 0.6) # back to Select, whatever the last tool left armed
|
||||
# Every rung re-establishes that a sketch is STILL open. One stray Escape too many leaves it,
|
||||
# and from then on every tool arms into a Feature-mode document that cannot open a value
|
||||
# field — which the checks below report as eleven independent product failures.
|
||||
if try_call("sketch_describe") is None:
|
||||
die(f"{name}: the sketch is no longer open before this rung — an earlier rung left it")
|
||||
key(k, 0.8)
|
||||
# MARK BEFORE THE CLICKS, not after. The field is opened from a CallAfter scheduled by the
|
||||
# render that follows the last click, so it can already be open by the time a mark taken
|
||||
# afterwards is read — and type_into_open_field, which only looks at events AFTER its mark,
|
||||
# then finds none and reports "a value field opened (nothing did)" for a field that is on
|
||||
# screen, open, and waiting. That message accused the product of the exact defect the ladder
|
||||
# exists to detect, from a bug in the ladder's own bookkeeping.
|
||||
mark = trace_mark()
|
||||
for (x, y) in clicks:
|
||||
click(x, y)
|
||||
for v in values:
|
||||
mark = type_into_open_field(v, mark)
|
||||
|
||||
|
||||
def rung_rounded_rect():
|
||||
"""The shape the user actually reported: a ROUNDED rectangle, Width -> Height -> Radius.
|
||||
|
||||
It has no keyboard shortcut — the rectangle family binds R to CornerRect and leaves the other
|
||||
modes in the toolbar flyout — so TOOLS above cannot reach it and the whole three-step chain
|
||||
went untested. `run_verb` arms it the way the offer menu does.
|
||||
|
||||
NOTE the id: the OFFER verb is `sk_rect_rounded`; `design_rect_rounded` is the ACTION name and
|
||||
run_verb throws on it, leaving the tool as Select. A run that misses that draws nothing and
|
||||
still reaches its assertions, so arm-and-verify rather than arm-and-hope.
|
||||
"""
|
||||
print(" Rounded rectangle")
|
||||
key("Escape", 0.6)
|
||||
tool = None
|
||||
for _ in range(8):
|
||||
try_call("run_verb", verb="sk_rect_rounded")
|
||||
time.sleep(0.8)
|
||||
tool = (try_call("sketch_describe") or {}).get("tool")
|
||||
if tool == "rect_rounded":
|
||||
break
|
||||
if not check(tool == "rect_rounded", f"the rounded-rectangle tool armed (tool={tool!r})"):
|
||||
return
|
||||
mark = trace_mark()
|
||||
click(1030, 540); click(1330, 700); click(1300, 660) # corners, then the radius point
|
||||
for v in (63, 41, 7):
|
||||
mark = type_into_open_field(v, mark)
|
||||
|
||||
|
||||
def rung_label_click():
|
||||
"""The user's own report: click an existing dimension label and type a new value into it.
|
||||
|
||||
KEEP THE SHAPE AS DRAWN. An earlier version committed 55 and 47 into the queued chain first,
|
||||
which resized the rectangle — and then clicked the pixel where the label had been before the
|
||||
resize. It missed, every time, and reported the reopen broken. The shape's on-screen position
|
||||
is only predictable if nothing has moved it, so Escape the chain instead: the rectangle stays
|
||||
exactly between the two corners we clicked.
|
||||
|
||||
FIND THE LABEL, do not assume its offset. A dimension label is drawn beside its edge at an
|
||||
offset that depends on zoom and text metrics, so a single hardcoded pixel is a guess that
|
||||
silently becomes wrong. Walk a short band across the top edge instead and stop at the first
|
||||
click that opens a field; if none of them does, that is a real failure and it says so.
|
||||
"""
|
||||
print(" label click-to-edit")
|
||||
key("Escape", 0.6) # Select mode
|
||||
key("R", 0.8)
|
||||
click(1020, 530)
|
||||
click(1350, 740)
|
||||
time.sleep(1.5)
|
||||
key("Escape", 0.8) # keep as drawn: abandon the queued value chain
|
||||
time.sleep(0.8)
|
||||
key("Escape", 0.6) # back to Select so a click picks rather than draws
|
||||
|
||||
mid_x, top_y = (1020 + 1350) // 2, 530
|
||||
candidates = [(mid_x, top_y + dy) for dy in (-26, -20, -14, -8, 0, 8, 14)]
|
||||
for (cx, cy) in candidates:
|
||||
mark = trace_mark()
|
||||
click(cx, cy)
|
||||
deadline = time.time() + 2.0
|
||||
while time.time() < deadline:
|
||||
if [e for e in (parse(l) for l in trace_lines()[mark:]) if e and e[0] == "open"]:
|
||||
check(True, f"clicking a dimension label reopened its value field (at {cx},{cy})")
|
||||
type_into_open_field(71, mark)
|
||||
return
|
||||
time.sleep(0.2)
|
||||
check(False, "clicking a dimension label reopened its value field "
|
||||
f"(tried {len(candidates)} points across the top edge at x={mid_x})")
|
||||
|
||||
|
||||
def main():
|
||||
if not A.attach:
|
||||
if not os.path.exists(A.bin):
|
||||
die(f"no binary at {A.bin}")
|
||||
open(TRACE, "w").close()
|
||||
launch()
|
||||
dismiss_first_run()
|
||||
win()
|
||||
print(f"click-edit ladder on {DISP}, trace {TRACE}")
|
||||
enter_sketch()
|
||||
for (k, name, clicks, values) in TOOLS:
|
||||
rung_tool(k, name, clicks, values)
|
||||
rung_rounded_rect()
|
||||
rung_label_click()
|
||||
print()
|
||||
if _fail:
|
||||
print(f"CLICK-EDIT LADDER FAILED — {_fail} of {_checks} checks", file=sys.stderr)
|
||||
else:
|
||||
print(f"CLICK-EDIT LADDER HELD — {_checks} checks")
|
||||
if _proc is not None and not A.keep:
|
||||
_proc.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
_proc.wait(20)
|
||||
except subprocess.TimeoutExpired:
|
||||
_proc.kill()
|
||||
return 1 if _fail else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,42 +1,35 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Autonomous 2D-sketch loop: drive the Design tab's sketch layer over the MCP socket and
|
||||
"""Autonomous 2D-sketch loop: drive the Design tab's sketch layer through the app's MCP server and
|
||||
assert the things that decide whether a profile is buildable.
|
||||
|
||||
WHY THIS EXISTS. The 2D layer used to be reachable only by clicking, so every question about it
|
||||
("is this loop closed?", "did the offset survive?", "is the circle a void or a second body?")
|
||||
cost a GUI session and a human. The socket verbs make each one a call, and this script is the
|
||||
loop: build a known profile, ask the app what it thinks it has, compare against arithmetic.
|
||||
WHY THIS EXISTS. Every question about the 2D layer ("is this loop closed?", "did the offset
|
||||
survive?", "is the circle a void or a second body?"), asked by clicking, costs a GUI session and a
|
||||
human. The Design commands make each one a call, and this script is the loop: build a known profile, ask
|
||||
the app what it thinks it has, compare against arithmetic.
|
||||
|
||||
RUN IT AGAINST A RUNNING APP:
|
||||
ORCA_CAD_MCP=/tmp/mcp.sock <binary> # launch with the socket enabled
|
||||
python3 scripts/CAD/check-mcp-sketch.py [socket] # default /tmp/mcp.sock
|
||||
RUN IT AGAINST A RUNNING APP started with --mcp and the CAD feature on, for example:
|
||||
python3 tools/mcp/orca_mcp.py launch --cad --datadir <datadir>
|
||||
python3 scripts/CAD/check-mcp-sketch.py [datadir]
|
||||
|
||||
datadir is the running app's data directory (default: $ORCA_DATADIR, else the platform's own); the
|
||||
script finds the app's MCP server through the port it writes to <datadir>/mcp/server.json.
|
||||
|
||||
Exit 0 = every assertion held. Anything else prints the first mismatch and stops.
|
||||
"""
|
||||
import json, math, socket, sys
|
||||
import math, os, sys
|
||||
|
||||
SOCK = sys.argv[1] if len(sys.argv) > 1 else "/tmp/mcp.sock"
|
||||
_n = 0
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tools", "mcp"))
|
||||
import orca_mcp # noqa: E402
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
|
||||
print(__doc__)
|
||||
sys.exit(0)
|
||||
DATADIR = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("ORCA_DATADIR", "")
|
||||
APP = orca_mcp.OrcaMcp.from_datadir(DATADIR)
|
||||
|
||||
|
||||
def call(method, **params):
|
||||
global _n
|
||||
_n += 1
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(30)
|
||||
s.connect(SOCK)
|
||||
s.sendall((json.dumps({"jsonrpc": "2.0", "id": _n, "method": method,
|
||||
"params": params}) + "\n").encode())
|
||||
buf = b""
|
||||
while b"\n" not in buf:
|
||||
d = s.recv(65536)
|
||||
if not d:
|
||||
break
|
||||
buf += d
|
||||
r = json.loads(buf.decode().strip())
|
||||
if "error" in r:
|
||||
raise RuntimeError(f"{method}: {r['error']}")
|
||||
return r["result"]
|
||||
return APP.call_command(method, **params)["result"]
|
||||
|
||||
|
||||
def near(a, b, tol=1e-6):
|
||||
|
|
@ -59,14 +52,14 @@ try:
|
|||
call("sketch_cancel")
|
||||
except Exception:
|
||||
pass
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", rect=[0, 0, 80, 50])
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", type="rectangle_2_point", p0=[0, 0], p1=[80, 50])
|
||||
r = call("sketch_describe")
|
||||
check(r["buildable"], "buildable")
|
||||
check(areas(r) == [4000.0], f"one loop of 4000 mm^2 (got {areas(r)})")
|
||||
|
||||
print("2. a circle inside it is a VOID, not a second profile")
|
||||
call("sketch_add", type="circle", center=[40, 25], radius=10)
|
||||
call("sketch_draw", type="circle_center", center=[40, 25], radius=10)
|
||||
r = call("sketch_describe")
|
||||
outer = [l for l in r["closed_loops"] if near(l["area"], 4000.0)][0]
|
||||
check(len(outer["holes"]) == 1, "the rectangle encloses exactly one void")
|
||||
|
|
@ -83,8 +76,8 @@ check(any(near(l["area"], 70 * 40) for l in r["closed_loops"]),
|
|||
|
||||
print("4. a gap is REPORTED with its coordinates, then healed into a constraint")
|
||||
call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", entities=[
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", entities=[
|
||||
{"type": "line", "p0": [0, 0], "p1": [60, 0]},
|
||||
{"type": "line", "p0": [60, 0], "p1": [60, 40]},
|
||||
{"type": "line", "p0": [60, 40], "p1": [0, 40]},
|
||||
|
|
@ -94,7 +87,7 @@ r = call("sketch_validate", tolerance=1.0)
|
|||
check(not r["buildable"], "a 0.4 mm gap makes the profile unbuildable")
|
||||
check(len(r["open_ends"]) == 2, f"both free ends are named (got {r['open_ends']})")
|
||||
dof_before = r["dof"]
|
||||
r = call("sketch_heal", tolerance=1.0)
|
||||
r = call("sketch_repair", tolerance=1.0)
|
||||
check(r["welded"] == 1, f"one pair welded (got {r['welded']})")
|
||||
check(r["buildable"] and r["open_ends"] == [], "healed profile is buildable")
|
||||
check(areas(r) == [2400.0], f"healed loop is 60x40 (got {areas(r)})")
|
||||
|
|
@ -103,17 +96,17 @@ check(r["dof"] < dof_before,
|
|||
|
||||
print("5. construction geometry is excluded from the profile")
|
||||
call("sketch_select", entities=[0])
|
||||
call("sketch_construction")
|
||||
call("sketch_toggle_construction", silent=True)
|
||||
r = call("sketch_describe")
|
||||
check(not r["buildable"], "turning one side into a guide opens the profile again")
|
||||
call("sketch_construction")
|
||||
call("sketch_toggle_construction", silent=True)
|
||||
r = call("sketch_describe")
|
||||
check(r["buildable"], "turning it back closes it again")
|
||||
|
||||
print("6. re-dimensioning one side keeps the rectangle a single closed loop")
|
||||
call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", rect=[0, 0, 60, 40])
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", type="rectangle_2_point", p0=[0, 0], p1=[60, 40])
|
||||
r = call("sketch_describe")
|
||||
check(areas(r) == [2400.0], f"one loop of 2400 mm^2 (got {areas(r)})")
|
||||
call("sketch_select", entities=[0]) # the bottom edge, y=0, from x=0 to x=60
|
||||
|
|
|
|||
|
|
@ -20,30 +20,37 @@ agree, and that the engine's own operations preserve what they promise.
|
|||
MIRROR a real closed profile, mirrored, is still exactly one closed loop
|
||||
OFFSET a real closed profile, offset, is still closed
|
||||
|
||||
Usage: check-sketch-engine-corpus.py [--sample N] [--corpus DIR]
|
||||
Run it against a running app started with --mcp and the CAD feature on, for example:
|
||||
|
||||
python3 tools/mcp/orca_mcp.py launch --cad --datadir <datadir>
|
||||
python3 scripts/CAD/check-sketch-engine-corpus.py --corpus DIR [--datadir <datadir>]
|
||||
[--step N] [--limit N] [--scale] [--budget S]
|
||||
|
||||
DIR is the folder of the StudyCadCam MPD*.pdf sheets. --datadir is the running app's data directory
|
||||
(default: $ORCA_DATADIR, else the platform's own); the script finds the app's MCP server through the
|
||||
port it writes to <datadir>/mcp/server.json. The sheets are read with poppler's pdftocairo and
|
||||
pdfinfo, which must be on the PATH.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
SOCK = os.environ.get("ORCA_CAD_MCP", "/tmp/mcp.sock")
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tools", "mcp"))
|
||||
import orca_mcp # noqa: E402
|
||||
|
||||
APP = None # the running app's MCP server, attached to in main()
|
||||
TOL = 1e-6 # exact-comparison tolerance (all inputs are lines)
|
||||
WELD = 0.05 # endpoint-coincidence tolerance, in PDF units
|
||||
|
||||
|
||||
# ── the socket ───────────────────────────────────────────────────────────────
|
||||
_id = [0]
|
||||
|
||||
|
||||
# ── the app's MCP server ─────────────────────────────────────────────────────
|
||||
def try_call(method, **params):
|
||||
"""sketch_cancel throws when nothing is open, which is not an error to us."""
|
||||
try:
|
||||
|
|
@ -53,24 +60,7 @@ def try_call(method, **params):
|
|||
|
||||
|
||||
def call(method, **params):
|
||||
_id[0] += 1
|
||||
req = json.dumps({"jsonrpc": "2.0", "id": _id[0], "method": method,
|
||||
"params": params}) + "\n"
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(30)
|
||||
s.connect(SOCK)
|
||||
s.sendall(req.encode())
|
||||
buf = b""
|
||||
while not buf.endswith(b"\n"):
|
||||
chunk = s.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
s.close()
|
||||
r = json.loads(buf.decode())
|
||||
if "error" in r:
|
||||
raise RuntimeError(r["error"]["message"])
|
||||
return r["result"]
|
||||
return APP.call_command(method, **params)["result"]
|
||||
|
||||
|
||||
# ── SVG → line segments ──────────────────────────────────────────────────────
|
||||
|
|
@ -262,8 +252,8 @@ def grade(pdf, name, report):
|
|||
"p0": [ring[i][0], ring[i][1]],
|
||||
"p1": [ring[i + 1][0], ring[i + 1][1]]})
|
||||
try_call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", entities=ents)
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", entities=ents)
|
||||
r = call("sketch_describe")
|
||||
|
||||
ok = True
|
||||
|
|
@ -275,27 +265,26 @@ def grade(pdf, name, report):
|
|||
mine = sorted(shoelace(x) for x in rings)
|
||||
theirs = sorted(abs(l["area"]) for l in got)
|
||||
# The bar: 1e-3 absolute, or 1e-6 relative for the big loops. Not bit-exactness — the
|
||||
# auto-constraint pass still snaps segments that are already axis-aligned to within its
|
||||
# 1e-4 rad tolerance, which moves an area by ~1e-4. It is deliberately tight enough to
|
||||
# have caught the real defect this rung was written for: with the old 3 degree gesture
|
||||
# slack applied to scripted input, a flattened circle came back 0.067% small — 0.266 on
|
||||
# an area of 397, some 300x above this line.
|
||||
# auto-constraint pass snaps segments that are already axis-aligned to within its 1e-4 rad
|
||||
# tolerance, which moves an area by ~1e-4. It is tight enough to catch a gesture's snap
|
||||
# slack applied to scripted input: a 3 degree slack flattens a circle to 0.067% small,
|
||||
# 0.266 on an area of 397, some 300x above this line.
|
||||
same = len(mine) == len(theirs) and all(
|
||||
abs(a - b) <= max(1e-3, 1e-6 * a) for a, b in zip(mine, theirs))
|
||||
ok &= report(name, "AREA", "every loop area matches the shoelace value exactly", same)
|
||||
|
||||
# VOID — a loop belongs to the SMALLEST loop that contains it, not to every loop that
|
||||
# encloses it. A hole inside a boss inside the part is a void of the boss, and the part
|
||||
# owns the boss. Comparing against "everything inside the outline" was measuring my own
|
||||
# sloppiness: on MPD781 that counted 36 voids where 26 of them are nested inside another
|
||||
# void. So compute the same rule here, independently, and compare the whole attribution.
|
||||
# owns the boss. Counting everything inside the outline as its void overcounts: on MPD781
|
||||
# 26 of the 36 loops inside the outline are nested inside another void. So compute the
|
||||
# same rule here, independently, and compare the whole attribution.
|
||||
if got:
|
||||
rings = [outer] + voids
|
||||
# Probe from a point STRICTLY INSIDE each ring, never from one of its vertices — the
|
||||
# same rule the engine now uses (DesignSketchTool::region_loops). A vertex is exactly
|
||||
# where two loops touch in a real drawing, and a ray cast from a point lying ON the
|
||||
# polygon under test answers by rounding: that alone accounted for every one of the 6
|
||||
# sheets where the two attributions used to disagree. 5hvl.
|
||||
# rule the engine uses too (DesignSketchTool::region_loops). A vertex is exactly where
|
||||
# two loops touch in a real drawing, and a ray cast from a point lying ON the polygon
|
||||
# under test answers by rounding, so probing from vertices would make the two
|
||||
# attributions disagree on such sheets for no fault of either.
|
||||
probes = [interior_point(r) for r in rings]
|
||||
mine_parent = {}
|
||||
for i, r in enumerate(rings):
|
||||
|
|
@ -319,8 +308,8 @@ def grade(pdf, name, report):
|
|||
# MIRROR / OFFSET — engine operations on a REAL profile, not a tidy one
|
||||
n_outer = len(outer) - 1
|
||||
try_call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", entities=ents[:n_outer])
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", entities=ents[:n_outer])
|
||||
xs = [p[0] for p in outer]
|
||||
axis = min(xs) - 10.0
|
||||
call("sketch_select", entities=list(range(n_outer)))
|
||||
|
|
@ -333,8 +322,8 @@ def grade(pdf, name, report):
|
|||
ok &= report(name, "MIRROR", f"refused: {e}", False)
|
||||
|
||||
try_call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
call("sketch_add", entities=ents[:n_outer])
|
||||
call("sketch_create", plane="XY")
|
||||
call("sketch_draw", entities=ents[:n_outer])
|
||||
try:
|
||||
call("sketch_offset", distance=0.5, entities=list(range(n_outer)))
|
||||
o = call("sketch_describe")
|
||||
|
|
@ -349,9 +338,9 @@ def grade(pdf, name, report):
|
|||
def grade_scale(pdf, name, report, budget):
|
||||
"""Same exactness, on a profile of several hundred entities, and timed.
|
||||
|
||||
"Interactive" is measurable from here even though nothing is clicked: every MCP verb is
|
||||
serviced on the UI THREAD, so the time a reply takes is time the window was not repainting.
|
||||
A round trip that stays inside the budget is a window that stayed responsive.
|
||||
"Interactive" is measurable from here even though nothing is clicked: every Design command runs on
|
||||
the UI THREAD, so the window was not repainting for at most the time its reply takes. A round
|
||||
trip that stays inside the budget is a window that stayed responsive.
|
||||
"""
|
||||
segs = drawing_segments(pdf)
|
||||
loops = find_loops(segs)
|
||||
|
|
@ -373,8 +362,8 @@ def grade_scale(pdf, name, report, budget):
|
|||
return None
|
||||
|
||||
try_call("sketch_cancel")
|
||||
call("sketch_begin", plane="XY")
|
||||
t0 = time.monotonic(); call("sketch_add", entities=ents); t_add = time.monotonic() - t0
|
||||
call("sketch_create", plane="XY")
|
||||
t0 = time.monotonic(); call("sketch_draw", entities=ents); t_add = time.monotonic() - t0
|
||||
t0 = time.monotonic(); r = call("sketch_describe"); t_desc = time.monotonic() - t0
|
||||
t0 = time.monotonic(); call("sketch_select", entities=list(range(len(ents))))
|
||||
t_sel = time.monotonic() - t0
|
||||
|
|
@ -404,8 +393,12 @@ def _pdf_error(path):
|
|||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--corpus", default=os.path.expanduser("~/studycadcam"))
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--corpus", required=True, help="the folder of the MPD*.pdf sheets")
|
||||
ap.add_argument("--datadir", default=os.environ.get("ORCA_DATADIR", ""),
|
||||
help="the running app's data directory (default: $ORCA_DATADIR, else the "
|
||||
"platform's own)")
|
||||
ap.add_argument("--step", type=int, default=20)
|
||||
ap.add_argument("--limit", type=int, default=0)
|
||||
ap.add_argument("--scale", action="store_true",
|
||||
|
|
@ -414,14 +407,17 @@ def main():
|
|||
help="seconds; the slowest round trip a scale drawing may take")
|
||||
a = ap.parse_args()
|
||||
|
||||
global APP
|
||||
APP = orca_mcp.OrcaMcp.from_datadir(a.datadir)
|
||||
|
||||
files = {}
|
||||
for f in glob.glob(os.path.join(a.corpus, "MPD*.pdf")):
|
||||
m = re.search(r"MPD(\d+)", os.path.basename(f))
|
||||
if m:
|
||||
files[int(m.group(1))] = f
|
||||
# step 1 means EVERY sheet. Written as `n % step == 1` it silently selected nothing, because
|
||||
# n % 1 is always 0 — and the run then printed "RUNG 9 HELD" over zero drawings graded. A
|
||||
# gate that passes by grading nothing is worse than no gate, so the count is checked below.
|
||||
# step 1 means EVERY sheet, which `n % step == 1` alone would never select, since n % 1 is
|
||||
# always 0. A gate that passes by grading nothing is worse than no gate, so the count is
|
||||
# checked below.
|
||||
picks = [files[n] for n in sorted(files) if a.step <= 1 or n % a.step == 1]
|
||||
if a.scale:
|
||||
# The heaviest real profiles in the corpus, biggest first — up to ~1300 entities.
|
||||
|
|
|
|||
|
|
@ -15,37 +15,32 @@ Every rung asserts those. Area appears only as a cross-check, never as the verdi
|
|||
|
||||
Entirely 2D: sketch entities only, no extrude, revolve or any solid feature.
|
||||
|
||||
ORCA_CAD_MCP=/tmp/mcp.sock <binary>
|
||||
python3 scripts/CAD/check-sketch-engine.py [socket]
|
||||
Run it against a running app started with --mcp and the CAD feature on, for example:
|
||||
|
||||
python3 tools/mcp/orca_mcp.py launch --cad --datadir <datadir>
|
||||
python3 scripts/CAD/check-sketch-engine.py [datadir]
|
||||
|
||||
datadir is the running app's data directory (default: $ORCA_DATADIR, else the platform's own); the
|
||||
script finds the app's MCP server through the port it writes to <datadir>/mcp/server.json.
|
||||
|
||||
Exit 0 = every rung held. Otherwise the first broken property is named and the run stops.
|
||||
"""
|
||||
import json, math, socket, sys
|
||||
import math, os, sys
|
||||
|
||||
SOCK = sys.argv[1] if len(sys.argv) > 1 else "/tmp/mcp.sock"
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "tools", "mcp"))
|
||||
import orca_mcp # noqa: E402
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
|
||||
print(__doc__)
|
||||
sys.exit(0)
|
||||
DATADIR = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("ORCA_DATADIR", "")
|
||||
APP = orca_mcp.OrcaMcp.from_datadir(DATADIR)
|
||||
EPS = 1e-9
|
||||
_n = 0
|
||||
_fail = 0
|
||||
|
||||
|
||||
def call(method, **params):
|
||||
global _n
|
||||
_n += 1
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(30)
|
||||
s.connect(SOCK)
|
||||
s.sendall((json.dumps({"jsonrpc": "2.0", "id": _n, "method": method,
|
||||
"params": params}) + "\n").encode())
|
||||
buf = b""
|
||||
while b"\n" not in buf:
|
||||
d = s.recv(65536)
|
||||
if not d:
|
||||
break
|
||||
buf += d
|
||||
r = json.loads(buf.decode().strip())
|
||||
if "error" in r:
|
||||
raise RuntimeError(f"{method}: {r['error']['message']}")
|
||||
return r["result"]
|
||||
return APP.call_command(method, **params)["result"]
|
||||
|
||||
|
||||
def check(kind, cond, what):
|
||||
|
|
@ -70,7 +65,7 @@ def fresh(plane="XY"):
|
|||
call("sketch_cancel")
|
||||
except Exception:
|
||||
pass
|
||||
call("sketch_begin", plane=plane)
|
||||
call("sketch_create", plane=plane)
|
||||
|
||||
|
||||
def ents():
|
||||
|
|
@ -138,7 +133,7 @@ def outer_loop(r):
|
|||
print("RUNG 1 — rectangle: four corners, four lengths, four right angles")
|
||||
fresh()
|
||||
W, H = 80.0, 50.0
|
||||
call("sketch_add", rect=[0, 0, W, H])
|
||||
call("sketch_draw", type="rectangle_2_point", p0=[0, 0], p1=[W, H])
|
||||
r = rep()
|
||||
es = r["entities"]
|
||||
corners = {(0, 0), (W, 0), (W, H), (0, H)}
|
||||
|
|
@ -165,7 +160,7 @@ check("ANGLE", ang_ok, "every corner is exactly 90 degrees")
|
|||
check("CLOSED", r["buildable"] and r["open_ends"] == [], "one closed loop, no free ends")
|
||||
|
||||
print("\nRUNG 2 — a circular void inside it")
|
||||
call("sketch_add", type="circle", center=[W / 2, H / 2], radius=12)
|
||||
call("sketch_draw", type="circle_center", center=[W / 2, H / 2], radius=12)
|
||||
r = rep()
|
||||
c = [e for e in r["entities"] if e["type"] == "circle"][0]
|
||||
check("VERTEX", pt_near(tuple(c["center"]), (W / 2, H / 2)), "void centred exactly where asked")
|
||||
|
|
@ -177,12 +172,12 @@ check("CLOSED", r["buildable"] and r["open_ends"] == [], "still closed with the
|
|||
print("\nRUNG 3 — stadium: straights running into caps, tangent at every junction")
|
||||
fresh()
|
||||
L, R = 50.0, 15.0
|
||||
call("sketch_add", entities=[
|
||||
call("sketch_draw", entities=[
|
||||
{"type": "line", "p0": [-L, -R], "p1": [L, -R]},
|
||||
{"type": "arc", "center": [L, 0], "radius": R,
|
||||
{"type": "arc_center", "center": [L, 0], "radius": R,
|
||||
"start_angle": -math.pi / 2, "end_angle": math.pi / 2},
|
||||
{"type": "line", "p0": [L, R], "p1": [-L, R]},
|
||||
{"type": "arc", "center": [-L, 0], "radius": R,
|
||||
{"type": "arc_center", "center": [-L, 0], "radius": R,
|
||||
"start_angle": math.pi / 2, "end_angle": 3 * math.pi / 2},
|
||||
])
|
||||
r = rep()
|
||||
|
|
@ -206,11 +201,11 @@ print("\nRUNG 4 — mirror: the reflected half is the exact reflection")
|
|||
fresh()
|
||||
half = [
|
||||
{"type": "line", "p0": [0, -R], "p1": [L, -R]},
|
||||
{"type": "arc", "center": [L, 0], "radius": R,
|
||||
{"type": "arc_center", "center": [L, 0], "radius": R,
|
||||
"start_angle": -math.pi / 2, "end_angle": math.pi / 2},
|
||||
{"type": "line", "p0": [L, R], "p1": [0, R]},
|
||||
]
|
||||
call("sketch_add", entities=half)
|
||||
call("sketch_draw", entities=half)
|
||||
r = rep()
|
||||
check("CLOSED", not r["buildable"] and len(r["open_ends"]) == 2,
|
||||
f"half profile is correctly OPEN, both ends named {r['open_ends']}")
|
||||
|
|
@ -249,7 +244,7 @@ check("VERTEX", all(near(abs(e["p0"][1]), R + d) for e in off_lines),
|
|||
|
||||
print("\nRUNG 6 — a gap is found by coordinate, then closed by a real constraint")
|
||||
fresh()
|
||||
call("sketch_add", entities=[
|
||||
call("sketch_draw", entities=[
|
||||
{"type": "line", "p0": [0, 0], "p1": [60, 0]},
|
||||
{"type": "line", "p0": [60, 0], "p1": [60, 40]},
|
||||
{"type": "line", "p0": [60, 40], "p1": [0, 40]},
|
||||
|
|
@ -259,7 +254,7 @@ r = call("sketch_validate", tolerance=1.0)
|
|||
check("CLOSED", not r["buildable"] and len(r["open_ends"]) == 2,
|
||||
f"the gap is reported, both free ends named {r['open_ends']}")
|
||||
dof0 = r["dof"]
|
||||
r = call("sketch_heal", tolerance=1.0)
|
||||
r = call("sketch_repair", tolerance=1.0)
|
||||
check("CLOSED", r["buildable"] and r["open_ends"] == [], "healed into a closed loop")
|
||||
check("VERTEX", r["welded"] == 1, "exactly one pair of vertices welded")
|
||||
check("ANGLE", r["dof"] < dof0,
|
||||
|
|
@ -270,11 +265,11 @@ check("VERTEX", pt_near(tuple(es[3]["p1"]), tuple(es[0]["p0"])),
|
|||
|
||||
print("\nRUNG 7 — the composite: mirrored, tangent, two voids, all at once")
|
||||
fresh()
|
||||
call("sketch_add", entities=half)
|
||||
call("sketch_draw", entities=half)
|
||||
call("sketch_select", entities=[0, 1, 2])
|
||||
call("sketch_mirror", axis_a=[0, 0], axis_b=[0, 1])
|
||||
call("sketch_add", type="circle", center=[-25, 0], radius=6)
|
||||
call("sketch_add", type="circle", center=[25, 0], radius=6)
|
||||
call("sketch_draw", type="circle_center", center=[-25, 0], radius=6)
|
||||
call("sketch_draw", type="circle_center", center=[25, 0], radius=6)
|
||||
r = rep()
|
||||
es = r["entities"]
|
||||
out = outer_loop(r)
|
||||
|
|
@ -307,11 +302,11 @@ ax, ay = TX - t, RAD # fillet tangent point on the cylinder
|
|||
cx, cy = ax, RAD - RF # fillet centre
|
||||
bx, by = TX + t * math.cos(-ANG), RAD + t * math.sin(-ANG) # tangent point on the cone
|
||||
ey = by - (LEN - bx) * math.tan(ANG) # where the cone meets the right face
|
||||
call("sketch_add", entities=[
|
||||
call("sketch_draw", entities=[
|
||||
{"type": "line", "p0": [0, 0], "p1": [0, RAD - CH]}, # left face
|
||||
{"type": "line", "p0": [0, RAD - CH], "p1": [CH, RAD]}, # C1 chamfer
|
||||
{"type": "line", "p0": [CH, RAD], "p1": [ax, ay]}, # cylinder top
|
||||
{"type": "arc", "center": [cx, cy], "radius": RF,
|
||||
{"type": "arc_center", "center": [cx, cy], "radius": RF,
|
||||
"start_angle": math.pi / 2, "end_angle": math.pi / 2 - ANG}, # R5 fillet
|
||||
{"type": "line", "p0": [bx, by], "p1": [LEN, ey]}, # 23 deg cone
|
||||
{"type": "line", "p0": [LEN, ey], "p1": [LEN, 0]}, # right face
|
||||
|
|
|
|||
|
|
@ -1,89 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# One turn of the keyboard-focus convergence loop, start to verdict, with no human in it.
|
||||
#
|
||||
# scripts/CAD/focus-loop.sh # full turn: sync -> build -> restart -> assert
|
||||
# SKIP_BUILD=1 scripts/CAD/focus-loop.sh # re-assert against the binary already on the host
|
||||
#
|
||||
# Exit 0 only when every gate holds. Any other exit is a failing gate and names which.
|
||||
#
|
||||
# WHY THIS EXISTS. The focus defects in the Design tab were chased for days by hand: build, launch
|
||||
# the GUI, drive it with xdotool, read a screenshot, guess, repeat. That needs a person at every
|
||||
# step and it is where the days went. This does not: behemoth carries an agent-owned Xvfb :10 with
|
||||
# openbox, the app, xdotool and an MCP socket that reports sketch state as JSON, so a turn is
|
||||
# sync -> build -> restart -> assert, and the ASSERTION is the verdict, not my reading of a picture.
|
||||
#
|
||||
# WHY BEHEMOTH AND NOT THE orcacad-gui RIG CONTAINER. The rig was the obvious host and it does not
|
||||
# work for this: its image pins a dependency set 216 non-CAD source files behind cad-mainline
|
||||
# (assimp among them), so today's CAD sources call GUI_App::is_auto_close_sketch_loops and
|
||||
# MainFrame::ensure_design_panel, which that tree has never heard of. Syncing all of src/ to fix
|
||||
# that needs a deps rebuild measured in hours. behemoth already builds this exact tree, already
|
||||
# runs a WM on :10, and is the machine the user actually runs the product on — so the loop asserts
|
||||
# against the shipping artefact rather than a stale twin. Reviving the rig means rebuilding its
|
||||
# deps image first; until then it cannot adjudicate anything about this code.
|
||||
#
|
||||
# SC2029: every ssh command below quotes locally-expanded config (HOST, SRC, DISP) on purpose
|
||||
# -- the remote tree is not this checkout and has no such config of its own.
|
||||
# shellcheck disable=SC2029
|
||||
set -uo pipefail
|
||||
|
||||
HOST="${HOST:-tommaso@100.103.234.2}"
|
||||
DISP="${DISP:-:10}"
|
||||
SRC="${SRC:-\$HOME/projects/orca/orcacad-native/src}"
|
||||
TRACE="${TRACE:-/tmp/ux-focus-loop.log}"
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
BIN="build/src/Release/orca-slicer"
|
||||
|
||||
say() { printf '\n=== %s\n' "$*"; }
|
||||
die() { printf 'GATE FAILED: %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
ssh -o ConnectTimeout=10 "$HOST" true || die "cannot reach $HOST"
|
||||
|
||||
# ---------------------------------------------------------------- S1 sync
|
||||
# Only the CAD paths and the ladders. behemoth's tree is a full cad-mainline checkout kept in step
|
||||
# by its own realign; pushing unrelated files from here would make the build host disagree with
|
||||
# git for reasons no later session could reconstruct.
|
||||
say "S1 sync"
|
||||
rsync -q "$REPO"/src/slic3r/GUI/CAD/*.{cpp,hpp} "$HOST:$SRC/src/slic3r/GUI/CAD/" || die "sync GUI/CAD"
|
||||
rsync -q "$REPO"/src/libslic3r/CAD/*.{cpp,hpp} "$HOST:$SRC/src/libslic3r/CAD/" || die "sync libslic3r/CAD"
|
||||
rsync -q "$REPO"/scripts/CAD/check-gui-click-edit.py "$REPO"/scripts/CAD/check-gui-sketching.py \
|
||||
"$HOST:/tmp/" || die "sync ladders"
|
||||
echo " sources + ladders in place"
|
||||
|
||||
# ---------------------------------------------------------------- S2 build
|
||||
# flock: two concurrent Orca builds once OOM'd this machine for 2h28m. Every build script on the
|
||||
# fleet takes this same lock.
|
||||
#
|
||||
# Grade the BINARY'S TIMESTAMP, never the build command's exit code. This is a Ninja Multi-Config
|
||||
# tree whose default rules are Debug while the artefact under test is Release, so a wrong-config
|
||||
# invocation returns success in seconds having touched nothing — it cost a wasted cycle here
|
||||
# before anyone thought to look at the file.
|
||||
if [ -z "${SKIP_BUILD:-}" ]; then
|
||||
say "S2 build"
|
||||
before=$(ssh "$HOST" "stat -c %Y $SRC/$BIN 2>/dev/null || echo 0")
|
||||
ssh "$HOST" "flock /tmp/orca-rig-build.lock \$HOME/projects/orca/orcacad-native/rebuild.sh > /tmp/focus-build.log 2>&1"
|
||||
rc=$?
|
||||
after=$(ssh "$HOST" "stat -c %Y $SRC/$BIN 2>/dev/null || echo 0")
|
||||
if [ "$rc" != 0 ] || [ "$after" = "$before" ]; then
|
||||
ssh "$HOST" "grep -m5 -B2 'error:' /tmp/focus-build.log; tail -5 /tmp/focus-build.log"
|
||||
die "S2 build (exit $rc, binary $( [ "$after" = "$before" ] && echo unchanged || echo rebuilt ))"
|
||||
fi
|
||||
echo " built"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------- S3 F2P
|
||||
# The ladder launches and tears down the app itself, in its own datadir, so nothing here has to
|
||||
# manage a process. It types WITHOUT clicking the field first, which is the whole contract.
|
||||
say "S3 fail-to-pass: type without clicking the field"
|
||||
ssh "$HOST" "cd $SRC && DISPLAY=$DISP python3 /tmp/check-gui-click-edit.py \
|
||||
--display $DISP --bin $BIN --trace $TRACE"
|
||||
f2p=$?
|
||||
|
||||
# ---------------------------------------------------------------- S4 P2P
|
||||
say "S4 pass-to-pass: the existing gesture ladder"
|
||||
ssh "$HOST" "cd $SRC && DISPLAY=$DISP python3 /tmp/check-gui-sketching.py 2>&1 | tail -3"
|
||||
p2p=$?
|
||||
|
||||
say "VERDICT"
|
||||
[ "$f2p" = 0 ] || die "F2P: a tool did not take the typed value (exit $f2p)"
|
||||
[ "$p2p" = 0 ] || die "P2P: the gesture ladder regressed (exit $p2p)"
|
||||
echo "ALL GATES HELD"
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Emit the C++ offer table from scripts/CAD/tool_atlas.json.
|
||||
"""Emit the Design tab's table from scripts/CAD/tool_atlas.json.
|
||||
|
||||
python3 scripts/CAD/gen_offer_table.py # rewrite the header
|
||||
python3 scripts/CAD/gen_offer_table.py --check # verify the checked-in header
|
||||
|
||||
The map exists ONCE: the atlas is the only place a verb's row, key, icon and refusal
|
||||
string are written down, so the menu the user sees cannot drift from the table the code
|
||||
is compiled against.
|
||||
The map exists ONCE: the atlas is the only place a verb's row, key, icon, refusal string and
|
||||
Design command are written down, so the menu the user sees, the Speed Dial's Design tab actions and
|
||||
the commands automation calls cannot drift from the table the code is compiled against.
|
||||
|
||||
Output: src/slic3r/GUI/CAD/DesignOffer.hpp, checked in and never hand-edited.
|
||||
"""
|
||||
|
|
@ -30,6 +30,21 @@ ENUM = {
|
|||
"sk_line": "SkLine", "sk_arc": "SkArc", "sk_point": "SkPoint", "sk_2ent": "Sk2Ent",
|
||||
}
|
||||
|
||||
# a tool block's access -> CadAccess enumerator
|
||||
ACCESS = {"read": "Read", "change": "Change", "sketch": "Sketch", "ui": "Ui"}
|
||||
|
||||
# The headings of tool_list's index of the Design commands (Mcp::design_command_index()), in its order: every
|
||||
# command's `section` is one of them. Menu items holds the commands that take no arguments and only do what their menu item
|
||||
# does.
|
||||
SECTIONS = ("Document", "Sketch", "Solid", "Surface", "Construct", "Inspect", "Bodies", "History", "Menu items")
|
||||
|
||||
# The keys of a tool block that its command's description, schema and examples are made from.
|
||||
DOC_KEYS = ("summary", "details", "params", "examples", "ids")
|
||||
|
||||
# A doc is emitted as adjacent string literals of at most this many characters each, so every
|
||||
# compiler takes it (MSVC refuses one literal over 16 KiB) and a change to it shows on its own line.
|
||||
DOC_PIECE = 96
|
||||
|
||||
|
||||
def cstr(s):
|
||||
if s is None:
|
||||
|
|
@ -48,27 +63,174 @@ def tstr_design(s):
|
|||
return "nullptr" if s is None else "L_CONTEXT(" + cstr(s) + ', "Design")'
|
||||
|
||||
|
||||
def validate(A):
|
||||
"""Refuse an atlas the header cannot represent, naming every fault at once.
|
||||
def doc_text(block):
|
||||
"""A tool block's summary, details, params, examples and ids as compact JSON text."""
|
||||
doc = {k: block[k] for k in DOC_KEYS}
|
||||
return json.dumps(doc, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def same(a, b):
|
||||
"""Whether two JSON values are equal, a boolean apart from a number."""
|
||||
return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True)
|
||||
|
||||
|
||||
def mode_of(v):
|
||||
return "sketch" if v.get("mode") == "sketch" else "model"
|
||||
|
||||
|
||||
def doc_literal(block, indent):
|
||||
if block is None:
|
||||
return "nullptr"
|
||||
text = doc_text(block)
|
||||
pieces = [text[i:i + DOC_PIECE] for i in range(0, len(text), DOC_PIECE)]
|
||||
return ("\n" + indent).join(cstr(p) for p in pieces)
|
||||
|
||||
|
||||
def arg_faults(vid, args, into):
|
||||
"""Why `args`, the arguments that choose entry `vid`'s item, are not arguments `into`'s block takes."""
|
||||
if not isinstance(args, dict):
|
||||
return [f"{vid}: args must be an object of the arguments that choose its item, not {args!r}"]
|
||||
params = {p.get("name"): p for p in into["tool"].get("params", [])}
|
||||
out = []
|
||||
for name, value in args.items():
|
||||
p = params.get(name)
|
||||
if p is None:
|
||||
out.append(f"{vid}: args name {name!r}, which {into['id']} does not take")
|
||||
elif "enum" in p and not any(same(value, e) for e in p["enum"]):
|
||||
out.append(f"{vid}: args give {name} {value!r}, which is not one of {p['enum']}")
|
||||
return out
|
||||
|
||||
|
||||
def faults(A):
|
||||
"""Every fault of the atlas A, each naming its entry: what the header cannot represent, and what would leave
|
||||
a call of a command unable to tell which of its items it opens.
|
||||
|
||||
An unknown slot or selection would surface as a bare ValueError from .index() below, and a
|
||||
duplicate verb id would not surface at all: DesignPanel::mcp_run_verb looks a verb up by id
|
||||
and takes the first match, so the second row would be unreachable from the offer.
|
||||
duplicate verb id would not surface at all: a verb is looked up by id (DesignPanel::mcp_run_verb,
|
||||
the catalog's command keys) and the first match taken, so the second item would be unreachable.
|
||||
An entry with no menu item, no handler (`action`) and no tool block is nothing; an item with neither is
|
||||
greyed (Align to, until it has a GUI path), and no command.
|
||||
|
||||
A folded item (`fold`) is a way of calling the command `into` names with `args`: it keeps its row and
|
||||
its handler and has no block of its own, and its command is an entry with a block that is no folded
|
||||
item. An entry with a handler and a block may name the `args` that choose its own item. The arguments
|
||||
that choose an item are ones its command takes, and choose that item only (Mcp::opened_item()): no two
|
||||
items of one command with equal args and different handlers, and no folded item with the args its
|
||||
command's own item takes, which a call with none also gives. A command's items are in one mode.
|
||||
|
||||
Every command, an entry with a handler or a block that is no folded item, has a `section`, its heading in
|
||||
tool_list's index (SECTIONS); a folded or greyed item, which is no command, has none.
|
||||
|
||||
`feature_row` marks an item whose handler acts on the selected row of the Feature list, which a call of its
|
||||
command takes as its target when nothing is picked in the view (Mcp::open_refusal()): only a command with a menu item
|
||||
of its own has one, an entry with a handler that is no folded item.
|
||||
"""
|
||||
slot_ids = {s["id"] for s in A["slots"]}
|
||||
sel_ids = {s["id"] for s in A["selections"]}
|
||||
errs, seen = [], set()
|
||||
for v in A["verbs"]:
|
||||
if v["slot"] not in slot_ids:
|
||||
errs.append(f'{v["id"]}: unknown slot {v["slot"]!r}')
|
||||
for a in v["accepts"]:
|
||||
vid = v["id"]
|
||||
if v["slot"] is None:
|
||||
# A command only: no menu item, so no handler the menu could run either.
|
||||
if v.get("action"):
|
||||
errs.append(f"{vid}: a handler (action) needs a slot")
|
||||
elif v["slot"] not in slot_ids:
|
||||
errs.append(f'{vid}: unknown slot {v["slot"]!r}')
|
||||
for a in v.get("accepts", []):
|
||||
if a not in sel_ids:
|
||||
errs.append(f'{v["id"]}: accepts unknown selection {a!r}')
|
||||
if v["id"] in seen:
|
||||
errs.append(f'{v["id"]}: duplicate verb id')
|
||||
seen.add(v["id"])
|
||||
errs.append(f"{vid}: accepts unknown selection {a!r}")
|
||||
if vid in seen:
|
||||
errs.append(f"{vid}: duplicate verb id")
|
||||
seen.add(vid)
|
||||
block = v.get("tool")
|
||||
if v["slot"] is None and not v.get("action") and block is None:
|
||||
errs.append(f"{vid}: neither a menu item, a handler (action) nor a tool block")
|
||||
if v.get("modal") and not v.get("action"):
|
||||
errs.append(f"{vid}: modal without a handler (action)")
|
||||
command = (v.get("action") or block is not None) and "fold" not in v
|
||||
if not command and "section" in v:
|
||||
errs.append(f"{vid}: a folded or greyed item is no command and has no section")
|
||||
elif command and "section" not in v:
|
||||
errs.append(f"{vid}: a command needs a section, its heading in tool_list's index: one of {list(SECTIONS)}")
|
||||
elif command and v["section"] not in SECTIONS:
|
||||
errs.append(f'{vid}: section {v["section"]!r} is not one of {list(SECTIONS)}')
|
||||
if v.get("feature_row") and (not v.get("action") or "fold" in v):
|
||||
errs.append(f"{vid}: feature_row needs a menu item of its own: a handler (action), and no fold")
|
||||
# By the key, not its value: an "operations": null names nothing, and is refused as a wrong value.
|
||||
if "operations" in v:
|
||||
ops = v["operations"]
|
||||
if not command:
|
||||
errs.append(f"{vid}: operations names what a command reaches, and a folded or greyed item is no command")
|
||||
elif not (isinstance(ops, list) and ops and all(isinstance(o, str) and o and "," not in o for o in ops)):
|
||||
errs.append(f"{vid}: operations is a list of the names of the operations its command reaches")
|
||||
if block is not None:
|
||||
if block.get("access") not in ACCESS:
|
||||
errs.append(f'{vid}: tool access {block.get("access")!r} is not one of {sorted(ACCESS)}')
|
||||
missing = [k for k in DOC_KEYS + ("ok_false",) if k not in block]
|
||||
if missing:
|
||||
errs.append(f"{vid}: tool block lacks {missing}")
|
||||
elif len(doc_text(block).encode("utf-8")) > 60000:
|
||||
errs.append(f"{vid}: tool block over 60000 bytes")
|
||||
# nullable false keeps a param's type from admitting null, which only a null default gives it.
|
||||
for p in block.get("params", []):
|
||||
if "nullable" in p and ("default" not in p or p["default"] is not None):
|
||||
errs.append(f'{vid}: param {p.get("name")!r} has nullable but no null default')
|
||||
if "args" in v:
|
||||
if not v.get("action") or block is None:
|
||||
errs.append(f"{vid}: own args need a handler (action) and a tool block")
|
||||
elif same(v["args"], {}):
|
||||
errs.append(f"{vid}: own args {{}} are what a call with none gives")
|
||||
else:
|
||||
errs += arg_faults(vid, v["args"], v)
|
||||
|
||||
by_id = {}
|
||||
for v in A["verbs"]:
|
||||
by_id.setdefault(v["id"], v)
|
||||
folded = {} # a command's id -> the items folded into it so far
|
||||
for v in A["verbs"]:
|
||||
if "fold" not in v:
|
||||
continue
|
||||
vid, fold = v["id"], v["fold"]
|
||||
if not isinstance(fold, dict):
|
||||
errs.append(f"{vid}: fold must be an object {{into, args}}, not {fold!r}")
|
||||
continue
|
||||
if not v.get("action"):
|
||||
errs.append(f"{vid}: a fold needs a handler (action), the item's own")
|
||||
if v.get("tool") is not None:
|
||||
errs.append(f"{vid}: a folded item has no tool block: its command has it")
|
||||
into = by_id.get(fold.get("into"))
|
||||
if into is None:
|
||||
errs.append(f"{vid}: fold's into {fold.get('into')!r} names no entry")
|
||||
continue
|
||||
if "fold" in into:
|
||||
errs.append(f"{vid}: fold's into {into['id']} is itself a folded item")
|
||||
continue
|
||||
if into.get("tool") is None:
|
||||
errs.append(f"{vid}: fold's into {into['id']} has no tool block")
|
||||
continue
|
||||
args = fold.get("args")
|
||||
bad = arg_faults(vid, args, into)
|
||||
errs += bad
|
||||
if bad:
|
||||
continue
|
||||
if into.get("action") and (same(args, {}) or ("args" in into and same(args, into["args"]))):
|
||||
errs.append(f"{vid}: its args are the args {into['id']}'s own item takes")
|
||||
if into["slot"] is not None and mode_of(v) != mode_of(into):
|
||||
errs.append(f"{vid}: in another mode than {into['id']}'s own item")
|
||||
for other in folded.get(into["id"], []):
|
||||
if mode_of(other) != mode_of(v):
|
||||
errs.append(f"{vid}: in another mode than {other['id']}, folded into {into['id']} too")
|
||||
if same(other["fold"]["args"], args) and other.get("action") != v.get("action"):
|
||||
errs.append(f"{vid}: the same args as {other['id']}, with another handler")
|
||||
folded.setdefault(into["id"], []).append(v)
|
||||
for s in sel_ids - set(ENUM):
|
||||
errs.append(f"selection {s!r} has no OfferSel enumerator")
|
||||
return errs
|
||||
|
||||
|
||||
def validate(A):
|
||||
"""Refuse an atlas the header cannot represent, naming every fault at once (faults())."""
|
||||
errs = faults(A)
|
||||
if errs:
|
||||
sys.exit("tool_atlas.json is inconsistent:\n " + "\n ".join(errs))
|
||||
|
||||
|
|
@ -83,10 +245,17 @@ def main():
|
|||
"// GENERATED FILE — DO NOT EDIT.",
|
||||
"// Source: scripts/CAD/tool_atlas.json Generator: scripts/CAD/gen_offer_table.py",
|
||||
"//",
|
||||
"// The object-driven tool offer (charter 4.1): every verb has ONE row index, that index",
|
||||
"// is the same in every selection it appears in, and verbs that do not apply are shown",
|
||||
"// disabled in place with their reason rather than removed. Row order was ratified",
|
||||
"// 2026-07-31; changing an index is a breaking change to every user's muscle memory.",
|
||||
"// The Design tab's table. Its verbs are the object-driven tool offer (charter 4.1): every verb",
|
||||
"// has ONE row index, that index is the same in every selection it appears in, and verbs that do",
|
||||
"// not apply are shown disabled in place with their reason rather than removed. Row order was",
|
||||
"// ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory.",
|
||||
"// An entry with a handler or a tool block, and no fold_into, is a command of the catalog's group Design",
|
||||
"// (Mcp::register_design_tools(), Mcp::is_design_command()), under its section in tool_list's index. A",
|
||||
"// call whose arguments are exactly those that choose one of its items opens that item's tool for a person",
|
||||
"// (Mcp::opened_item()): none choose the entry's own item where it has a handler, else the items folded into it",
|
||||
"// with {}; a folded item's args, or the entry's own, choose that item. Any other call runs its tool block's",
|
||||
"// silent form. A folded item (fold_into) is no command: it is a way of calling the command it names. An item",
|
||||
"// with neither a handler nor a tool block is greyed, and no command. An entry with no menu item is a command only.",
|
||||
"#ifndef slic3r_GUI_DesignOffer_hpp_",
|
||||
"#define slic3r_GUI_DesignOffer_hpp_",
|
||||
"",
|
||||
|
|
@ -102,7 +271,7 @@ def main():
|
|||
"namespace Slic3r { namespace GUI {",
|
||||
"",
|
||||
"// What the viewport has selected. Ordered as in tool_atlas.json; the bitmask in",
|
||||
"// OfferVerb::accepts indexes these.",
|
||||
"// DesignTool::accepts indexes these.",
|
||||
"enum class OfferSel : int {",
|
||||
]
|
||||
for i, s in enumerate(sels):
|
||||
|
|
@ -113,19 +282,38 @@ def main():
|
|||
"",
|
||||
"inline uint32_t offer_bit(OfferSel s) { return 1u << int(s); }",
|
||||
"",
|
||||
"// One row of the offer. `action` routes to the code that already implements the verb:",
|
||||
"// The atlas's id of each selection, in OfferSel's order.",
|
||||
"static const char* const kDesignSelectionIds[] = {",
|
||||
]
|
||||
for s in sels:
|
||||
lines.append(f" {cstr(s)},")
|
||||
lines += [
|
||||
"};",
|
||||
"",
|
||||
"// What a Design command's silent form does to the document, which decides when the Design tab lets",
|
||||
"// it run (DesignPanel::mcp_busy()). Read only looks, so it runs under anything but a rebuild. Sketch",
|
||||
"// drives the live sketch session, and Change edits the feature list or variables, or sets what is",
|
||||
"// selected in the model; both are refused under an open card, the Text dialog, Constrain mode or a body",
|
||||
"// Move, and Change under a sketch session too, which is about to commit into the feature list and in",
|
||||
"// which a click means something else. Ui acts on what the tab has open (its Confirm and Cancel), so only a",
|
||||
"// rebuild refuses it, though it changes the document. None: an entry with no silent form, and the opening",
|
||||
"// of a tool, which only a rebuild refuses, as the Design tab's keys and menu do.",
|
||||
"enum class CadAccess { None, Read, Change, Sketch, Ui };",
|
||||
"",
|
||||
"// One entry of the table. Its handler (`action`) routes to the code that already implements the verb:",
|
||||
'// "key:S+E" -> m_keys_feature[SHIFT(\'E\')]',
|
||||
'// "key:L" -> m_keys_sketch[\'L\']',
|
||||
'// "fly:material#4" -> row 4 of the "material" feature flyout',
|
||||
'// "btn:delete" -> a standalone toolbar button',
|
||||
"// nullptr -> kernel support exists, no GUI path yet (row shows disabled)",
|
||||
"struct OfferVerb {",
|
||||
" const char* id;",
|
||||
"// nullptr -> no GUI path (the item, if it has one, shows disabled)",
|
||||
"struct DesignTool {",
|
||||
" const char* id; // also the key of its Design command",
|
||||
" const char* name; // drawing-office word (L10); msgctxt \"Design\", translated at use",
|
||||
" int row; // index into kOfferRowNames, the ratified address — NEVER reorder",
|
||||
" const char* key; // shortcut shown in the row, or nullptr",
|
||||
" int row; // index into kOfferRowNames, the ratified address — NEVER reorder;",
|
||||
" // -1: no menu item, a command only",
|
||||
" const char* key; // shortcut shown in the item, or nullptr",
|
||||
" const char* action;",
|
||||
" const char* refusal; // why this row is greyed, in the product's own words",
|
||||
" const char* refusal; // why this item is greyed, in the product's own words",
|
||||
" uint32_t accepts; // bitmask over OfferSel",
|
||||
" int need_bodies;",
|
||||
" int need_sketches;",
|
||||
|
|
@ -136,8 +324,37 @@ def main():
|
|||
" // address fixed (L4.1) while the variants hang one level below it, mirroring the toolbar's",
|
||||
" // grouping instead of flattening 19 create tools into one wall.",
|
||||
" const char* family;",
|
||||
" const char* icon; // resources/images name, or nullptr — the offer draws it beside the row",
|
||||
" const char* icon; // resources/images name, or nullptr — the offer draws it beside the item",
|
||||
" const char* hint; // what the verb does / what to click; shown on hover",
|
||||
" bool modal; // its handler opens a dialog that waits for an answer: a modal one, which holds",
|
||||
" // the call until it is answered, or Text's, which is modeless and does not",
|
||||
" CadAccess access; // its silent form's, None without one",
|
||||
" bool ok_false; // its silent form reports a rejected rebuild in its reply (ok false)",
|
||||
" // Its silent form's summary, details, params, examples and ids as JSON text, the parameter",
|
||||
" // schema of record; nullptr for an entry whose command only does what its menu item does.",
|
||||
" const char* doc;",
|
||||
" const char* fold_into; // the id of the command this item is a variant of, or nullptr",
|
||||
" // The arguments that choose this item, as JSON text: a folded item's, or those that choose the own item of",
|
||||
" // an entry with a handler and a tool block as a call with none does; nullptr for none.",
|
||||
" const char* args;",
|
||||
" // The heading its command is listed under in tool_list's index (kDesignSections,",
|
||||
" // Mcp::design_command_index()); nullptr for an entry that is no command.",
|
||||
" const char* section;",
|
||||
" // Its handler acts on the selected row of the Feature list, which a call of its command, not a person's",
|
||||
" // pick, takes as what the item is for while nothing is picked in the view (Mcp::open_refusal()).",
|
||||
" bool feature_row;",
|
||||
" // The operations of GUI/Operations its command reaches, comma-separated, which the catalog lists as the",
|
||||
" // command's (Mcp::reaching()); nullptr for none, as a command that changes only the Design document has.",
|
||||
" const char* operations;",
|
||||
"};",
|
||||
"",
|
||||
"// The headings of tool_list's index of the Design commands, in its order. Menu items holds the commands",
|
||||
"// that take no arguments and only do what their menu item does.",
|
||||
"static const char* const kDesignSections[] = {",
|
||||
]
|
||||
for s in SECTIONS:
|
||||
lines.append(f" {cstr(s)},")
|
||||
lines += [
|
||||
"};",
|
||||
"",
|
||||
"// Row labels, in ratified order.",
|
||||
|
|
@ -158,7 +375,7 @@ def main():
|
|||
lines += [
|
||||
"};",
|
||||
"",
|
||||
"static const OfferVerb kOfferVerbs[] = {",
|
||||
"static const DesignTool kDesignTools[] = {",
|
||||
]
|
||||
# A verb the user can PICK must say what it does. Fail loudly rather than ship a
|
||||
# bare name — the offer is now the only door to these tools.
|
||||
|
|
@ -173,20 +390,39 @@ def main():
|
|||
for ln in ([v["note"]] if isinstance(v.get("note"), str) else v.get("note") or []):
|
||||
lines.append(f" // {ln}")
|
||||
mask = 0
|
||||
for a in v["accepts"]:
|
||||
for a in v.get("accepts", []):
|
||||
mask |= 1 << sels.index(a)
|
||||
n = v.get("needs") or {}
|
||||
block = v.get("tool")
|
||||
in_menu = v["slot"] is not None
|
||||
# Every name is marked, an entry's with no menu item too: it is its command's title, which a person
|
||||
# sees translated in the Design context in the Action Replay window and a recording's caption,
|
||||
# and on the Speed Dial action of an entry with a menu item. A table with an unmarked name is
|
||||
# refused, written or checked, since nothing at run time can tell (L_CONTEXT compiles to the bare
|
||||
# string).
|
||||
name = tstr_design(v["name"])
|
||||
if not (name.startswith('L_CONTEXT("') and name.endswith('", "Design")')):
|
||||
sys.exit(f'entry {v["id"]}: its name is not marked for translation in the Design context: {name}')
|
||||
fold = v.get("fold")
|
||||
args = fold["args"] if fold else v.get("args")
|
||||
lines.append(
|
||||
" {%s, %s, %d, %s, %s, %s, 0x%08xu, %d, %d, %s, %s, %s, %s, %s}," % (
|
||||
cstr(v["id"]), tstr_design(v["name"]), slots.index(v["slot"]),
|
||||
" {%s, %s, %d, %s, %s, %s, 0x%08xu, %d, %d, %s, %s, %s, %s, %s, %s, CadAccess::%s, %s,\n %s, %s, %s, %s, %s, %s}," % (
|
||||
cstr(v["id"]), name, slots.index(v["slot"]) if in_menu else -1,
|
||||
cstr(v.get("key")), cstr(v.get("action")), tstr(v.get("refusal")),
|
||||
mask, n.get("bodies", 0), n.get("sketches", 0),
|
||||
"true" if n.get("sheet") else "false",
|
||||
"true" if v.get("mode") == "sketch" else "false",
|
||||
tstr_design(v.get("family")), cstr(v.get("icon")), tstr(v.get("hint"))))
|
||||
tstr_design(v.get("family")), cstr(v.get("icon")), tstr(v.get("hint")),
|
||||
"true" if v.get("modal") else "false",
|
||||
ACCESS[block["access"]] if block else "None",
|
||||
"true" if block and block["ok_false"] else "false",
|
||||
doc_literal(block, " "), cstr(fold["into"]) if fold else "nullptr",
|
||||
"nullptr" if args is None else cstr(json.dumps(args, ensure_ascii=False, separators=(",", ":"))),
|
||||
cstr(v.get("section")), "true" if v.get("feature_row") else "false",
|
||||
cstr(",".join(v["operations"]) if v.get("operations") else None)))
|
||||
lines += [
|
||||
"};",
|
||||
f"static const int kOfferVerbCount = {len(A['verbs'])};",
|
||||
f"static const int kDesignToolCount = {len(A['verbs'])};",
|
||||
"",
|
||||
"}} // namespace Slic3r::GUI",
|
||||
"",
|
||||
|
|
@ -195,8 +431,9 @@ def main():
|
|||
]
|
||||
text = "\n".join(lines)
|
||||
# --check: prove the checked-in header IS what this generator produces, and change nothing.
|
||||
# The header calls itself GENERATED and was hand-edited anyway; a claim like that is only
|
||||
# worth having if something enforces it, so run-all-checks.sh runs this on every gate.
|
||||
# The header calls itself GENERATED; a claim like that is only worth having if something
|
||||
# enforces it, so the check_cad_offer_table.yml workflow runs this on every push and pull
|
||||
# request that touches the atlas, this generator or the header.
|
||||
if "--check" in sys.argv:
|
||||
have = open(OUT, encoding="utf-8").read() if os.path.exists(OUT) else ""
|
||||
if have == text:
|
||||
|
|
@ -208,11 +445,15 @@ def main():
|
|||
print(f"{os.path.relpath(OUT, REPO)} DIFFERS from tool_atlas.json:")
|
||||
print("\n".join(d[:60]))
|
||||
return 1
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
with open(OUT, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(text)
|
||||
in_menu = [v for v in A["verbs"] if v["slot"] is not None]
|
||||
wired = sum(1 for v in A["verbs"] if v.get("action"))
|
||||
print(f"wrote {os.path.relpath(OUT, REPO)}: {len(A['verbs'])} verbs, "
|
||||
f"{len(slots)} rows, {wired} wired to existing actions")
|
||||
blocks = sum(1 for v in A["verbs"] if v.get("tool"))
|
||||
folded = sum(1 for v in A["verbs"] if v.get("fold"))
|
||||
print(f"wrote {os.path.relpath(OUT, REPO)}: {len(A['verbs'])} entries, {len(in_menu)} in "
|
||||
f"{len(slots)} rows, {wired} with a handler, {blocks} with a silent form, "
|
||||
f"{folded} folded into their commands")
|
||||
return 0
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,151 +0,0 @@
|
|||
# Rig build traps
|
||||
|
||||
The build rig is two long-lived containers, `snapmaker-gui` and `orcacad-gui`, one per fork. Each
|
||||
mounts only its fork's build volume (`snapmaker_buildcache` / `orcacad_buildcache`) at
|
||||
`/OrcaSlicer/build`, its fork's `resources/`, and a shots directory — nothing else. They run the
|
||||
binary; they do not build it. Rebuild with `scripts/CAD/build-gui.sh`.
|
||||
|
||||
| fork repo | project() | deps image | build volume | GUI container | binary |
|
||||
|---|---|---|---|---|---|
|
||||
| `Snapmaker` | `Snapmaker_Orca` | `snapmaker-deps` | `snapmaker_buildcache` | `snapmaker-gui` | `snapmaker-orca` |
|
||||
| `orca_cad` | `OrcaSlicer` | `orcacad-deps` | `orcacad_buildcache` | `orcacad-gui` | `orca-slicer` |
|
||||
|
||||
`scripts/CAD/build-gui.sh` exists alongside `scripts/CAD/build-gui-incremental.sh` for one reason: it does a
|
||||
target-only `ninja` into the volume the GUI rig launches from, so a session can test a single
|
||||
change without a full repackage, whereas `build-gui-incremental.sh` runs the full packaged build.
|
||||
Both start a throwaway container from the deps image with the live repo mounted over the baked
|
||||
tree — never build inside the GUI container (Trap 1).
|
||||
|
||||
Every trap below has already cost about a session to re-derive, once each. They are recorded now
|
||||
so no fresh session pays them again. Symptoms, causes, and exact recovery commands follow.
|
||||
|
||||
---
|
||||
|
||||
## Trap 1 — never configure inside the GUI container
|
||||
|
||||
**Symptom.** After building inside the GUI container, the fork's targets no longer exist; ninja
|
||||
reports an unknown target, and `orca-slicer` / `OrcaSlicer` have been replaced by
|
||||
`snapmaker-orca` / `Snapmaker_Orca`.
|
||||
|
||||
**Cause.** The GUI image's baked `/OrcaSlicer` tree is the Jun-13 Snapmaker-derived source
|
||||
(`project(Snapmaker_Orca)`, executable `snapmaker-orca`). `orcacad-deps` is layered on
|
||||
`snapmaker-deps`, so even on the mainline fork the baked tree is the other fork's. A `cmake .`
|
||||
there reconfigures the shared build dir under the wrong project name.
|
||||
|
||||
**Fix.** Build only via `scripts/CAD/build-gui.sh`, which starts a throwaway container from the deps
|
||||
image with the live repo mounted over the baked tree — `src`, `resources`, `cmake`, `deps_src`,
|
||||
`localization`, `CMakeLists.txt`, `version.inc` — and writes into the same volume the rig
|
||||
launches from.
|
||||
|
||||
---
|
||||
|
||||
## Trap 2 — stale `NLopt_DIR` in CMakeCache
|
||||
|
||||
**Symptom.** Configure fails with `Cannot find NLopt library 'nlopt_cxx' in '<prefix>/lib'`.
|
||||
|
||||
**Cause.** `cmake/modules/FindNLopt.cmake:26` is `set(NLopt_DIR $ENV{NLOPT})`. With `NLOPT`
|
||||
unset that expands to `set(NLopt_DIR)` — zero arguments — which *unsets the normal variable* and
|
||||
lets a leftover CACHE entry of the same name (e.g. `<prefix>/lib/cmake/nlopt`) show through the
|
||||
following `if(NOT NLopt_DIR)`. The `else()` branch then searches for `nlopt_cxx` under
|
||||
`${NLopt_DIR}/lib` with `NO_DEFAULT_PATH`, while the deps prefix ships plain `nlopt`.
|
||||
|
||||
**Fix.** From inside the build dir:
|
||||
|
||||
cmake -U NLopt_DIR -U NLopt_LIBS .
|
||||
|
||||
Do **not** `sed` the entry out of `CMakeCache.txt` — deleting a line breaks the cache parser.
|
||||
|
||||
---
|
||||
|
||||
## Trap 3 — the image lacks `deps_src/pybind11`
|
||||
|
||||
**Symptom.** Configure aborts with `pybind11 headers not found in /OrcaSlicer/deps_src/pybind11.
|
||||
Did you initialize submodules?` (the `FATAL_ERROR` guarding `PYBIND11_SOURCE_DIR` in the mainline
|
||||
fork's root `CMakeLists.txt`, near line 948).
|
||||
|
||||
**Cause.** The deps image predates that requirement. Only the mainline (`orca_cad`) fork has
|
||||
`deps_src/pybind11` and the requirement; Snapmaker has neither.
|
||||
|
||||
**Fix.** Mount `deps_src` over the baked tree — `scripts/CAD/build-gui.sh` does. Corollary: mounting a
|
||||
Snapmaker tree into an `orcacad-deps` build reproduces this error exactly.
|
||||
|
||||
---
|
||||
|
||||
## Trap 4 — `OCCT_LIBS` lags one configure
|
||||
|
||||
**Symptom.** A wall of undefined references to `TopOpeBRepBuild` symbols. It reads as a broken
|
||||
OCCT installation. It is not.
|
||||
|
||||
**Cause.** `src/libslic3r/CMakeLists.txt:603` does
|
||||
`set(OCCT_LIBS "${OCCT_LIBS}" CACHE INTERNAL "OCCT toolkits linked by libslic3r")` at the END of
|
||||
its own configure, while the consumer in the root `CMakeLists.txt` (`if (NOT OCCT_LIBS)` …
|
||||
`foreach (_tk IN LISTS OCCT_LIBS)`) reads whatever is already in the cache. The first reconfigure
|
||||
after the `TKFillet TKOffset` prepend (`src/libslic3r/CMakeLists.txt:599`) therefore links the
|
||||
previous list and drops `TKBool`/`TKOffset`.
|
||||
|
||||
**Fix.** Configure twice. `scripts/CAD/build-gui.sh` runs `cmake .` twice for exactly this reason; if
|
||||
you ever configure by hand, run it twice.
|
||||
|
||||
---
|
||||
|
||||
## Trap 5 — `SLIC3R_CAD=ON` in the cache, macro never defined
|
||||
|
||||
**Symptom.** The build succeeds and links, but the Design tab is simply absent — or it fails with
|
||||
`class GLCanvas3D has no member named set_design_sketch_tool`.
|
||||
|
||||
**Cause.** The cache carries `SLIC3R_CAD=ON`, but the root `CMakeLists.txt` actually configured is
|
||||
a stale baked copy that predates the gate and never runs `add_definitions(-DSLIC3R_CAD)` (the
|
||||
gate is `if (SLIC3R_CAD)` / `add_definitions(-DSLIC3R_CAD)` in the root list — line 179/180 in
|
||||
Snapmaker, 319/320 in orca_cad). Every `#ifdef SLIC3R_CAD` block therefore compiles out while the
|
||||
option still reads ON.
|
||||
|
||||
**Fix.** Always mount the live `CMakeLists.txt` and `cmake/` — never inherit them from the image.
|
||||
This is why `scripts/CAD/build-gui-incremental.sh`, `scripts/CAD/run-kernel-tests.sh` and `scripts/CAD/build-gui.sh`
|
||||
all mount both.
|
||||
|
||||
---
|
||||
|
||||
## The binary the rig actually launches
|
||||
|
||||
`ninja <target>` writes `/OrcaSlicer/build/src/Release/<binary>`; only `build_linux.sh`
|
||||
additionally packages to `/OrcaSlicer/build/package/bin/<binary>`. `orca_cad`'s
|
||||
`scripts/CAD/start-headless-gui.sh` defaults `BIN` to `src/Release/orca-slicer`, but Snapmaker's defaults to
|
||||
`package/bin/snapmaker-orca`. So after a target-only rebuild on Snapmaker, launching
|
||||
`start-headless-gui.sh` with its default runs the **stale packaged** binary — the change under test is
|
||||
invisible and the session hunts a phantom. Pass `BIN` explicitly:
|
||||
|
||||
docker exec -e BIN=/OrcaSlicer/build/src/Release/snapmaker-orca snapmaker-gui /OrcaSlicer/scripts/CAD/start-headless-gui.sh
|
||||
|
||||
`scripts/CAD/build-gui.sh` prints the correct line for the current fork when it finishes.
|
||||
|
||||
Note also that the GUI containers do **not** mount `scripts/`: `/OrcaSlicer/scripts` inside them
|
||||
is the baked copy, so a local edit to `start-headless-gui.sh` has no effect until you
|
||||
`docker cp scripts/CAD/start-headless-gui.sh <container>:/OrcaSlicer/scripts/`.
|
||||
|
||||
---
|
||||
|
||||
## Trap 6 — `src/Release/` resolves resources to `build/resources`, which may not exist
|
||||
|
||||
The binary derives `resources_dir()` from its own location, so the `src/Release/` one looks in
|
||||
`/OrcaSlicer/build/resources` while the packaged one looks inside `build/package/`. Only the
|
||||
packaging step creates the latter; nothing creates the former. Without it the app fails every
|
||||
`Failed to add custom font ".../build/resources/fonts/…"`, logs `Health check is not running`,
|
||||
and **exits 255 with nothing on stdout** — which reads exactly like a crash in whatever you just
|
||||
changed. Measured 2026-08-02: an hour was nearly spent bisecting a GUI change that was fine.
|
||||
|
||||
`build/` is the shared cache volume, so one symlink fixes it permanently, and pointing it at the
|
||||
bind-mounted repo tree means the rig also picks up new `resources/images/*.svg` without a rebuild:
|
||||
|
||||
docker exec <fork>-gui ln -sfn /OrcaSlicer/resources /OrcaSlicer/build/resources
|
||||
|
||||
Tell the two apart before debugging: a resource failure dies in the first second with no window;
|
||||
a real fault in your code gets past the version banner. Compare
|
||||
`~/.config/<App>/log/<newest>.log.0` against a known-good run — 47 lines versus 340 is the tell.
|
||||
|
||||
## Trap 7 — a single-instance app plus a path-matched `pkill`
|
||||
|
||||
`start-headless-gui.sh` used to kill by `"$BIN"`, while its own `app_pid()` matched by BASENAME. Launch
|
||||
with a `BIN` that differs from the running instance's path and the old process survives, keeps
|
||||
the single-instance lock, and the new one exits seconds after loading fonts — then `status`
|
||||
reports the *stale* pid as a healthy session. Fixed by killing on the basename; `status` now also
|
||||
prints `binary : $(readlink -f /proc/<pid>/exe)`. **Read that line before trusting a screenshot.**
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Every ladder, in one command, as the gate before a push that touched the Design tab.
|
||||
#
|
||||
# WHY A SCRIPT AND NOT CI. Three of the four rungs need a running application with an OpenGL
|
||||
# canvas and synthetic input; GitHub's runners have neither. So the gate is local and explicit:
|
||||
# run this, read the last line, and do not push a red one. The kernel suite is the only part CI
|
||||
# can carry, and it already does.
|
||||
#
|
||||
# scripts/CAD/run-all-checks.sh # kernel + engine + corpus (every 20th) + gestures + offer
|
||||
# FULL=1 scripts/CAD/run-all-checks.sh # corpus over ALL 997 sheets (~25 min)
|
||||
# SKIP_GUI=1 scripts/CAD/run-all-checks.sh # kernel only, for a machine with no rig
|
||||
#
|
||||
# The rig container is expected to be up with the app running and ORCA_CAD_MCP set; bring it up
|
||||
# with scripts/CAD/start-headless-gui.sh inside it. The corpus lives at /corpus in that container.
|
||||
set -uo pipefail
|
||||
# ../.. -- this script lives in scripts/CAD/, so one level up is scripts/, not the repo
|
||||
# root. It was scripts/ladder-all.sh when it was written; the move fixed the three sibling
|
||||
# scripts and missed this one, which left every rung looking for its own path under
|
||||
# scripts/scripts/ and reporting instant failures that were all the same typo.
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/../.." || exit 1
|
||||
|
||||
# orcacad-gui, NOT snapmaker-gui: that is the other fork's rig, and defaulting to it makes
|
||||
# this gate verify the wrong fork's binary while reporting green. run-kernel-tests.sh
|
||||
# carries the same warning about the build volume, where the defect was found first.
|
||||
C="${C:-orcacad-gui}"
|
||||
CORPUS="${CORPUS:-/corpus}"
|
||||
STEP="${STEP:-20}"
|
||||
[ -n "${FULL:-}" ] && STEP=1
|
||||
fail=0
|
||||
|
||||
step() {
|
||||
local name="$1"; shift
|
||||
echo
|
||||
echo "=== $name ==="
|
||||
if "$@"; then echo "--- $name OK"; else echo "--- $name FAILED"; fail=1; fi
|
||||
}
|
||||
|
||||
# This fork's rig runs Xvfb on :11, the other fork's on :10, and the check scripts default
|
||||
# to ":10" when DISPLAY is unset -- which docker exec leaves unset. The rungs that drive the
|
||||
# GUI therefore looked for a window on a display that does not exist here and reported
|
||||
# "FATAL no app window on :10", which reads like a dead app rather than a wrong display.
|
||||
RIG_DISPLAY="${RIG_DISPLAY:-:11}"
|
||||
|
||||
# SC2329: every call goes through step(), which invokes it via "$@", so shellcheck
|
||||
# cannot see the callers below.
|
||||
# shellcheck disable=SC2329
|
||||
run_in_rig() { # copy the script in fresh, then run it there
|
||||
docker cp "$1" "$C:/tmp/$(basename "$1")" >/dev/null || return 1
|
||||
shift
|
||||
docker exec -e DISPLAY="$RIG_DISPLAY" "$C" python3 "$@"
|
||||
}
|
||||
|
||||
# FIRST, and it needs no rig: the offer table the menu is compiled from must be what the atlas
|
||||
# says. The header calls itself GENERATED and had been hand-edited anyway — which cost four rows
|
||||
# that existed only in the header, one row wired to the wrong action, and a count of 91 for a
|
||||
# 92-row array, so the last verb was unreachable (z8rs, ziam).
|
||||
# The atlas and its generator live beside this script, in scripts/CAD/: they are build inputs
|
||||
# for a checked-in header, not documentation, so they do not belong under docs/.
|
||||
step "offer table matches the atlas" python3 scripts/CAD/gen_offer_table.py --check
|
||||
|
||||
step "kernel suite" scripts/CAD/run-kernel-tests.sh --vol "${KVOL:-orcacad_kerneltest}"
|
||||
|
||||
if [ -z "${SKIP_GUI:-}" ]; then
|
||||
step "engine ladder (rungs 1-8, scripted geometry)" \
|
||||
run_in_rig scripts/CAD/check-sketch-engine.py /tmp/check-sketch-engine.py
|
||||
step "corpus rung (real drawings, every ${STEP}th)" \
|
||||
run_in_rig scripts/CAD/check-sketch-engine-corpus.py /tmp/check-sketch-engine-corpus.py --corpus "$CORPUS" --step "$STEP"
|
||||
step "corpus scale rung (the heaviest sheets)" \
|
||||
run_in_rig scripts/CAD/check-sketch-engine-corpus.py /tmp/check-sketch-engine-corpus.py --corpus "$CORPUS" --scale
|
||||
step "gesture ladder (mouse and keyboard)" \
|
||||
run_in_rig scripts/CAD/check-gui-sketching.py /tmp/check-gui-sketching.py
|
||||
# The offer ladder needs TWO extra things the others do not: the app must have been launched
|
||||
# with ORCA_CAD_KEYTRACE=1 (its [OFFER] lines are the whole instrument), and it reads the
|
||||
# generated offer table to predict what each selection should show — which is not in the
|
||||
# container's own baked source tree, so it is copied in beside the script — /tmp, where
|
||||
# run_in_rig puts the script, is one of the paths the ladder looks in.
|
||||
docker cp src/slic3r/GUI/CAD/DesignOffer.hpp "$C:/tmp/DesignOffer.hpp" >/dev/null
|
||||
step "offer ladder (right-click, the menu, the verbs behind it)" \
|
||||
run_in_rig scripts/CAD/check-gui-context-menu.py /tmp/check-gui-context-menu.py
|
||||
fi
|
||||
|
||||
echo
|
||||
if [ "$fail" -eq 0 ]; then echo "ALL LADDERS HELD"; else echo "AT LEAST ONE LADDER FAILED"; fi
|
||||
exit "$fail"
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Headless CAD-kernel test loop. THE verification contract for delegated work:
|
||||
# exit 0 means the kernel builds and the selected Catch2 tags pass. Nothing else counts.
|
||||
#
|
||||
# Builds only the `libslic3r_tests` target (not the GUI app), so a round trip is
|
||||
# minutes, not tens of minutes. Needs no display: every [CadDocument] case builds a
|
||||
# CadDocument, recompute()s it and asserts on geometry.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/CAD/run-kernel-tests.sh # [CadDocument] tags, default volume
|
||||
# scripts/CAD/run-kernel-tests.sh --tags '[CadDocument],[Sketch]'
|
||||
# scripts/CAD/run-kernel-tests.sh --vol wt_mirror # private build cache (parallel workers)
|
||||
# scripts/CAD/run-kernel-tests.sh --host tommaso@100.103.234.2 # build on a remote host
|
||||
#
|
||||
# Parallel workers MUST pass a distinct --vol: two builds sharing one cache corrupt
|
||||
# each other. A new volume pays one full build; runs after that are incremental.
|
||||
#
|
||||
# --host exists because the deps image lives wherever it was first built. It rsyncs this
|
||||
# working tree to a per-volume staging dir on that host and re-runs this same script
|
||||
# there, so the verification contract is identical either way. Drop --host once the image
|
||||
# is present locally.
|
||||
# Rig build traps already paid for once each (stale project, NLopt cache, pybind11, OCCT_LIBS, SLIC3R_CAD gate): scripts/CAD/rig_build_traps.md
|
||||
set -euo pipefail
|
||||
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# orcacad-deps, NOT snapmaker-deps: this fork is mainline-based and needs Eigen 5.0.1,
|
||||
# CGAL 6.2.1, wx 3.3.2 and Python 3.12 Development.Embed, none of which snapmaker-deps has.
|
||||
# With the wrong image CMake dies at configure, which is exactly why this fork went
|
||||
# M1-M8 without ever compiling (see commit 1633005bba).
|
||||
IMAGE="${IMAGE:-orcacad-deps}"
|
||||
# Must NOT default to snapmaker_buildcache: that is the other fork's volume, and pointing
|
||||
# this fork at it makes the two silently trade build artefacts. build-gui-incremental.sh had the
|
||||
# identical defect and was fixed to orcacad_buildcache; this script was missed.
|
||||
VOL="${BUILD_VOL:-orcacad_kerneltest}"
|
||||
# No exclusions. Both cases that used to be quarantined now run: the solver SIGABRT on
|
||||
# circle-line tangency is fixed (tkz), and the internal-thread case turned out to have
|
||||
# correct geometry and a wrong reference in the test (kzy). A green run here now means
|
||||
# the whole CAD suite passed, not "everything except the two we gave up on".
|
||||
#
|
||||
# ...and that claim was still not true, because the default tag was [CadDocument] alone while
|
||||
# four CAD test files carry their own tags and NOTHING ELSE selected them. test_sketchinference
|
||||
# ([inference], 15), test_sketchedit ([SketchEdit], 23), test_sketchconstraints
|
||||
# ([SketchConstraints], 8) and test_sketchimport ([SketchImport], 4) never ran here, nor did the
|
||||
# older [slvs]-only cases in test_slvs_constraints. Measured 2026-08-31: the default reported
|
||||
# 2624 assertions / 206 cases, the full set 7648 / 264 -- so the gate was speaking for about a
|
||||
# third of the assertions, and a whole file could be added, tagged by its own convention, and
|
||||
# stay dark while the suite printed green. All 58 were passing; the coverage was simply never
|
||||
# exercised. Adding a tag here is now part of adding a test file.
|
||||
TAGS="${TAGS:-[CadDocument],[inference],[SketchEdit],[SketchConstraints],[SketchImport],[slvs]}"
|
||||
HOST=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--vol) VOL="$2"; shift 2 ;;
|
||||
--tags) TAGS="$2"; shift 2 ;;
|
||||
--image) IMAGE="$2"; shift 2 ;;
|
||||
--host) HOST="$2"; shift 2 ;;
|
||||
*) echo "unknown arg: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "REPO=$REPO IMAGE=$IMAGE VOL=$VOL TAGS=$TAGS HOST=${HOST:-local}"
|
||||
|
||||
if [[ -n "$HOST" ]]; then
|
||||
# Stage per-volume so parallel workers never share a remote tree.
|
||||
REMOTE="kt-$VOL" # relative: ssh and rsync both start in the remote home dir
|
||||
# SC2029: $REMOTE expanding on the CLIENT is the point -- it is derived from $VOL here,
|
||||
# and the remote has no such variable. The rsync destination below expands it the same way.
|
||||
# shellcheck disable=SC2029
|
||||
ssh "$HOST" "mkdir -p $REMOTE"
|
||||
# Only the inputs the build reads. --delete keeps a stale file from a prior worker from
|
||||
# silently compiling in.
|
||||
rsync -a --delete \
|
||||
"$REPO/src" "$REPO/tests" "$REPO/resources" "$REPO/cmake" "$REPO/scripts" \
|
||||
"$REPO/CMakeLists.txt" \
|
||||
"$HOST:$REMOTE/"
|
||||
exec ssh "$HOST" "cd $REMOTE && scripts/CAD/run-kernel-tests.sh --vol '$VOL' --tags '$TAGS' --image '$IMAGE'"
|
||||
fi
|
||||
|
||||
if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
|
||||
echo "FATAL: image '$IMAGE' not present locally. Either transfer it, or pass" >&2
|
||||
echo " --host <user@host> to build where the image already exists." >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
# A private volume is always built CLEAN on first use. Cloning a warm cache from another
|
||||
# tree looks tempting but is a correctness trap: rsync preserves source mtimes, so ninja
|
||||
# compares foreign object timestamps against them, decides everything is up to date, and
|
||||
# relinks stale objects. That produced a binary with NO [CadDocument] tests at all while
|
||||
# reporting success -- a green run that tested nothing. Pay the one-off full build instead;
|
||||
# incremental rebuilds within a volume are correct because the mtimes then share a lineage.
|
||||
if ! docker volume inspect "$VOL" >/dev/null 2>&1; then
|
||||
echo "=== $VOL: new volume, clean configure + full build (one-off, slow) ==="
|
||||
docker volume create "$VOL" >/dev/null
|
||||
fi
|
||||
|
||||
# tests/ is mounted too -- unlike build-gui-incremental.sh, this script exists precisely to
|
||||
# compile tests being edited. CMakeLists.txt and cmake/ carry the SLIC3R_CAD gate; taking
|
||||
# them from the baked image instead leaves the gate off and the CAD symbols vanish.
|
||||
|
||||
# ---- OOM guard (2026-08-21) -------------------------------------------------------------
|
||||
# Two of these builds ran at once on 2026-08-21, each with ninja -j$(nproc)=16: ~36 cc1plus
|
||||
# holding 42 GB of a 62 GB box -> global OOM at 21:05, a 2h28m kill storm, ssh unreachable,
|
||||
# lightdm destroyed. Neither build produced a single object. scripts/CAD/build-gui.sh grew the
|
||||
# bounds first; every script that starts a compile needs the same three, or the guard is only
|
||||
# as strong as the script you happened not to use.
|
||||
# flock — the lock path is SHARED with build-gui.sh and the other fork on purpose, so
|
||||
# concurrent builds serialise instead of summing.
|
||||
# -j — bounded parallelism; ~1.17 GB per cc1plus was the measured average.
|
||||
# --memory — the actual guarantee: a runaway build dies in its own cgroup instead of taking
|
||||
# the host down. --memory-swap equal to --memory forbids swap, which is what made
|
||||
# ssh hang.
|
||||
JOBS="${JOBS:-12}"
|
||||
MEM="${MEM:-40g}"
|
||||
LOCK=/tmp/orca-rig-build.lock
|
||||
|
||||
exec 9>"$LOCK"
|
||||
if ! flock -n 9; then
|
||||
echo "another build holds $LOCK — waiting (this is the OOM guard, not a hang)"
|
||||
flock 9
|
||||
fi
|
||||
|
||||
docker run --rm \
|
||||
--memory="$MEM" --memory-swap="$MEM" \
|
||||
-v "$REPO/src":/OrcaSlicer/src \
|
||||
-v "$REPO/tests":/OrcaSlicer/tests \
|
||||
-v "$REPO/resources":/OrcaSlicer/resources \
|
||||
-v "$REPO/CMakeLists.txt":/OrcaSlicer/CMakeLists.txt \
|
||||
-v "$REPO/cmake":/OrcaSlicer/cmake \
|
||||
-v "$REPO/deps_src":/OrcaSlicer/deps_src \
|
||||
-v "$VOL":/OrcaSlicer/build \
|
||||
"$IMAGE" \
|
||||
bash -lc "set -e
|
||||
cd /OrcaSlicer
|
||||
DESTDIR=/OrcaSlicer/deps/build/destdir/usr/local
|
||||
export PATH=\$DESTDIR/bin:\$PATH # wx-config, and anything else the deps prefix ships
|
||||
# Configure unconditionally. Guarding on 'CMakeCache.txt exists' is wrong: a FAILED
|
||||
# configure still writes that file, so the guard then skips reconfiguring forever and
|
||||
# every later run reuses a poisoned cache while ignoring corrected flags. A no-op
|
||||
# reconfigure costs seconds; that bug costs an afternoon.
|
||||
# SLIC3R_GTK=3 and BUILD_TESTS=ON are not optional extras: src/CMakeLists.txt turns
|
||||
# SLIC3R_GTK into 'wx-config --toolkit=gtk<N>', so omitting it asks for toolkit 'gtk'
|
||||
# and no wx build matches -> 'Could NOT find wxWidgets'. BUILD_TESTS=ON is what makes
|
||||
# the libslic3r_tests target exist at all. build_linux.sh sets both (lines 218, 226).
|
||||
cmake -S . -B build -G 'Ninja Multi-Config' \
|
||||
-DCMAKE_PREFIX_PATH=\$DESTDIR \
|
||||
-DwxWidgets_CONFIG_EXECUTABLE=\$DESTDIR/bin/wx-config \
|
||||
-DSLIC3R_GTK=3 -DBUILD_TESTS=ON -DSLIC3R_GUI=OFF \
|
||||
-DSLIC3R_CAD=ON -DSLIC3R_STATIC=1 -DORCA_TOOLS=ON -DCMAKE_BUILD_TYPE=Release
|
||||
# SLIC3R_GUI=OFF: this script builds ONLY libslic3r_tests, which links libslic3r and no GUI
|
||||
# code, but cmake still PROCESSES the if SLIC3R_GUI block of src/CMakeLists.txt (lines 16-98)
|
||||
# and every find_package inside it. That made the kernel suite depend on the GUI dependency
|
||||
# set for no benefit, and it broke the moment upstream added wxInspector as a REQUIRED
|
||||
# find_package at line 92: the orcacad-deps image predates it, so configure died pointing at
|
||||
# src/CMakeLists.txt:92 while nothing about the kernel had changed. Turning the block off is
|
||||
# not a workaround for that one dependency; it is the kernel suite finally declaring what it
|
||||
# actually needs, so the next GUI-side dependency upstream adds cannot break it either.
|
||||
cmake --build build --config Release --target libslic3r_tests -- -j$JOBS
|
||||
./build/tests/libslic3r/Release/libslic3r_tests '$TAGS' --order decl"
|
||||
|
|
@ -1,148 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Bring the headless GUI up on a VNC-served X display, ready to drive or to attach Remmina to.
|
||||
#
|
||||
# Runs INSIDE the long-lived GUI container (see the header of scripts/CAD/build-gui-incremental.sh for how
|
||||
# that container is created). Idempotent: safe to re-run to recover a session whose app died.
|
||||
#
|
||||
# docker exec <container> /OrcaSlicer/scripts/CAD/start-headless-gui.sh # launch + settle
|
||||
# docker exec <container> /OrcaSlicer/scripts/CAD/start-headless-gui.sh --status # report, change nothing
|
||||
#
|
||||
# WHY THIS EXISTS. Dismissing the first-run dialogs by computing the titlebar close box from
|
||||
# `xdotool getwindowgeometry --shell` and clicking it went wrong whenever the dialog had already
|
||||
# closed: the eval left the geometry variables stale or empty, the click landed at a garbage
|
||||
# coordinate, and it repeatedly hit the Sketch button in the toolbar underneath, so the app came up
|
||||
# in sketch mode with a stray Sketch feature. Three of those in one session.
|
||||
#
|
||||
# The titlebar click is nevertheless the RIGHT mechanism and is kept. `xdotool windowclose` looks
|
||||
# cleaner but kills the app: it destroys the GdkWindow out from under the dialog and the process
|
||||
# dies with "GdkWindow unexpectedly destroyed", three GLib-GObject criticals and a segfault
|
||||
# (measured 2026-07-30). Escape does not close the Setup Wizard either. So the fix is not a
|
||||
# different mechanism, it is refusing to click on geometry we have not validated.
|
||||
set -euo pipefail
|
||||
|
||||
DISP="${DISP:-:11}"
|
||||
GEOM="${GEOM:-1920x1080}"
|
||||
BIN="${BIN:-/OrcaSlicer/build/src/Release/orca-slicer}"
|
||||
# Packaging cannot bundle python (the deps python layer carries a doubled-DESTDIR RUNPATH), so the
|
||||
# build-tree binary needs the deps libpython on the path. Packaging-only issue; the app runs fine.
|
||||
LIBPY="/OrcaSlicer/deps/build/destdir/usr/local/libpython/lib"
|
||||
LIBPY2="/OrcaSlicer/build/src/Release/python/lib"
|
||||
LOG="${LOG:-/tmp/gui-session.log}"
|
||||
|
||||
export DISPLAY="$DISP" HOME=/root
|
||||
export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
# The ladders read the document back through the MCP socket, and the offer ladder's only
|
||||
# instrument is the [OFFER] keytrace. Neither is on by default, and a session launched without
|
||||
# them comes up looking perfectly healthy: the window is there, status says app up, and every
|
||||
# ladder then dies on "Connection refused" — which reads as a dead app rather than a rig that was
|
||||
# started without its instrument. The script that launches the rig is where they belong.
|
||||
export ORCA_CAD_MCP="${ORCA_CAD_MCP:-/tmp/mcp.sock}"
|
||||
export ORCA_CAD_KEYTRACE="${ORCA_CAD_KEYTRACE:-1}"
|
||||
export LD_LIBRARY_PATH="$LIBPY:$LIBPY2:${LD_LIBRARY_PATH:-}"
|
||||
mkdir -p /root/.config # startup dies in boost::filesystem::create_directory without this
|
||||
|
||||
# Skip zombies. This container accumulates <defunct> instances of the app across runs, and pgrep
|
||||
# matches them, so the naive "first match" reported a dead pid as if the session were healthy.
|
||||
app_pid() {
|
||||
local p
|
||||
for p in $(pgrep -f "$(basename "$BIN")" 2>/dev/null); do
|
||||
[ "$(awk "{print \$3}" "/proc/$p/stat" 2>/dev/null)" = "Z" ] && continue
|
||||
echo "$p"; return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
status() {
|
||||
echo "display : $(pgrep -f "Xvfb $DISP" >/dev/null && echo up || echo DOWN)"
|
||||
echo "wm : $(pgrep -x openbox >/dev/null && echo up || echo DOWN)"
|
||||
if pgrep -x x11vnc >/dev/null; then echo "vnc : up on :5900"
|
||||
elif ! command -v x11vnc >/dev/null; then echo "vnc : n/a (x11vnc not installed here)"
|
||||
else echo "vnc : DOWN"; fi
|
||||
local p; p="$(app_pid || true)"
|
||||
echo "app : ${p:-DOWN}"
|
||||
# WHICH binary is on screen, not just that something is. A pid alone cannot tell you whether
|
||||
# you are looking at the build you just linked or one from last week, and that is precisely
|
||||
# the question every rig verification is asking.
|
||||
[ -n "${p:-}" ] && echo "binary : $(readlink -f "/proc/$p/exe" 2>/dev/null || echo unknown)"
|
||||
[ -n "${p:-}" ] && echo "windows : $(xdotool search --name . getwindowname %@ 2>/dev/null | paste -sd'|' -)"
|
||||
return 0
|
||||
}
|
||||
|
||||
[ "${1:-}" = "--status" ] && { status; exit 0; }
|
||||
|
||||
# --- desktop: Xvfb, a window manager, and the VNC server ------------------------------------
|
||||
# openbox is REQUIRED: without it xdotool windowactivate aborts with "windowmanager claims not to
|
||||
# support _NET_ACTIVE_WINDOW" and dialogs never take focus.
|
||||
pgrep -f "Xvfb $DISP" >/dev/null || { nohup Xvfb "$DISP" -screen 0 "${GEOM}x24" -nolisten tcp >/tmp/xvfb.log 2>&1 & sleep 3; }
|
||||
pgrep -x openbox >/dev/null || { nohup openbox >/tmp/openbox.log 2>&1 & sleep 1; }
|
||||
if ! pgrep -x x11vnc >/dev/null && command -v x11vnc >/dev/null; then
|
||||
AUTH=()
|
||||
[ -f /root/.vnc/passwd ] && AUTH=(-rfbauth /root/.vnc/passwd)
|
||||
nohup x11vnc -display "$DISP" -rfbport 5900 "${AUTH[@]}" -forever -shared -noxdamage \
|
||||
>/tmp/x11vnc.log 2>&1 &
|
||||
sleep 2
|
||||
fi
|
||||
|
||||
# --- app ------------------------------------------------------------------------------------
|
||||
# Kill by BASENAME, not by "$BIN". The app enforces a single instance, so an older copy launched
|
||||
# from a DIFFERENT path (the packaged build/package/bin/ one, say, when BIN points at the freshly
|
||||
# linked build/src/Release/ one) survives a path-matched pkill, keeps the instance lock, and the
|
||||
# new process exits seconds after loading fonts — leaving no error anywhere. app_pid() below has
|
||||
# always matched by basename, so status then reported that stale process as a healthy session:
|
||||
# the launch looked green while the window on screen was days old. Measured 2026-08-02, where it
|
||||
# nearly passed a UI change against a Jul-30 binary. The killer and the reporter must agree on
|
||||
# what counts as "the app".
|
||||
pkill -9 -f "$(basename "$BIN")" 2>/dev/null || true
|
||||
sleep 2
|
||||
nohup "$BIN" >"$LOG" 2>&1 &
|
||||
echo "launched $(basename "$BIN") pid $!"
|
||||
|
||||
# Wait for the main window rather than sleeping a fixed amount: cold starts vary a lot under
|
||||
# software GL, and a fixed sleep either wastes time or races.
|
||||
for _ in $(seq 1 40); do
|
||||
xdotool search --name "Untitled" >/dev/null 2>&1 && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# --- first-run dialogs ----------------------------------------------------------------------
|
||||
# Click the titlebar close box, but only on geometry we have just read for a window that still
|
||||
# exists, and only if the resulting point is inside the screen. Every variable is unset first so a
|
||||
# failed read cannot leave the previous dialog's numbers behind — that is the whole bug.
|
||||
screen_w="${GEOM%x*}"; screen_h="${GEOM#*x}"
|
||||
close_dialog() {
|
||||
local name="$1" id X Y WIDTH HEIGHT cx cy
|
||||
id="$(xdotool search --name "$name" 2>/dev/null | head -1 || true)"
|
||||
[ -z "$id" ] && return 1
|
||||
unset X Y WIDTH HEIGHT
|
||||
eval "$(xdotool getwindowgeometry --shell "$id" 2>/dev/null || true)"
|
||||
# All four must be present and numeric: an empty or stale read is how the stray click happened.
|
||||
for v in "${X:-}" "${Y:-}" "${WIDTH:-}" "${HEIGHT:-}"; do
|
||||
[[ "$v" =~ ^-?[0-9]+$ ]] || { echo " $name: unreadable geometry, not clicking"; return 1; }
|
||||
done
|
||||
cx=$((X + WIDTH - 11)); cy=$((Y - 31)) # openbox decoration: close box above the frame
|
||||
if [ "$cx" -lt 0 ] || [ "$cy" -lt 0 ] || [ "$cx" -ge "$screen_w" ] || [ "$cy" -ge "$screen_h" ]; then
|
||||
echo " $name: close box at ${cx},${cy} is off-screen, not clicking"; return 1
|
||||
fi
|
||||
echo " $name: closing via titlebar at ${cx},${cy}"
|
||||
xdotool mousemove "$cx" "$cy" click 1
|
||||
sleep 2
|
||||
return 0
|
||||
}
|
||||
# "Restore" is not a first-RUN dialog, it is a second-run one: killing the app mid-session leaves
|
||||
# unsaved items behind, and the next launch asks whether to restore them. It sits over the tab bar
|
||||
# with a modal grab, so every synthetic click afterwards lands on it and the ladder reports
|
||||
# geometry that never got drawn — that is the "success with no log" shape twice already.
|
||||
for name in "Setup Wizard" "New version" "Restore"; do
|
||||
for _ in 1 2 3; do close_dialog "$name" || break; done
|
||||
done
|
||||
|
||||
# --- main window ----------------------------------------------------------------------------
|
||||
main="$(xdotool search --name "Untitled" 2>/dev/null | head -1 || true)"
|
||||
if [ -n "$main" ]; then
|
||||
xdotool windowmove "$main" 0 0 windowsize "$main" "$screen_w" "$screen_h" 2>/dev/null || true
|
||||
xdotool windowactivate "$main" 2>/dev/null || true
|
||||
sleep 2
|
||||
fi
|
||||
|
||||
echo "--- session ---"
|
||||
status
|
||||
297
scripts/CAD/test_gen_offer_table.py
Normal file
297
scripts/CAD/test_gen_offer_table.py
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
#!/usr/bin/env python3
|
||||
"""The Design table generator's checks: every fault of an atlas is found and names its entry.
|
||||
|
||||
python3 scripts/CAD/test_gen_offer_table.py
|
||||
|
||||
Each case builds a small valid atlas, breaks one rule and looks for the fault that names the entry
|
||||
breaking it. The checked-in atlas must have none.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import gen_offer_table as gen # noqa: E402
|
||||
|
||||
|
||||
def block(params=None, **extra):
|
||||
"""A tool block with every key the generator requires."""
|
||||
b = {"access": "change", "ok_false": False, "summary": "Paint a body.", "details": "",
|
||||
"params": params if params is not None else [
|
||||
{"name": "shade", "type": "string", "default": "red", "enum": ["red", "blue"]},
|
||||
{"name": "body", "type": "integer", "default": -1}],
|
||||
"examples": [], "ids": False}
|
||||
b.update(extra)
|
||||
return b
|
||||
|
||||
|
||||
def atlas():
|
||||
"""One slot, two selections, a command with a block and a menu item (paint), and a second item (tint), a command with
|
||||
a handler only; each under its heading."""
|
||||
return {
|
||||
"slots": [{"id": "make", "label": "Make"}],
|
||||
"selections": [{"id": "none"}, {"id": "body_solid"}],
|
||||
"verbs": [
|
||||
{"id": "paint", "name": "Paint", "section": "Solid", "slot": "make", "key": None,
|
||||
"accepts": ["none", "body_solid"], "action": "btn:paint", "icon": "paint", "hint": "Paint the body",
|
||||
"tool": block()},
|
||||
{"id": "tint", "name": "Tint", "section": "Menu items", "slot": "make", "key": None, "accepts": ["body_solid"],
|
||||
"action": "btn:tint", "icon": "tint", "hint": "Tint the body"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def entry(A, vid):
|
||||
return next(v for v in A["verbs"] if v["id"] == vid)
|
||||
|
||||
|
||||
def item(vid, handler, **extra):
|
||||
v = {"id": vid, "name": vid.title(), "slot": "make", "key": None, "accepts": ["body_solid"],
|
||||
"action": handler, "icon": vid, "hint": "Do " + vid}
|
||||
v.update(extra)
|
||||
return v
|
||||
|
||||
|
||||
class Faults(unittest.TestCase):
|
||||
def assertFault(self, A, vid, words):
|
||||
"""A fault of A names entry `vid` and says `words`."""
|
||||
found = gen.faults(A)
|
||||
mine = [f for f in found if f.startswith(vid + ":")]
|
||||
self.assertTrue(any(words in f for f in mine), f"no fault of {vid} says {words!r}: {found}")
|
||||
|
||||
# --- the atlases that pass -------------------------------------------------------------------
|
||||
|
||||
def test_the_small_atlas_has_no_fault(self):
|
||||
self.assertEqual(gen.faults(atlas()), [])
|
||||
|
||||
def test_the_checked_in_atlas_has_no_fault(self):
|
||||
with open(gen.ATLAS, encoding="utf-8") as f:
|
||||
self.assertEqual(gen.faults(json.load(f)), [])
|
||||
|
||||
def test_a_folded_item_with_args_its_command_takes_passes(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
del entry(A, "tint")["section"]
|
||||
entry(A, "paint")["args"] = {"shade": "red"}
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_a_greyed_item_passes_whatever_its_id(self):
|
||||
A = atlas()
|
||||
del entry(A, "tint")["action"]
|
||||
del entry(A, "tint")["section"]
|
||||
entry(A, "tint")["id"] = "anything"
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_items_of_one_command_with_equal_args_and_one_handler_pass(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
del entry(A, "tint")["section"]
|
||||
A["verbs"].append(item("tint_again", "btn:tint", fold={"into": "paint", "args": {"shade": "blue"}}))
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_a_block_with_access_ui_passes(self):
|
||||
# A command that acts on what the tab has open, as design_confirm_tool and design_cancel_tool do.
|
||||
A = atlas()
|
||||
entry(A, "paint")["tool"]["access"] = "ui"
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_every_heading_passes(self):
|
||||
for heading in gen.SECTIONS:
|
||||
A = atlas()
|
||||
entry(A, "paint")["section"] = heading
|
||||
self.assertEqual(gen.faults(A), [], heading)
|
||||
|
||||
# --- a fold ----------------------------------------------------------------------------------
|
||||
|
||||
def test_a_fold_on_an_entry_with_no_handler(self):
|
||||
A = atlas()
|
||||
del entry(A, "tint")["action"]
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {}}
|
||||
self.assertFault(A, "tint", "fold needs a handler")
|
||||
|
||||
def test_a_fold_on_an_entry_with_a_block(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["tool"] = block()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {}}
|
||||
self.assertFault(A, "tint", "a folded item has no tool block")
|
||||
|
||||
def test_a_fold_that_is_no_object(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = "paint"
|
||||
self.assertFault(A, "tint", "fold must be an object")
|
||||
|
||||
def test_an_into_that_names_no_entry(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "nothing", "args": {}}
|
||||
self.assertFault(A, "tint", "names no entry")
|
||||
|
||||
def test_an_into_that_names_an_entry_with_no_block(self):
|
||||
A = atlas()
|
||||
A["verbs"].append(item("wash", "btn:wash", fold={"into": "tint", "args": {}}))
|
||||
self.assertFault(A, "wash", "has no tool block")
|
||||
|
||||
def test_an_into_that_names_a_folded_item(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
A["verbs"].append(item("wash", "btn:wash", fold={"into": "tint", "args": {}}))
|
||||
self.assertFault(A, "wash", "is itself a folded item")
|
||||
|
||||
# --- the arguments that choose an item -------------------------------------------------------
|
||||
|
||||
def test_a_folds_args_that_are_no_object(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": ["blue"]}
|
||||
self.assertFault(A, "tint", "args must be an object")
|
||||
|
||||
def test_a_folds_args_that_name_a_param_its_command_lacks(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"colour": "blue"}}
|
||||
self.assertFault(A, "tint", "'colour'")
|
||||
|
||||
def test_a_folds_args_that_give_a_value_the_enum_lacks(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "green"}}
|
||||
self.assertFault(A, "tint", "'green'")
|
||||
|
||||
def test_own_args_that_are_no_object(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["args"] = "red"
|
||||
self.assertFault(A, "paint", "args must be an object")
|
||||
|
||||
def test_own_args_that_name_a_param_the_block_lacks(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["args"] = {"colour": "red"}
|
||||
self.assertFault(A, "paint", "'colour'")
|
||||
|
||||
def test_own_args_that_give_a_value_the_enum_lacks(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["args"] = {"shade": "green"}
|
||||
self.assertFault(A, "paint", "'green'")
|
||||
|
||||
def test_two_items_of_one_command_with_equal_args_and_different_handlers(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
A["verbs"].append(item("wash", "btn:wash", fold={"into": "paint", "args": {"shade": "blue"}}))
|
||||
self.assertFault(A, "wash", "the same args as tint")
|
||||
|
||||
def test_an_items_args_equal_to_its_commands_own(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["args"] = {"shade": "blue"}
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
self.assertFault(A, "tint", "the args paint's own item takes")
|
||||
|
||||
def test_no_args_for_an_item_of_a_command_with_a_menu_item_of_its_own(self):
|
||||
# A call with none opens the command's own item.
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {}}
|
||||
self.assertFault(A, "tint", "the args paint's own item takes")
|
||||
|
||||
def test_own_args_on_an_entry_with_no_handler(self):
|
||||
A = atlas()
|
||||
A["verbs"].append({"id": "rinse", "name": "Rinse", "slot": None, "tool": block(), "args": {"shade": "red"}})
|
||||
self.assertFault(A, "rinse", "own args need a handler (action) and a tool block")
|
||||
|
||||
def test_own_args_on_an_entry_with_no_block(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["args"] = {"shade": "red"}
|
||||
self.assertFault(A, "tint", "own args need a handler (action) and a tool block")
|
||||
|
||||
def test_empty_own_args(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["args"] = {}
|
||||
self.assertFault(A, "paint", "own args {} are what a call with none gives")
|
||||
|
||||
# --- modes -----------------------------------------------------------------------------------
|
||||
|
||||
def test_items_of_one_command_in_different_modes(self):
|
||||
A = atlas()
|
||||
A["verbs"].append({"id": "rinse", "name": "Rinse", "slot": None, "tool": block()})
|
||||
entry(A, "tint")["fold"] = {"into": "rinse", "args": {"shade": "blue"}}
|
||||
A["verbs"].append(item("wash", "btn:wash", mode="sketch", fold={"into": "rinse", "args": {"shade": "red"}}))
|
||||
self.assertFault(A, "wash", "in another mode than tint")
|
||||
|
||||
def test_an_item_in_another_mode_than_its_commands_own_item(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["mode"] = "sketch"
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
self.assertFault(A, "tint", "in another mode than paint's own item")
|
||||
|
||||
# --- headings --------------------------------------------------------------------------------
|
||||
|
||||
def test_a_command_with_no_section(self):
|
||||
A = atlas()
|
||||
del entry(A, "tint")["section"]
|
||||
self.assertFault(A, "tint", "a command needs a section")
|
||||
|
||||
def test_a_section_outside_the_headings(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["section"] = "Painting"
|
||||
self.assertFault(A, "paint", "section 'Painting' is not one of")
|
||||
|
||||
def test_a_section_on_a_folded_item(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
self.assertFault(A, "tint", "is no command and has no section")
|
||||
|
||||
def test_a_section_on_a_greyed_item(self):
|
||||
A = atlas()
|
||||
del entry(A, "tint")["action"]
|
||||
self.assertFault(A, "tint", "is no command and has no section")
|
||||
|
||||
# --- the items that act on the Feature list's row --------------------------------------------
|
||||
|
||||
def test_feature_row_on_a_command_with_a_menu_item_of_its_own_passes(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["feature_row"] = True
|
||||
entry(A, "paint")["feature_row"] = True
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_feature_row_on_an_entry_with_no_handler(self):
|
||||
A = atlas()
|
||||
A["verbs"].append({"id": "rinse", "name": "Rinse", "section": "Solid", "slot": None, "tool": block(),
|
||||
"feature_row": True})
|
||||
self.assertFault(A, "rinse", "feature_row needs a menu item of its own")
|
||||
|
||||
def test_feature_row_on_a_folded_item(self):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
del entry(A, "tint")["section"]
|
||||
entry(A, "tint")["feature_row"] = True
|
||||
self.assertFault(A, "tint", "feature_row needs a menu item of its own")
|
||||
|
||||
# --- the operations a command reaches ---------------------------------------------------------
|
||||
|
||||
def test_operations_on_a_command_pass(self):
|
||||
A = atlas()
|
||||
entry(A, "paint")["operations"] = ["delete_objects"]
|
||||
entry(A, "tint")["operations"] = ["rename_object", "select_plate"]
|
||||
self.assertEqual(gen.faults(A), [])
|
||||
|
||||
def test_operations_on_a_folded_item(self):
|
||||
for ops in (["delete_objects"], None):
|
||||
with self.subTest(ops=ops):
|
||||
A = atlas()
|
||||
entry(A, "tint")["fold"] = {"into": "paint", "args": {"shade": "blue"}}
|
||||
del entry(A, "tint")["section"]
|
||||
entry(A, "tint")["operations"] = ops
|
||||
self.assertFault(A, "tint", "a folded or greyed item is no command")
|
||||
|
||||
def test_operations_that_are_no_list_of_names(self):
|
||||
for ops in ("delete_objects", [], [""], ["delete_objects,rename_object"], [3], None):
|
||||
with self.subTest(ops=ops):
|
||||
A = atlas()
|
||||
entry(A, "paint")["operations"] = ops
|
||||
self.assertFault(A, "paint", "operations is a list of the names")
|
||||
|
||||
# --- entries and blocks ----------------------------------------------------------------------
|
||||
|
||||
def test_an_entry_with_no_slot_no_handler_and_no_block(self):
|
||||
A = atlas()
|
||||
A["verbs"].append({"id": "nothing", "name": "Nothing", "slot": None})
|
||||
self.assertFault(A, "nothing", "neither a menu item, a handler (action) nor a tool block")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,93 +0,0 @@
|
|||
# Deps-only base image for fast iteration on Orca.
|
||||
# Identical system+pinned-dependency setup to scripts/Dockerfile, but STOPS after
|
||||
# `build_linux.sh -dr` (no slicer/AppImage build). Produces an image with the pinned
|
||||
# deps baked at /OrcaSlicer/deps/build/destdir, so the slicer can be rebuilt
|
||||
# incrementally via scripts/CAD/build-gui-incremental.sh without re-running the long deps build.
|
||||
#
|
||||
# Build once (rebuild only when deps/ changes, e.g. OCCT module flags):
|
||||
# docker build -t snapmaker-deps -f scripts/Dockerfile.deps .
|
||||
FROM docker.io/ubuntu:24.04
|
||||
LABEL maintainer="Orca CAD iteration base"
|
||||
|
||||
# Disable interactive package configuration
|
||||
RUN apt-get update && \
|
||||
echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
|
||||
|
||||
# Add a deb-src
|
||||
RUN echo deb-src http://archive.ubuntu.com/ubuntu \
|
||||
$(cat /etc/*release | grep VERSION_CODENAME | cut -d= -f2) main universe>> /etc/apt/sources.list
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
autoconf \
|
||||
build-essential \
|
||||
cmake \
|
||||
curl \
|
||||
eglexternalplatform-dev \
|
||||
extra-cmake-modules \
|
||||
file \
|
||||
git \
|
||||
gstreamer1.0-plugins-bad \
|
||||
gstreamer1.0-libav \
|
||||
libcairo2-dev \
|
||||
libcurl4-openssl-dev \
|
||||
libdbus-1-dev \
|
||||
libgstreamer1.0-dev \
|
||||
libgstreamerd-3-dev \
|
||||
libgstreamer-plugins-base1.0-dev \
|
||||
libgstreamer-plugins-good1.0-dev \
|
||||
libgtk-3-dev \
|
||||
libsecret-1-dev \
|
||||
libsoup2.4-dev \
|
||||
libssl3 \
|
||||
libssl-dev \
|
||||
libtool \
|
||||
libudev-dev \
|
||||
libwayland-dev \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libxkbcommon-dev \
|
||||
locales \
|
||||
locales-all \
|
||||
m4 \
|
||||
pkgconf \
|
||||
sudo \
|
||||
wayland-protocols \
|
||||
wget
|
||||
|
||||
ENV LC_ALL=en_US.utf8
|
||||
RUN locale-gen $LC_ALL
|
||||
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
COPY ./ OrcaSlicer
|
||||
WORKDIR OrcaSlicer
|
||||
|
||||
# System dependencies
|
||||
RUN ./build_linux.sh -u
|
||||
|
||||
# Pinned dependencies in ./deps (OCCT 7.6 with ModelingAlgorithms enabled, OpenCV,
|
||||
# Boost, wxWidgets, ...). This is the long step; it is baked into the image.
|
||||
# -j 12, not the default all-cores: on 2026-08-21 an unbounded deps build plus an unbounded
|
||||
# app build put 42 GB of cc1plus on a 62 GB box and OOM-killed the host for 2h28m. 12 keeps
|
||||
# the compile fast while leaving the machine usable. Pair with `docker build --memory`.
|
||||
RUN ./build_linux.sh -dr -j 12
|
||||
|
||||
# Compatibility symlink. This deps tree installs into deps/build/OrcaSlicer_dep/, while the
|
||||
# orcacad_buildcache volume was configured against the previous image, whose prefix was
|
||||
# deps/build/destdir/. Those paths are baked as absolute strings into the app's CMakeCache, so
|
||||
# without this symlink a rebuild on the new image reconfigures from scratch — hours of compile
|
||||
# to change one directory name. Same tree, two names.
|
||||
RUN ln -sfn /OrcaSlicer/deps/build/OrcaSlicer_dep /OrcaSlicer/deps/build/destdir
|
||||
|
||||
# The rig's GUI runtime. This used to arrive for free because orcacad-deps was layered on
|
||||
# snapmaker-deps; that lineage is Trap 1 in docs/rig_build_traps.md (a baked project(Snapmaker_Orca)
|
||||
# tree) and building from this Dockerfile is what removes it — along with the X stack the rig
|
||||
# needs. scripts/CAD/start-headless-gui.sh requires Xvfb and openbox (without a window manager `xdotool
|
||||
# windowactivate` aborts with "windowmanager claims not to support..."), drives the UI with
|
||||
# xdotool, and captures to /shots with scrot/ImageMagick. Same set snapmaker-deps carries.
|
||||
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
imagemagick \
|
||||
openbox \
|
||||
scrot \
|
||||
xauth \
|
||||
xdotool \
|
||||
xvfb \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
# Adds assimp to the orcacad-deps image.
|
||||
#
|
||||
# WHY THIS EXISTS. OrcaSlicer mainline gained `find_package(assimp REQUIRED)` in
|
||||
# src/libslic3r/CMakeLists.txt (glTF/GLB/FBX import for texture-to-colour), and the baked
|
||||
# orcacad-deps image predates it: the image's deps/ tree has no Assimp directory at all, and
|
||||
# nothing named assimp exists anywhere in it. On the host, deps/build/dep_Assimp-prefix has
|
||||
# only `patch` and `update` stamps -- no build, no install -- so the dependency was fetched
|
||||
# and then never built, in the image or out of it.
|
||||
#
|
||||
# The consequence was that scripts/CAD/run-kernel-tests.sh failed at CMake CONFIGURE time,
|
||||
# before a single source file compiled, so THIS FORK'S KERNEL SUITE COULD NOT RUN AT ALL.
|
||||
# Every kernel change ported here was parity-checked against Snapmaker and never independently
|
||||
# tested (w80c). The Snapmaker fork does not hit this: its base requires neither
|
||||
# assimp nor OpenCV.
|
||||
#
|
||||
# WHY A LAYER AND NOT A FULL DEPS REBUILD. Rebuilding every dependency takes hours and would
|
||||
# rewrite artifacts that are currently working. This adds exactly the one missing package on
|
||||
# top of the existing image, and it is a Dockerfile rather than a `docker commit` so that what
|
||||
# was done is reviewable and repeatable instead of being an undocumented mutation.
|
||||
#
|
||||
# The flags below are copied from the project's own recipe (deps/Assimp/Assimp.cmake) plus the
|
||||
# standard superbuild arguments from orcaslicer_add_cmake_project (deps/CMakeLists.txt:158) and
|
||||
# DEP_CMAKE_OPTS (deps/deps-linux.cmake). Keep them in step with that recipe: this file is a
|
||||
# stand-in for the superbuild, not an independent opinion about how to build assimp.
|
||||
#
|
||||
# BUILD (from the repo root, tarball already in deps/DL_CACHE/Assimp/):
|
||||
# docker build -f scripts/Dockerfile.deps-assimp -t orcacad-deps .
|
||||
#
|
||||
# VERIFY:
|
||||
# docker run --rm orcacad-deps sh -c \
|
||||
# 'ls /OrcaSlicer/deps/build/destdir/usr/local/lib/cmake/assimp*'
|
||||
# scripts/CAD/run-kernel-tests.sh
|
||||
#
|
||||
FROM orcacad-deps
|
||||
|
||||
# v5.4.3 is the version deps/Assimp/Assimp.cmake selects for CMake >= 3.22 (the image has
|
||||
# 3.28.3). The SHA256 is that recipe's URL_HASH, verified against the cached tarball before
|
||||
# this file was written -- an unverified archive is not a dependency, it is whatever was
|
||||
# sitting in the cache.
|
||||
ARG ASSIMP_SHA256=66dfbaee288f2bc43172440a55d0235dfc7bf885dda6435c038e8000e79582cb
|
||||
COPY deps/DL_CACHE/Assimp/v5.4.3.tar.gz /tmp/assimp.tar.gz
|
||||
|
||||
RUN set -eux; \
|
||||
echo "${ASSIMP_SHA256} /tmp/assimp.tar.gz" | sha256sum -c -; \
|
||||
mkdir -p /tmp/assimp-src && \
|
||||
tar -xzf /tmp/assimp.tar.gz -C /tmp/assimp-src --strip-components=1; \
|
||||
DESTDIR=/OrcaSlicer/deps/build/destdir/usr/local; \
|
||||
cmake -S /tmp/assimp-src -B /tmp/assimp-build -G Ninja \
|
||||
-DCMAKE_POLICY_VERSION_MINIMUM=3.10 \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX="$DESTDIR" \
|
||||
-DCMAKE_PREFIX_PATH="$DESTDIR" \
|
||||
-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
|
||||
-DBUILD_SHARED_LIBS=OFF \
|
||||
-DASSIMP_BUILD_USE_CCACHE=OFF \
|
||||
-DASSIMP_BUILD_TESTS=OFF \
|
||||
-DASSIMP_BUILD_SAMPLES=OFF \
|
||||
-DASSIMP_BUILD_ASSIMP_TOOLS=OFF \
|
||||
-DASSIMP_INSTALL_PDB=OFF \
|
||||
-DASSIMP_NO_EXPORT=ON \
|
||||
-DASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT=OFF \
|
||||
-DASSIMP_BUILD_GLTF_IMPORTER=ON \
|
||||
-DASSIMP_BUILD_OBJ_IMPORTER=ON \
|
||||
-DASSIMP_BUILD_FBX_IMPORTER=ON \
|
||||
-DASSIMP_BUILD_ZLIB=ON \
|
||||
-DASSIMP_WARNINGS_AS_ERRORS=OFF \
|
||||
-DBUILD_WITH_STATIC_CRT=OFF; \
|
||||
cmake --build /tmp/assimp-build --target install -- -j"$(nproc)"; \
|
||||
rm -rf /tmp/assimp-src /tmp/assimp-build /tmp/assimp.tar.gz; \
|
||||
test -n "$(ls "$DESTDIR"/lib/cmake/assimp* 2>/dev/null)"
|
||||
|
|
@ -122,7 +122,7 @@ modules:
|
|||
# No branch and no tag: flatpak-builder checks that a named branch's tip is the pinned
|
||||
# commit, which fails once the fork's branch moves past it. With the commit alone it
|
||||
# fetches as much history as the commit needs on its own.
|
||||
commit: b44c39c100975a0ac0e46f937aa3f3eae5e18631
|
||||
commit: 89844cb1f80b17a5916d5274cd88317cac3e2a3c
|
||||
|
||||
# OrcaSlicer C++ dependencies (built offline with pre-downloaded archives)
|
||||
- name: orca_deps
|
||||
|
|
@ -416,7 +416,7 @@ modules:
|
|||
# this build uses the default Makefile generator, so it is not available here.)
|
||||
- cmake --build build_flatpak -j"${FLATPAK_BUILDER_N_JOBS:-$(nproc)}" --target
|
||||
libslic3r_tests fff_print_tests sla_print_tests libnest2d_tests slic3rutils_tests
|
||||
filament_group_tests
|
||||
automation_tests filament_group_tests
|
||||
|
||||
cleanup:
|
||||
- /include
|
||||
|
|
|
|||
|
|
@ -257,6 +257,13 @@ echo "Comparing against $BASE"
|
|||
|
||||
# --- Run ----------------------------------------------------------------------
|
||||
|
||||
# Apple's compiler finds the macOS SDK through xcrun, so the compile database names
|
||||
# none; any other clang-tidy, such as the pinned one, finds it through SDKROOT.
|
||||
if [ "$OS" = Darwin ] && [ -z "${SDKROOT:-}" ]; then
|
||||
SDKROOT=$(xcrun --show-sdk-path)
|
||||
export SDKROOT
|
||||
fi
|
||||
|
||||
args=(-p "$BUILD_DIR" --base "$BASE" --clang-tidy "$CLANG_TIDY")
|
||||
[ -n "$JOBS" ] && args+=(-j "$JOBS")
|
||||
[ "$FIX" = 1 ] && args+=(-- --fix)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ find_package(libnoise REQUIRED)
|
|||
add_subdirectory(libslic3r)
|
||||
|
||||
if (SLIC3R_GUI)
|
||||
# Before wxWidgets is found, so the automation core builds without wx (see its CMakeLists.txt).
|
||||
add_subdirectory(libslic3r_automation)
|
||||
add_subdirectory(glad)
|
||||
# imgui, imguizmo, and hidapi are now included from deps_src
|
||||
add_subdirectory(libvgcode)
|
||||
|
|
|
|||
|
|
@ -168,7 +168,10 @@ using json = nlohmann::json;
|
|||
#endif
|
||||
|
||||
#ifdef SLIC3R_GUI
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/GUI_Init.hpp"
|
||||
#include "slic3r/GUI/Mcp/McpStdioBridge.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
// BBLPrinterAgent::from_orca_filament_id(); the map and its lookups live in libslic3r_gui,
|
||||
// which only a SLIC3R_GUI build links (see target_link_libraries(OrcaSlicer libslic3r_gui)
|
||||
// in CMakeLists).
|
||||
|
|
@ -1218,6 +1221,15 @@ int CLI::run(int argc, char **argv)
|
|||
// Save the thread ID of the main thread.
|
||||
save_main_thread_id();
|
||||
|
||||
#ifdef SLIC3R_GUI
|
||||
// The stdio bridge is a plain pipe to a running GUI instance; it needs none of the setup below.
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::strcmp(argv[i], "--mcp-stdio") == 0)
|
||||
return Slic3r::GUI::Mcp::run_stdio_bridge(argc, argv, []() -> const Slic3r::GUI::CommandCatalog& {
|
||||
return Slic3r::GUI::NativeCommands::instance();
|
||||
});
|
||||
#endif
|
||||
|
||||
#ifdef __WXGTK__
|
||||
// ------------------------------------------------------------------
|
||||
// Linux backend selection — runtime, based on GDK_BACKEND env var.
|
||||
|
|
@ -1499,6 +1511,14 @@ int CLI::run(int argc, char **argv)
|
|||
}
|
||||
|
||||
bool start_gui = m_actions.empty() && !downward_check;
|
||||
// --run runs its file in the GUI, so it is refused where no GUI starts rather than left unrun.
|
||||
if (!start_gui && m_given_option_keys.count("run") > 0) {
|
||||
std::string flag = m_actions.empty() ? std::string("downward_check") : m_actions.front();
|
||||
std::replace(flag.begin(), flag.end(), '_', '-');
|
||||
boost::nowide::cerr << "--run cannot be combined with --" << flag << std::endl;
|
||||
record_exit_reson(outfile_dir, CLI_INVALID_PARAMS, 0, cli_errors[CLI_INVALID_PARAMS], sliced_info);
|
||||
flush_and_exit(CLI_INVALID_PARAMS);
|
||||
}
|
||||
if (start_gui) {
|
||||
BOOST_LOG_TRIVIAL(info) << "no action, start gui directly" << std::endl;
|
||||
#ifdef SLIC3R_GUI
|
||||
|
|
@ -1542,6 +1562,22 @@ int CLI::run(int argc, char **argv)
|
|||
//BBS: remove GCodeViewer as separate APP logic
|
||||
//params.start_as_gcodeviewer = start_as_gcodeviewer;
|
||||
|
||||
// --mcp-port opens the endpoint as --mcp does, whatever its value. Every option has a value after setup(),
|
||||
// so whether it was given is read from the options the command line named.
|
||||
if (const auto *opt = m_config.opt<ConfigOptionBool>("mcp"))
|
||||
params.mcp.enable = opt->value;
|
||||
if (m_given_option_keys.count("mcp_port") > 0)
|
||||
params.mcp.enable = true;
|
||||
if (const auto *opt = m_config.opt<ConfigOptionInt>("mcp_port"))
|
||||
params.mcp.port = opt->value;
|
||||
// Resolved now: the GUI moves the working directory to <data_dir>/log before the replay or script runs.
|
||||
if (m_given_option_keys.count("run") > 0) {
|
||||
params.mcp.run_file = resolve_cli_input_path(m_config.opt_string("run"));
|
||||
params.mcp.run_out = resolve_cli_input_path(m_config.opt_string("outputdir"));
|
||||
}
|
||||
params.unrestricted_scripts = m_config.opt_bool("unrestricted_scripts");
|
||||
params.cad = m_config.opt_bool("cad");
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "begin to launch OrcaSlicer GUI soon";
|
||||
return Slic3r::GUI::GUI_Run(params);
|
||||
#else // SLIC3R_GUI
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
#include <Standard_TypeDef.hxx>
|
||||
#include <TopAbs_State.hxx>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
|
||||
#include <Standard_Failure.hxx>
|
||||
#include <BRepBuilderAPI_MakeWire.hxx>
|
||||
|
|
@ -89,6 +90,7 @@
|
|||
#include <math.h>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
|
@ -114,19 +116,30 @@ namespace Slic3r {
|
|||
|
||||
// ---- helical-thread construction helpers (file-local) ----------------------
|
||||
|
||||
// Helix spine on a cylinder (radius/pitch/height) about `axis`, as a wire.
|
||||
// Helix spine on a cylinder (radius/pitch/height) about `axis`, as a wire of edges of at most one
|
||||
// turn each, all the same length. A thread swept along it has a face per edge, and a face that
|
||||
// winds round several turns is what OCCT's face/face intersection cannot be trusted with: cutting a
|
||||
// thread swept along a single many-turn edge from a bore intermittently loses a piece of the
|
||||
// helical curve where the groove meets the wall, and the cut then reports success having removed
|
||||
// nothing. Which placements fail depends only on round-off, so a bore that threads at one spot on
|
||||
// the bed would fail a few millimetres away. Faces of under one turn intersect reliably.
|
||||
static TopoDS_Wire make_helix_wire(const gp_Ax3& axis, double radius,
|
||||
double pitch, double height)
|
||||
{
|
||||
Handle(Geom_CylindricalSurface) cyl = new Geom_CylindricalSurface(axis, radius);
|
||||
double turns = (pitch > 1e-6) ? (height / pitch) : 1.0;
|
||||
// In the surface (u,v) parametrization u is the angle, v the axial height.
|
||||
gp_Pnt2d p0(0.0, 0.0);
|
||||
gp_Pnt2d p1(2.0 * M_PI * turns, height);
|
||||
Handle(Geom2d_TrimmedCurve) seg = GC_MakeSegment2d(p0, p1);
|
||||
TopoDS_Edge e = BRepBuilderAPI_MakeEdge(seg, cyl).Edge();
|
||||
BRepLib::BuildCurves3d(e);
|
||||
return BRepBuilderAPI_MakeWire(e).Wire();
|
||||
const int n = std::max(1, int(std::ceil(turns - 1e-9)));
|
||||
BRepBuilderAPI_MakeWire wire;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const double t0 = double(i) / n, t1 = double(i + 1) / n;
|
||||
Handle(Geom2d_TrimmedCurve) seg = GC_MakeSegment2d(gp_Pnt2d(2.0 * M_PI * turns * t0, height * t0),
|
||||
gp_Pnt2d(2.0 * M_PI * turns * t1, height * t1));
|
||||
TopoDS_Edge e = BRepBuilderAPI_MakeEdge(seg, cyl).Edge();
|
||||
BRepLib::BuildCurves3d(e);
|
||||
wire.Add(e); // joins it to the previous edge's end, the same point on the cylinder
|
||||
}
|
||||
return wire.Wire();
|
||||
}
|
||||
|
||||
// Helix spine from a CadFeature's helix params. Supports cylindrical (taper==0)
|
||||
|
|
@ -458,11 +471,8 @@ evaluate_variables(const std::map<std::string, std::string>& variables)
|
|||
return done;
|
||||
}
|
||||
|
||||
// Write `value` into the CadFeature numeric field named `field`. Allow-list of
|
||||
// the geometric dimension fields a variable realistically drives. Integer-valued
|
||||
// fields are rounded. Throws std::runtime_error("unknown parameter: " + field)
|
||||
// for anything not in the list.
|
||||
static void assign_field(CadFeature& f, const std::string& field, double value)
|
||||
// The allow-list is the geometric dimensions a variable realistically drives.
|
||||
void CadDocument::set_numeric_field(CadFeature& f, const std::string& field, double value)
|
||||
{
|
||||
// double fields (alphabetical)
|
||||
if (field == "bool_tolerance") { f.bool_tolerance = value; return; }
|
||||
|
|
@ -531,7 +541,7 @@ bool CadDocument::produces_body(CadFeatureType t)
|
|||
bool CadDocument::is_bindable_field(const std::string& field)
|
||||
{
|
||||
CadFeature probe;
|
||||
try { assign_field(probe, field, 0.0); return true; }
|
||||
try { set_numeric_field(probe, field, 0.0); return true; }
|
||||
catch (const std::exception&) { return false; }
|
||||
}
|
||||
|
||||
|
|
@ -871,7 +881,7 @@ bool CadDocument::solve_sketch_feature(int index)
|
|||
case SketchConstraintType::EqualLength: if ((valid = ok_idx({c.a, c.b, c.c, c.d}))) sc.equal_length(c.a, c.b, c.c, c.d); break;
|
||||
case SketchConstraintType::Parallel: if ((valid = ok_idx({c.a, c.b, c.c, c.d}))) sc.parallel(c.a, c.b, c.c, c.d); break;
|
||||
case SketchConstraintType::Perpendicular:if ((valid = ok_idx({c.a, c.b, c.c, c.d}))) sc.perpendicular(c.a, c.b, c.c, c.d); break;
|
||||
// The legacy solver implements these too; they used to be dropped without a word.
|
||||
// The legacy solver implements these too, so they are passed on, not dropped.
|
||||
case SketchConstraintType::Midpoint: if ((valid = ok_idx({c.a, c.b, c.c}))) sc.midpoint(c.a, c.b, c.c); break;
|
||||
case SketchConstraintType::Symmetric: if ((valid = ok_idx({c.a, c.b, c.c, c.d}))) sc.symmetric(c.a, c.b, c.c, c.d); break;
|
||||
case SketchConstraintType::Angle: if ((valid = ok_idx({c.a, c.b, c.c, c.d}))) sc.angle(c.a, c.b, c.c, c.d, c.value); break;
|
||||
|
|
@ -1399,35 +1409,63 @@ int CadDocument::add_project_edges(int source_body, const std::vector<int>& edge
|
|||
return int(features.size()) - 1;
|
||||
}
|
||||
|
||||
std::vector<SketchEntity> CadDocument::project_edges_on(const SketchPlane& plane, int source_body,
|
||||
const std::vector<int>& edge_ids, int face,
|
||||
std::string& error) const
|
||||
{
|
||||
error.clear();
|
||||
const int nb = int(bodies.size());
|
||||
const std::string body = "body " + std::to_string(source_body);
|
||||
if (source_body < 0 || source_body >= nb) {
|
||||
error = body + " does not exist; the model has " + std::to_string(nb) + (nb == 1 ? " body" : " bodies");
|
||||
return {};
|
||||
}
|
||||
const TopoDS_Shape& shape = bodies[source_body].shape;
|
||||
if (shape.IsNull()) {
|
||||
error = body + " has no shape";
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<TopoDS_Edge> edges;
|
||||
if (!edge_ids.empty()) {
|
||||
for (int id : edge_ids) {
|
||||
TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id);
|
||||
if (e.IsNull()) {
|
||||
error = "edge " + std::to_string(id) + " of " + body + " does not exist (it has " +
|
||||
std::to_string(GeometryEngine::edge_count(shape)) + " edges)";
|
||||
return {};
|
||||
}
|
||||
edges.push_back(e);
|
||||
}
|
||||
} else if (face >= 0) {
|
||||
TopoDS_Face fc = GeometryEngine::face_by_index(shape, face);
|
||||
if (fc.IsNull()) {
|
||||
error = "face " + std::to_string(face) + " of " + body + " does not exist (it has " +
|
||||
std::to_string(GeometryEngine::face_count(shape)) + " faces)";
|
||||
return {};
|
||||
}
|
||||
edges = GeometryEngine::edges_of_face(fc);
|
||||
} else {
|
||||
edges = GeometryEngine::edges_of(shape);
|
||||
}
|
||||
|
||||
std::vector<SketchEntity> out;
|
||||
project_edges_to_entities(edges, plane, /*construction=*/true, out);
|
||||
if (out.empty()) error = "the edges project to a point on the plane: each is perpendicular to it";
|
||||
return out;
|
||||
}
|
||||
|
||||
int CadDocument::project_edges_into_sketch(int sketch_feature, int source_body,
|
||||
const std::vector<int>& edge_ids, int face)
|
||||
{
|
||||
if (sketch_feature < 0 || sketch_feature >= int(features.size())) return -1;
|
||||
CadFeature& sk = features[sketch_feature];
|
||||
if (sk.type != CadFeatureType::Sketch && sk.type != CadFeatureType::Project) return -1;
|
||||
if (source_body < 0 || source_body >= int(bodies.size())
|
||||
|| bodies[source_body].shape.IsNull()) return -1;
|
||||
const TopoDS_Shape& shape = bodies[source_body].shape;
|
||||
|
||||
std::vector<TopoDS_Edge> edges;
|
||||
if (!edge_ids.empty()) {
|
||||
for (int id : edge_ids) {
|
||||
TopoDS_Edge e = GeometryEngine::edge_by_index(shape, id);
|
||||
if (e.IsNull()) return -1;
|
||||
edges.push_back(e);
|
||||
}
|
||||
} else if (face >= 0) {
|
||||
TopoDS_Face fc = GeometryEngine::face_by_index(shape, face);
|
||||
if (fc.IsNull()) return -1;
|
||||
edges = GeometryEngine::edges_of_face(fc);
|
||||
} else {
|
||||
edges = GeometryEngine::edges_of(shape);
|
||||
}
|
||||
if (edges.empty()) return -1;
|
||||
|
||||
const size_t before = sk.entities.size();
|
||||
project_edges_to_entities(edges, sk.plane, /*construction=*/true, sk.entities);
|
||||
return int(sk.entities.size() - before);
|
||||
std::string error;
|
||||
const std::vector<SketchEntity> ents = project_edges_on(sk.plane, source_body, edge_ids, face, error);
|
||||
if (ents.empty()) return -1;
|
||||
sk.entities.insert(sk.entities.end(), ents.begin(), ents.end());
|
||||
return int(ents.size());
|
||||
}
|
||||
|
||||
int CadDocument::add_bridge(int sketch_ref, int ent_a, int end_a, int ent_b, int end_b,
|
||||
|
|
@ -1650,6 +1688,95 @@ bool CadDocument::plane_of_face(int body_idx, int face_idx, SketchPlane& out) co
|
|||
return true;
|
||||
}
|
||||
|
||||
bool CadDocument::inward_plane_of_face(int body_idx, int face_idx, SketchPlane& out) const
|
||||
{
|
||||
if (face_idx < 0 || body_idx < 0 || body_idx >= int(bodies.size())) return false;
|
||||
const TopoDS_Face face = GeometryEngine::face_by_index(bodies[body_idx].shape, face_idx);
|
||||
if (face.IsNull()) return false;
|
||||
SketchPlane p;
|
||||
p.origin = GeometryEngine::face_centroid_world(face);
|
||||
p.normal = (-GeometryEngine::face_normal_world(face)).normalized(); // inward
|
||||
Vec3d x(0, 0, 0); double best = 0;
|
||||
for (const TopoDS_Edge& e : GeometryEngine::edges_of_face(face)) {
|
||||
const std::vector<Vec3d> pts = GeometryEngine::sample_edge_world(e);
|
||||
if (pts.size() < 2) continue;
|
||||
Vec3d d = pts.back() - pts.front();
|
||||
d = d - p.normal * d.dot(p.normal); // project the edge direction into the plane
|
||||
const double len = d.norm();
|
||||
if (len > best) { best = len; x = d / len; }
|
||||
}
|
||||
if (best < 1e-9) { // curved/edgeless face: an arbitrary in-plane basis; a hole is round anyway
|
||||
const Vec3d ref = std::abs(p.normal.z()) < 0.9 ? Vec3d(0, 0, 1) : Vec3d(1, 0, 0);
|
||||
x = ref.cross(p.normal).normalized();
|
||||
}
|
||||
p.x_axis = x.normalized();
|
||||
p.y_axis = p.normal.cross(p.x_axis).normalized();
|
||||
out = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CadDocument::thread_target(int body_idx, int face, int edge, SketchPlane& plane, GeometryEngine::CylinderFace& cyl,
|
||||
bool* from_face) const
|
||||
{
|
||||
cyl = GeometryEngine::CylinderFace();
|
||||
if (body_idx >= 0 && body_idx < int(bodies.size())) {
|
||||
const TopoDS_Shape& shape = bodies[body_idx].shape;
|
||||
if (face >= 0) cyl = GeometryEngine::cylinder_of_face(GeometryEngine::face_by_index(shape, face));
|
||||
if (from_face != nullptr) *from_face = cyl.ok;
|
||||
if (!cyl.ok && edge >= 0) cyl = GeometryEngine::circle_of_edge(GeometryEngine::edge_by_index(shape, edge));
|
||||
} else if (from_face != nullptr) {
|
||||
*from_face = false;
|
||||
}
|
||||
if (!cyl.ok) return false;
|
||||
plane = frame_from(cyl.base, cyl.axis);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string CadDocument::datum_plane_refusal(const CadFeature& f) const
|
||||
{
|
||||
auto face_of = [&](int body, int face) {
|
||||
return face < 0 || body < 0 || body >= int(bodies.size()) ? TopoDS_Face()
|
||||
: GeometryEngine::face_by_index(bodies[body].shape, face);
|
||||
};
|
||||
// As resolve_datum_planes() reads an edge: one it can sample end to end.
|
||||
auto edge_on = [&](int body, int edge) {
|
||||
if (edge < 0 || body < 0 || body >= int(bodies.size())) return false;
|
||||
const TopoDS_Edge e = GeometryEngine::edge_by_index(bodies[body].shape, edge);
|
||||
return !e.IsNull() && GeometryEngine::sample_edge_world(e).size() >= 2;
|
||||
};
|
||||
const bool faceA_on = !face_of(f.plane_face_body, f.plane_face).IsNull();
|
||||
const char* gone = L("A picked face or edge is no longer on the model — pick it again");
|
||||
switch (f.plane_type) {
|
||||
case PlaneType::Offset:
|
||||
case PlaneType::Coincident:
|
||||
// Face A is optional here; without it the plane is built from the base plane.
|
||||
if (f.plane_face >= 0 && !faceA_on) return gone;
|
||||
break;
|
||||
case PlaneType::Angle:
|
||||
if (f.plane_edge < 0) return L("An angled plane needs an edge to tilt about — pick Edge A");
|
||||
if (!edge_on(f.plane_edge_body, f.plane_edge) || (f.plane_face >= 0 && !faceA_on)) return gone;
|
||||
break;
|
||||
case PlaneType::Midplane:
|
||||
if (f.plane_face < 0 || f.plane_face2 < 0) return L("A midplane needs two faces — pick Face A and Face B");
|
||||
// Well-defined but useless: the midplane of a face with itself is that same face.
|
||||
if (f.plane_face == f.plane_face2 && f.plane_face_body == f.plane_face2_body)
|
||||
return L("Face A and Face B are the same face — a midplane needs two different faces");
|
||||
if (!faceA_on || face_of(f.plane_face2_body, f.plane_face2).IsNull()) return gone;
|
||||
break;
|
||||
case PlaneType::Tangent:
|
||||
if (f.plane_face < 0) return L("A tangent plane needs a cylindrical face — pick Face A");
|
||||
if (!faceA_on) return gone;
|
||||
if (!GeometryEngine::cylinder_of_face(face_of(f.plane_face_body, f.plane_face)).ok)
|
||||
return L("A tangent plane needs a cylindrical face — pick Face A");
|
||||
break;
|
||||
case PlaneType::TwoEdges:
|
||||
if (f.plane_edge < 0 || f.plane_edge2 < 0) return L("This plane needs two edges — pick Edge A and Edge B");
|
||||
if (!edge_on(f.plane_edge_body, f.plane_edge) || !edge_on(f.plane_edge2_body, f.plane_edge2)) return gone;
|
||||
break;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, SketchPlane>> CadDocument::resolve_datum_planes() const
|
||||
{
|
||||
std::vector<std::pair<std::string, SketchPlane>> out;
|
||||
|
|
@ -2039,24 +2166,30 @@ void CadDocument::clear()
|
|||
variables.clear();
|
||||
error.clear();
|
||||
mate_conflicts.clear();
|
||||
bodies_before.clear();
|
||||
++topo_generation; // every face/edge id handed out before this is stale now
|
||||
// A cleared document is a fresh start with no history.
|
||||
m_undo.clear();
|
||||
m_redo.clear();
|
||||
m_redo_at_checkpoint.clear();
|
||||
}
|
||||
|
||||
void CadDocument::checkpoint()
|
||||
{
|
||||
m_undo.push_back(Snapshot{features, variables}); // snapshot the pre-mutation recipe
|
||||
m_redo.clear(); // any new action invalidates the redo branch
|
||||
m_redo_at_checkpoint = std::move(m_redo); // any new action invalidates the redo branch
|
||||
m_redo.clear();
|
||||
if (m_undo.size() > k_undo_cap)
|
||||
m_undo.erase(m_undo.begin());
|
||||
}
|
||||
|
||||
void CadDocument::abandon_checkpoint()
|
||||
{
|
||||
if (!m_undo.empty())
|
||||
m_undo.pop_back();
|
||||
if (m_undo.empty())
|
||||
return;
|
||||
m_undo.pop_back();
|
||||
m_redo = std::move(m_redo_at_checkpoint); // nothing happened, so what was redoable still is
|
||||
m_redo_at_checkpoint.clear();
|
||||
}
|
||||
|
||||
bool CadDocument::undo()
|
||||
|
|
@ -2083,10 +2216,23 @@ bool CadDocument::redo()
|
|||
return true;
|
||||
}
|
||||
|
||||
bool CadDocument::rollback()
|
||||
{
|
||||
if (m_undo.empty())
|
||||
return false;
|
||||
features = std::move(m_undo.back().features);
|
||||
variables = std::move(m_undo.back().variables);
|
||||
m_undo.pop_back();
|
||||
m_redo = std::move(m_redo_at_checkpoint);
|
||||
m_redo_at_checkpoint.clear();
|
||||
recompute();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// A feature's body index: -1 means "the last body", anything else must exist. An index past
|
||||
// the end used to fall back to the last body in silence, so a feature whose body had gone away
|
||||
// went on to work on a different one.
|
||||
// the end is refused rather than taken as the last body, so a feature whose body has gone away
|
||||
// does not go on to work on a different one.
|
||||
static int pick_body(int ref, int nb)
|
||||
{
|
||||
if (ref == -1) return nb - 1;
|
||||
|
|
@ -2143,6 +2289,25 @@ static int find_body(const std::vector<CadBody>& v, const CadFeature::BodyId& id
|
|||
return -1;
|
||||
}
|
||||
|
||||
CadFeature::BodyId CadDocument::body_id(int body) const { return body_id_of(bodies, body); }
|
||||
|
||||
int CadDocument::body_index(const CadFeature::BodyId& id) const { return find_body(bodies, id); }
|
||||
|
||||
CadDocument CadDocument::history_before(int f) const
|
||||
{
|
||||
CadDocument out;
|
||||
out.features.assign(features.begin(), features.begin() + std::clamp(f, 0, int(features.size())));
|
||||
out.variables = variables;
|
||||
out.bodies = bodies;
|
||||
out.modeling_origin = modeling_origin;
|
||||
out.origin_from_recipe = origin_from_recipe;
|
||||
out.auto_close_loops = auto_close_loops;
|
||||
out.linear_deflection = linear_deflection;
|
||||
out.angular_deflection = angular_deflection;
|
||||
out.topo_generation = topo_generation;
|
||||
return out;
|
||||
}
|
||||
|
||||
// Re-point `f`'s body fields of one kind (`running`) from the identities recorded last time,
|
||||
// then record the identities they resolve to now. Throws when a pending reference cannot be
|
||||
// found: the body it named is gone, and working on some other body instead is the bug this
|
||||
|
|
@ -2166,15 +2331,6 @@ static void settle_body_refs(CadFeature& f, const std::vector<CadBody>& v, bool
|
|||
});
|
||||
}
|
||||
|
||||
// Datum-plane ordinals: plane_base, axis_plane_a, axis_plane_b hold 3 + N.
|
||||
template<class Visit>
|
||||
static void for_each_datum_ref(CadFeature& f, Visit&& visit)
|
||||
{
|
||||
visit(f.plane_base);
|
||||
visit(f.axis_plane_a);
|
||||
visit(f.axis_plane_b);
|
||||
}
|
||||
|
||||
// Prepare every reference for a change of history in which feature `i` ends up at
|
||||
// `map_feature(i)` (-1 = removed) and enabled as `enabled_after(i)`. Runs on the OLD history and
|
||||
// writes into `features` in the old order; the caller then performs the change.
|
||||
|
|
@ -2202,7 +2358,7 @@ static void stage_history_change(std::vector<CadFeature>& features,
|
|||
for (int j = 0; j < n; ++j) {
|
||||
if (map_feature(j) < 0) continue;
|
||||
CadFeature& f = features[j];
|
||||
for_each_datum_ref(f, [&](int& ref) {
|
||||
CadDocument::for_each_datum_ref(f, [&](int& ref) {
|
||||
if (ref < 3) return;
|
||||
const int N = ref - 3;
|
||||
const int oldf = (N < int(planes_before.size())) ? planes_before[N] : -1;
|
||||
|
|
@ -2260,33 +2416,6 @@ static bool commit_or_rollback(CadDocument& doc, std::vector<CadFeature>& snapsh
|
|||
return false;
|
||||
}
|
||||
|
||||
// Visit every field of `f` that holds an index into features[].
|
||||
//
|
||||
// Deliberately NOT dispatched on f.type. A type switch is what this replaced, and it was
|
||||
// wrong in the way type switches go wrong: it listed Extrude and Mate, and every feature
|
||||
// type added afterwards — Revolve, Sweep, Loft, Rib, Pattern-on-curve, the Surface* family —
|
||||
// silently inherited a remap that skipped its references. Visiting the FIELDS instead means
|
||||
// a new type is covered the moment it reuses one of them, and reaching a field its type
|
||||
// never reads costs nothing: unset refs are -1 and every visitor here ignores those.
|
||||
//
|
||||
// The list is exactly the fields documented as "index into features[]" / "feature index" in
|
||||
// CadDocument.hpp. Not included, because they are a different basis and need their own pass:
|
||||
// plane_base / axis_plane_a / axis_plane_b encode `3 + N` = the Nth DATUM PLANE, an ordinal
|
||||
// into resolve_datum_planes(), not into features[]. Everything named *_body / *_face / *_edge
|
||||
// is a body index or a global topology id and must never be remapped here.
|
||||
template<class Visit>
|
||||
static void for_each_feature_ref(CadFeature& f, Visit&& visit)
|
||||
{
|
||||
visit(f.sketch_ref);
|
||||
visit(f.sweep_path_ref);
|
||||
visit(f.pattern_curve_sketch);
|
||||
visit(f.rib_sketch_ref);
|
||||
visit(f.mate_cs_a);
|
||||
visit(f.mate_cs_b);
|
||||
for (int& r : f.loft_profile_refs)
|
||||
visit(r);
|
||||
}
|
||||
|
||||
bool CadDocument::remove_feature(int index)
|
||||
{
|
||||
if (index < 0 || index >= int(features.size()))
|
||||
|
|
@ -2413,10 +2542,11 @@ bool CadDocument::replace_feature(int index, const CadFeature& edited)
|
|||
|
||||
std::vector<CadFeature> snapshot = features;
|
||||
|
||||
// Preserve identity (name) and the structural link (sketch_ref) from the
|
||||
// Preserve identity (name and uid) and the structural link (sketch_ref) from the
|
||||
// original; only the user-editable parameters come from `edited`.
|
||||
CadFeature f = edited;
|
||||
f.name = features[index].name;
|
||||
f.uid = features[index].uid;
|
||||
f.type = features[index].type;
|
||||
if (f.type == CadFeatureType::Extrude)
|
||||
f.sketch_ref = features[index].sketch_ref;
|
||||
|
|
@ -2499,10 +2629,10 @@ TopoDS_Wire CadDocument::build_sketch_wire(const CadFeature& sketch, bool closed
|
|||
// An entity sketch that yields no wire is an ERROR, not a cue to fall through. The
|
||||
// legacy tail of this function ends in a default rectangle built from width/height,
|
||||
// which for an entity sketch are whatever they happened to be initialised to — so a
|
||||
// sketch entities_to_wire cannot handle (a circle coexisting with a line, two circles:
|
||||
// 88v) used to extrude into a box the user never drew, silently. Failing here
|
||||
// costs the caller an error message; falling through cost them wrong geometry that
|
||||
// looked deliberate. The legacy profile/shape paths below are still reached by sketches
|
||||
// sketch entities_to_wire cannot handle (a circle coexisting with a line, two circles)
|
||||
// would extrude into a box the user never drew, silently. Failing here costs the
|
||||
// caller an error message; falling through would cost them wrong geometry that looks
|
||||
// deliberate. The legacy profile/shape paths below are still reached by sketches
|
||||
// that legitimately carry no entities at all.
|
||||
throw std::runtime_error(
|
||||
open_loop_message(sketch,
|
||||
|
|
@ -2750,8 +2880,7 @@ void CadDocument::apply_feature(TopoDS_Shape& result, bool& have_body,
|
|||
if (wire.IsNull()) throw std::runtime_error(_u8L("surface-revolve: empty profile"));
|
||||
gp_Ax1 axis = revolve_axis_of(f, sk);
|
||||
// Same angle rules as the solid Revolve (flip reverses it, and a negative sweep is a
|
||||
// positive one about the reversed axis — MakeRevol wants (0, 2 pi]); this surface
|
||||
// version used to ignore both.
|
||||
// positive one about the reversed axis — MakeRevol wants (0, 2 pi]).
|
||||
double ang = (f.flip ? -f.revolve_angle : f.revolve_angle) * M_PI / 180.0;
|
||||
if (ang < 0) { axis.Reverse(); ang = -ang; }
|
||||
BRepPrimAPI_MakeRevol rev(wire, axis, ang, false);
|
||||
|
|
@ -2816,7 +2945,11 @@ void CadDocument::apply_feature(TopoDS_Shape& result, bool& have_body,
|
|||
throw std::runtime_error(_u8L("sweep path must be a sketch or helix"));
|
||||
}
|
||||
TopoDS_Wire profile = build_sketch_wire(sk, true);
|
||||
TopoDS_Shape tool = SketchEngine::make_sweep(profile, path);
|
||||
// Along a helix the profile keeps its angle to the helix axis, as a spring's wire does.
|
||||
const Vec3d& axis = path_feat.plane.normal;
|
||||
TopoDS_Shape tool = path_feat.type == CadFeatureType::Helix
|
||||
? SketchEngine::make_sweep(profile, path, gp_Dir(axis.x(), axis.y(), axis.z()))
|
||||
: SketchEngine::make_sweep(profile, path);
|
||||
if (!have_body || f.mode == BooleanMode::New) {
|
||||
result = tool;
|
||||
have_body = true;
|
||||
|
|
@ -3479,8 +3612,8 @@ void CadDocument::apply_thicken_surface(std::vector<CadBody>& bodies, const CadF
|
|||
// successfully a few hundred lines up — but it CANNOT be handed an open sheet. In OCCT,
|
||||
// BRepOffset_MakeOffset::MakeThickSolid builds the solid only inside `if (!myFaces.IsEmpty())`
|
||||
// (BRepOffset_MakeOffset.cxx:1115): with no closing faces it stops after the offset shell and
|
||||
// returns that. So it reports IsDone() and a non-null shape containing no TopAbs_SOLID at all
|
||||
// — which is exactly how two earlier attempts failed, and why no parameter could have fixed it.
|
||||
// returns that. So on an open sheet it reports IsDone() and a non-null shape containing no
|
||||
// TopAbs_SOLID at all, and no parameter changes that.
|
||||
//
|
||||
// So close the sheet first, then use the working call: cap the free rims, sew into a closed
|
||||
// shell, make a solid, and hollow it inward passing the caps as the faces to remove. The caps
|
||||
|
|
@ -3547,7 +3680,7 @@ void CadDocument::apply_thicken_surface(std::vector<CadBody>& bodies, const CadF
|
|||
solid = mts.Shape();
|
||||
}
|
||||
if (solid.IsNull()) throw std::runtime_error(_u8L("thicken-surface: produced no geometry"));
|
||||
// IsDone() is NOT a success test here — the failed attempts had IsDone() true and no solid.
|
||||
// IsDone() is NOT a success test here: ByJoin on an open sheet reports IsDone() with no solid.
|
||||
if (!TopExp_Explorer(solid, TopAbs_SOLID).More())
|
||||
throw std::runtime_error(_u8L("thicken-surface: produced a shell, not a solid"));
|
||||
|
||||
|
|
@ -4033,12 +4166,30 @@ void CadDocument::route_feature(std::vector<CadBody>& bodies, const CadFeature&
|
|||
}
|
||||
}
|
||||
|
||||
std::map<std::string, double> CadDocument::variable_values(std::string& err) const
|
||||
{
|
||||
try {
|
||||
return evaluate_variables(variables);
|
||||
} catch (const std::exception& e) {
|
||||
err = e.what();
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
void CadDocument::bind_expressions()
|
||||
{
|
||||
std::map<std::string, double> varvals = evaluate_variables(variables);
|
||||
for (CadFeature& f : features)
|
||||
for (const auto& [field, e] : f.expr)
|
||||
assign_field(f, field, eval_expr(e, varvals));
|
||||
set_numeric_field(f, field, eval_expr(e, varvals));
|
||||
}
|
||||
|
||||
// The next CadFeature::uid. One count for the whole process, so that a copy of a document (a card's preview, the history
|
||||
// before a feature) never hands its new features a number the document it was copied from gives one of its own.
|
||||
static uint64_t next_feature_uid()
|
||||
{
|
||||
static std::atomic<uint64_t> next{1};
|
||||
return next.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void CadDocument::replay_feature(size_t fi, std::vector<CadBody>& built)
|
||||
|
|
@ -4069,9 +4220,13 @@ void CadDocument::replay_feature(size_t fi, std::vector<CadBody>& built)
|
|||
bool CadDocument::recompute()
|
||||
{
|
||||
error.clear();
|
||||
// A feature added since the last rebuild, or read from a project, gets its identity.
|
||||
for (CadFeature& f : features)
|
||||
if (f.uid == 0) f.uid = next_feature_uid();
|
||||
set_sketch_auto_close(auto_close_loops); // this document's weld rule, not the last one's
|
||||
detect_mate_conflicts();
|
||||
std::vector<CadBody> built;
|
||||
bodies_before.assign(features.size(), std::nullopt);
|
||||
// Did any feature in this document even ASK for a solid? A document made only of sketches
|
||||
// and datums has nothing to build, and that is a legitimate state — it is every document
|
||||
// between drawing the first profile and extruding it. Reporting it as a failure is what
|
||||
|
|
@ -4084,8 +4239,12 @@ bool CadDocument::recompute()
|
|||
});
|
||||
try {
|
||||
bind_expressions();
|
||||
for (size_t fi = 0; fi < features.size(); ++fi)
|
||||
for (size_t fi = 0; fi < features.size(); ++fi) {
|
||||
// The bodies the feature starts from, which feature_describe lists.
|
||||
std::vector<BodyBefore>& was = bodies_before[fi].emplace();
|
||||
for (int b = 0; b < int(built.size()); ++b) was.push_back({built[size_t(b)].name, body_id_of(built, b)});
|
||||
replay_feature(fi, built);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
error = *e.what() ? e.what() : _u8L("OCCT operation failed");
|
||||
return false;
|
||||
|
|
@ -4095,11 +4254,11 @@ bool CadDocument::recompute()
|
|||
}
|
||||
if (built.empty() && any_solid_feature) { error = _u8L("no solid-producing features"); return false; }
|
||||
|
||||
// A feature that leaves a body with a null shape must fail loudly. Until this existed,
|
||||
// recompute() returned true and the document kept advertising the body: describe_scene
|
||||
// counted it, error was empty, and only mass_properties on that specific body revealed
|
||||
// anything was wrong. Returning false hands the caller its normal rollback path, so the
|
||||
// operation that destroyed the body is undone rather than committed.
|
||||
// A feature that leaves a body with a null shape fails the rebuild loudly. Were recompute() to
|
||||
// return true, the document would go on listing the body: design_describe would count it, error
|
||||
// would be empty, and only body_mass_properties on that body would show anything was wrong. Returning
|
||||
// false hands the caller its normal rollback path, so the operation that destroyed the body is
|
||||
// undone rather than committed.
|
||||
for (size_t i = 0; i < built.size(); ++i) {
|
||||
if (!built[i].shape.IsNull()) continue;
|
||||
const int src = built[i].source_feature;
|
||||
|
|
@ -4473,8 +4632,8 @@ std::string CadDocument::serialize_recipe() const
|
|||
ar(blen);
|
||||
ar(cereal::binary_data(bb.data(), bb.size()));
|
||||
// DOCUMENT EXTRAS, appended after the body names on the same terms (older builds stop
|
||||
// reading before it): the modeling origin, and the body colours. A colour set with the
|
||||
// Color tool used to live only until the project was closed.
|
||||
// reading before it): the modeling origin, and the body colours, so a colour set with
|
||||
// the Color tool is saved with the project.
|
||||
std::map<uint32_t, std::array<float, 4>> colours;
|
||||
for (uint32_t i = 0; i < bodies.size(); ++i)
|
||||
if (bodies[i].has_color)
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <cereal/types/map.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
|
@ -237,6 +238,12 @@ struct CadFeature {
|
|||
std::vector<BodyId> body_ref_ids;
|
||||
bool body_refs_pending{false};
|
||||
|
||||
// Transient, never serialized: the feature's identity, which its index is not, since a delete, a reorder or an undo
|
||||
// moves it. Every copy keeps it (undo and redo, a reorder, a suppress, replace_feature(), a copy of the document),
|
||||
// and no other feature in the process is given the same one. 0 until recompute() gives it one: a feature read from
|
||||
// a project, or added since the last rebuild, has none. The Design tab keys where a body stands by its maker's.
|
||||
uint64_t uid{0};
|
||||
|
||||
// Datum/reference plane: a derived SketchPlane the document offers as a selectable
|
||||
// sketch plane (no solid). plane_base selects the reference (0=XY,1=XZ,2=YZ, or 3+N
|
||||
// = the Nth earlier datum plane); plane_offset shifts along the base normal;
|
||||
|
|
@ -543,6 +550,39 @@ public:
|
|||
// Can a feature expression drive this numeric field? The single allow-list the evaluator
|
||||
// uses, so a caller can refuse a name before it breaks the next recompute.
|
||||
static bool is_bindable_field(const std::string& field);
|
||||
// Write `value` into the numeric field named `field`: the allow-list above, so a literal edit
|
||||
// and an expression binding reach exactly the same fields. Integer fields are rounded, and
|
||||
// thread_diameter writes half of it to thread_radius. Throws std::runtime_error naming an
|
||||
// unknown field.
|
||||
static void set_numeric_field(CadFeature& f, const std::string& field, double value);
|
||||
// The variables' values as recompute() evaluates them. Empty, with `err` set, on a cycle, an
|
||||
// unknown name or an expression that does not evaluate.
|
||||
std::map<std::string, double> variable_values(std::string& err) const;
|
||||
// Visit every field of `f` holding an index into `features`. It visits fields rather than
|
||||
// dispatching on the type, so a feature type that reuses one of them is covered without being
|
||||
// listed; an unset reference is -1. Body indices and face or edge ids are not visited, nor are
|
||||
// datum-plane ordinals (for_each_datum_ref). `Feature` is CadFeature or const CadFeature.
|
||||
template<class Feature, class Visit>
|
||||
static void for_each_feature_ref(Feature& f, Visit&& visit)
|
||||
{
|
||||
visit(f.sketch_ref);
|
||||
visit(f.sweep_path_ref);
|
||||
visit(f.pattern_curve_sketch);
|
||||
visit(f.rib_sketch_ref);
|
||||
visit(f.mate_cs_a);
|
||||
visit(f.mate_cs_b);
|
||||
for (auto& r : f.loft_profile_refs)
|
||||
visit(r);
|
||||
}
|
||||
// Visit every field holding a datum-plane ordinal: 3 + N names the Nth enabled Plane feature
|
||||
// (resolve_datum_planes()), below 3 a base plane.
|
||||
template<class Feature, class Visit>
|
||||
static void for_each_datum_ref(Feature& f, Visit&& visit)
|
||||
{
|
||||
visit(f.plane_base);
|
||||
visit(f.axis_plane_a);
|
||||
visit(f.axis_plane_b);
|
||||
}
|
||||
// Does a feature of this type leave a body behind? Sketches, datums, the helix curve and
|
||||
// Project (which emits sketch entities) do not. The one answer recompute(), the rollback
|
||||
// rule and the GUI's preview all use.
|
||||
|
|
@ -556,6 +596,20 @@ public:
|
|||
std::vector<int> display_tri_face; // per-triangle face id WITHIN its source body
|
||||
std::vector<int> display_tri_body; // per-triangle source body index (into bodies)
|
||||
std::string error; // last recompute error ("" = ok)
|
||||
// The bodies each feature started from in the last recompute(), indexed like `features`: their makers' names and
|
||||
// identities, which body_index() finds them by in `bodies`. Null for a feature that rebuild did not reach. A
|
||||
// rebuild result like `bodies`: refilled by recompute(), never saved.
|
||||
struct BodyBefore { std::string name; CadFeature::BodyId id; };
|
||||
std::vector<std::optional<std::vector<BodyBefore>>> bodies_before;
|
||||
// A body's identity, the feature that made it and which of that feature's bodies it is, and the index in `bodies`
|
||||
// of the body that has one (-1 for none): what carries a body's colour, its name and the references to it across
|
||||
// a rebuild that renumbers the bodies.
|
||||
CadFeature::BodyId body_id(int body) const;
|
||||
int body_index(const CadFeature::BodyId& id) const;
|
||||
// The history before feature `f`, not rebuilt: features [0, f) with the variables, the settings the rebuild reads
|
||||
// and the bodies, whose names and colours recompute() carries across. No undo history and no display meshes,
|
||||
// which a copy of the whole document would spend its time on.
|
||||
CadDocument history_before(int f) const;
|
||||
|
||||
// Mate diagnostics, refilled by every recompute(). Non-fatal by design: the
|
||||
// document still evaluates — this only names what the user should look at.
|
||||
|
|
@ -600,11 +654,19 @@ public:
|
|||
// entities are (re)derived on every recompute.
|
||||
int add_project_edges(int source_body, const std::vector<int>& edge_ids, int face,
|
||||
const SketchPlane& plane, const std::string& name);
|
||||
// Onshape's "Use" / SolidWorks' "Convert Entities": project a body's edges onto the plane of
|
||||
// an EXISTING sketch feature and append them to that sketch as CONSTRUCTION entities, so new
|
||||
// geometry can be constrained to them. Returns the number of entities appended, or -1 if the
|
||||
// sketch or body reference is invalid. Unlike add_project_edges this creates no feature: the
|
||||
// references become part of the sketch that borrows them.
|
||||
// The edges of bodies[source_body] that a Project feature takes (`edge_ids`, else the edges of
|
||||
// face `face`, else all of them), projected onto `plane` as CONSTRUCTION entities: references a
|
||||
// sketch borrows to constrain new geometry to. Face and edge ids are those of the model as it
|
||||
// stands. Changes nothing. Empty, with `error` saying why, for a body that does not exist or has
|
||||
// no shape, an id that names no face or edge, and edges that all project to a point.
|
||||
std::vector<SketchEntity> project_edges_on(const SketchPlane& plane, int source_body,
|
||||
const std::vector<int>& edge_ids, int face,
|
||||
std::string& error) const;
|
||||
// Onshape's "Use" / SolidWorks' "Convert Entities": the entities project_edges_on() gives on the
|
||||
// plane of an EXISTING sketch feature, appended to that sketch. Returns the number of entities
|
||||
// appended, or -1 if the sketch reference is invalid or project_edges_on() gives none. Unlike
|
||||
// add_project_edges this creates no feature: the references become part of the sketch that
|
||||
// borrows them.
|
||||
int project_edges_into_sketch(int sketch_feature, int source_body,
|
||||
const std::vector<int>& edge_ids, int face);
|
||||
// Append a bridging BSpline entity connecting endpoint `end_a` of entity `ent_a` to
|
||||
|
|
@ -733,6 +795,13 @@ public:
|
|||
// Every datum plane currently in the recipe, in feature order, as (name, plane).
|
||||
// Used by the GUI to populate plane pickers (after the 3 base planes).
|
||||
std::vector<std::pair<std::string, SketchPlane>> resolve_datum_planes() const;
|
||||
// Why the Plane feature `f` cannot be built as its plane_type asks, or "" when it can. Each
|
||||
// construction needs its references (an angled plane an edge, a midplane two different faces,
|
||||
// a tangent plane a cylindrical face, a two-edge plane two edges), and every reference it uses
|
||||
// must still be on its body. resolve_datum_planes() falls back to an offset plane, silently,
|
||||
// when they are not; this is the check that keeps a new plane off that fallback. The reason is
|
||||
// an untranslated message (marked with L()), translated where it is shown.
|
||||
std::string datum_plane_refusal(const CadFeature& f) const;
|
||||
|
||||
// World-space sketch plane lying on a body's PLANAR face, so a face picked in the viewport can
|
||||
// be sketched on directly — no datum plane in between and nothing to choose from a list.
|
||||
|
|
@ -740,6 +809,19 @@ public:
|
|||
// has no single plane, and guessing one from a mid-parameter normal would silently sketch on a
|
||||
// tangent). Same derivation the Coincident datum method uses, shared so the two cannot drift.
|
||||
bool plane_of_face(int body_idx, int face_idx, SketchPlane& out) const;
|
||||
// The plane a hole drills from on a body's face: origin at the face centroid, normal pointing
|
||||
// INTO the solid, so a positioned hole drills inward and its (x,y) read as the offset from the
|
||||
// face centre, and x along the face's longest straight edge, so the hole's distances from the
|
||||
// face sides read along the sides. False when the indices don't resolve. Any face is accepted,
|
||||
// as the Hole card accepts any picked face; a curved one gets its mid-parameter normal.
|
||||
bool inward_plane_of_face(int body_idx, int face_idx, SketchPlane& out) const;
|
||||
// What a Thread is cut on when a body's face or rim is picked: the cylindrical face `face` of
|
||||
// body `body_idx`, else its circular edge `edge` (-1 for none). `cyl` is that cylinder (an edge
|
||||
// gives no length and reads as external); `plane` sits on its axis, origin at the base and
|
||||
// normal along the axis, where a thread starts and the way it rises. False when neither is
|
||||
// round; `from_face` says whether the face was.
|
||||
bool thread_target(int body_idx, int face, int edge, SketchPlane& plane, GeometryEngine::CylinderFace& cyl,
|
||||
bool* from_face = nullptr) const;
|
||||
// Resolved datum axes in feature order. axis_err is non-empty if construction failed.
|
||||
struct DatumAxis { std::string name; Vec3d origin{0,0,0}; Vec3d direction{0,0,1};
|
||||
std::string error; };
|
||||
|
|
@ -800,10 +882,11 @@ public:
|
|||
// body) is derived by recompute(), snapshotting `features` alone is a complete,
|
||||
// exact history; one checkpoint == one Ctrl+Z step.
|
||||
void checkpoint(); // snapshot `features` for undo + invalidate redo
|
||||
// Drop the most recent checkpoint. For a mutation that took a checkpoint, then failed
|
||||
// and restored the pre-mutation state itself (the constraint paths reject an
|
||||
// over-constrained addition this way): the snapshot now describes a state identical to
|
||||
// the current one, and leaving it turns the next Ctrl+Z into a press that does nothing.
|
||||
// Drop the most recent checkpoint and put back the redo branch it cleared. For a mutation
|
||||
// that took a checkpoint, then failed and restored the pre-mutation state itself (the
|
||||
// constraint paths reject an over-constrained addition this way, and the feature-tree edits
|
||||
// below roll themselves back): the snapshot now describes a state identical to the current
|
||||
// one, and leaving it turns the next Ctrl+Z into a press that does nothing.
|
||||
void abandon_checkpoint();
|
||||
bool can_undo() const { return !m_undo.empty(); }
|
||||
bool can_redo() const { return !m_redo.empty(); }
|
||||
|
|
@ -811,6 +894,12 @@ public:
|
|||
size_t redo_depth() const { return m_redo.size(); }
|
||||
bool undo(); // restore the previous feature list + recompute(); false if no history
|
||||
bool redo(); // re-apply the most recently undone change; false if none
|
||||
// Take back a refused edit as if it had never been made: restore and drop the last checkpoint,
|
||||
// recompute, and put back the redo branch that checkpoint() cleared. For an edit whose rebuild
|
||||
// failed after its checkpoint; undo() there would leave the refused recipe on the redo stack,
|
||||
// where Redo brings it back. Call it straight after the failed edit, in place of undo().
|
||||
// False if there is no checkpoint.
|
||||
bool rollback();
|
||||
|
||||
// Feature-tree editing (Onshape-style). All are transactional: they snapshot
|
||||
// features, mutate, recompute(), and roll back to the snapshot (re-recomputing)
|
||||
|
|
@ -912,6 +1001,7 @@ private:
|
|||
};
|
||||
std::vector<Snapshot> m_undo;
|
||||
std::vector<Snapshot> m_redo;
|
||||
std::vector<Snapshot> m_redo_at_checkpoint; // the redo branch the last checkpoint() cleared, for rollback() and abandon_checkpoint()
|
||||
static constexpr size_t k_undo_cap = 200;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,14 @@
|
|||
#include <TopoDS_Solid.hxx>
|
||||
#include <TopoDS_Vertex.hxx>
|
||||
#include <ShapeUpgrade_UnifySameDomain.hxx>
|
||||
#include <ChFi3d.hxx>
|
||||
#include <ChFiDS_TypeOfConcavity.hxx>
|
||||
#include <NCollection_DataMap.hxx>
|
||||
#include <gp_Ax1.hxx>
|
||||
#include <gp_Cone.hxx>
|
||||
#include <gp_Sphere.hxx>
|
||||
#include <gp_Torus.hxx>
|
||||
#include <gp_XYZ.hxx>
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <cmath>
|
||||
|
|
@ -689,6 +697,110 @@ GeometryEngine::CylinderFace GeometryEngine::circle_of_edge(const TopoDS_Edge& e
|
|||
return cf;
|
||||
}
|
||||
|
||||
GeometryEngine::SurfaceInfo GeometryEngine::surface_info(const TopoDS_Face& face)
|
||||
{
|
||||
SurfaceInfo s;
|
||||
if (face.IsNull()) return s;
|
||||
GProp_GProps props;
|
||||
BRepGProp::SurfaceProperties(face, props);
|
||||
s.area = props.Mass();
|
||||
s.centroid = Vec3d(props.CentreOfMass().X(), props.CentreOfMass().Y(), props.CentreOfMass().Z());
|
||||
|
||||
BRepAdaptor_Surface surf(face);
|
||||
s.type = surf.GetType();
|
||||
auto vec = [](const gp_XYZ& v) { return Vec3d(v.X(), v.Y(), v.Z()); };
|
||||
// A bore or a countersink faces its axis: the outward normal at the face's middle points from
|
||||
// the surface toward the axis (or the centre).
|
||||
const gp_Pnt mid = surf.Value(0.5 * (surf.FirstUParameter() + surf.LastUParameter()),
|
||||
0.5 * (surf.FirstVParameter() + surf.LastVParameter()));
|
||||
auto facing = [&](const Vec3d& toward) { return face_normal_world(face).dot(toward) > 0.0; };
|
||||
switch (s.type) {
|
||||
case GeomAbs_Cylinder: {
|
||||
const CylinderFace c = cylinder_of_face(face);
|
||||
s.location = c.base;
|
||||
s.axis = c.axis;
|
||||
s.radius = c.radius;
|
||||
s.internal = c.internal;
|
||||
break;
|
||||
}
|
||||
case GeomAbs_Cone: {
|
||||
// The radius at parameter v is RefRadius + v sin(SemiAngle), and v runs along the axis, so
|
||||
// the cone opens along the axis when the semi-angle is positive.
|
||||
const gp_Cone cone = surf.Cone();
|
||||
const double sa = cone.SemiAngle();
|
||||
const Vec3d dir = vec(cone.Axis().Direction().XYZ());
|
||||
s.location = vec(cone.Apex().XYZ());
|
||||
s.axis = sa >= 0.0 ? dir : Vec3d(-dir);
|
||||
s.half_angle = std::abs(sa);
|
||||
const double r0 = std::abs(cone.RefRadius() + surf.FirstVParameter() * std::sin(sa));
|
||||
const double r1 = std::abs(cone.RefRadius() + surf.LastVParameter() * std::sin(sa));
|
||||
s.radius = std::min(r0, r1);
|
||||
s.radius2 = std::max(r0, r1);
|
||||
const Vec3d m = vec(mid.XYZ());
|
||||
s.internal = facing(s.location + s.axis * (m - s.location).dot(s.axis) - m);
|
||||
break;
|
||||
}
|
||||
case GeomAbs_Sphere: {
|
||||
const gp_Sphere sphere = surf.Sphere();
|
||||
s.location = vec(sphere.Location().XYZ());
|
||||
s.radius = sphere.Radius();
|
||||
s.internal = facing(s.location - vec(mid.XYZ()));
|
||||
break;
|
||||
}
|
||||
case GeomAbs_Torus: {
|
||||
const gp_Torus torus = surf.Torus();
|
||||
s.location = vec(torus.Location().XYZ());
|
||||
s.axis = vec(torus.Axis().Direction().XYZ());
|
||||
s.radius = torus.MajorRadius();
|
||||
s.radius2 = torus.MinorRadius();
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<std::vector<int>> GeometryEngine::edge_faces(const TopoDS_Shape& shape)
|
||||
{
|
||||
NCollection_DataMap<TopoDS_Shape, int, TopTools_ShapeMapHasher> face_id;
|
||||
int n = 0;
|
||||
for (TopExp_Explorer e(shape, TopAbs_FACE); e.More(); e.Next(), ++n)
|
||||
if (!face_id.IsBound(e.Current())) face_id.Bind(e.Current(), n); // faces_of's ordinal
|
||||
NCollection_IndexedDataMap<TopoDS_Shape, NCollection_List<TopoDS_Shape>, TopTools_ShapeMapHasher> faces_of_edge;
|
||||
TopExp::MapShapesAndAncestors(shape, TopAbs_EDGE, TopAbs_FACE, faces_of_edge);
|
||||
const std::vector<TopoDS_Edge> edges = edges_of(shape);
|
||||
std::vector<std::vector<int>> out(edges.size());
|
||||
for (size_t i = 0; i < edges.size(); ++i) {
|
||||
const int k = faces_of_edge.FindIndex(edges[i]);
|
||||
if (k == 0 || BRep_Tool::Degenerated(edges[i])) continue;
|
||||
for (NCollection_List<TopoDS_Shape>::Iterator it(faces_of_edge.FindFromIndex(k)); it.More(); it.Next()) {
|
||||
const int* f = face_id.Seek(it.Value());
|
||||
if (f != nullptr && std::find(out[i].begin(), out[i].end(), *f) == out[i].end()) out[i].push_back(*f);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
int GeometryEngine::edge_convexity(const TopoDS_Edge& edge, const TopoDS_Face& f1, const TopoDS_Face& f2)
|
||||
{
|
||||
// Faces closer than a degree to each other along the edge count as tangent.
|
||||
switch (ChFi3d::DefineConnectType(edge, f1, f2, std::sin(M_PI / 180.0), true)) {
|
||||
case ChFiDS_Convex: return 1;
|
||||
case ChFiDS_Concave: return -1;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
double GeometryEngine::min_distance(const TopoDS_Shape& a, const TopoDS_Shape& b, Vec3d& pa, Vec3d& pb)
|
||||
{
|
||||
BRepExtrema_DistShapeShape dss(a, b);
|
||||
if (!dss.IsDone() || dss.NbSolution() < 1) return -1.0;
|
||||
const gp_Pnt p = dss.PointOnShape1(1), q = dss.PointOnShape2(1);
|
||||
pa = Vec3d(p.X(), p.Y(), p.Z());
|
||||
pb = Vec3d(q.X(), q.Y(), q.Z());
|
||||
return dss.Value();
|
||||
}
|
||||
|
||||
bool GeometryEngine::face_plane_bounds(const TopoDS_Face& face, const Vec3d& origin,
|
||||
const Vec3d& x_axis, const Vec3d& y_axis,
|
||||
double& umin, double& umax, double& vmin, double& vmax)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
|
||||
#include <GeomAbs_SurfaceType.hxx>
|
||||
#include <TopoDS_Shape.hxx>
|
||||
#include <array>
|
||||
#include <TopoDS_Face.hxx>
|
||||
|
|
@ -138,6 +139,37 @@ public:
|
|||
// the edge is not a circle. Lets the Thread tool be driven by a picked circular rim.
|
||||
static CylinderFace circle_of_edge(const TopoDS_Edge& edge);
|
||||
|
||||
// What surface a face lies on, for reading a body's topology: its OCCT type, area and centre
|
||||
// of mass, and the numbers that define an analytic surface. Cylinder: as cylinder_of_face
|
||||
// (`location` its base). Cone: `location` the apex, `axis` from the apex into the opening,
|
||||
// `half_angle` (radians), `radius` and `radius2` the smallest and largest radius the face
|
||||
// reaches. Sphere: `location` the centre, `radius`. Torus: `location` the centre, `axis`,
|
||||
// `radius` the major and `radius2` the minor radius. `internal` (cylinder, cone, sphere): the
|
||||
// outward normal points toward the axis or centre, as in a bore or a countersink.
|
||||
struct SurfaceInfo {
|
||||
GeomAbs_SurfaceType type{GeomAbs_OtherSurface};
|
||||
double area{0};
|
||||
Vec3d centroid{0, 0, 0};
|
||||
Vec3d location{0, 0, 0};
|
||||
Vec3d axis{0, 0, 1};
|
||||
double radius{0};
|
||||
double radius2{0};
|
||||
double half_angle{0};
|
||||
bool internal{false};
|
||||
};
|
||||
static SurfaceInfo surface_info(const TopoDS_Face& face);
|
||||
// The faces each edge bounds: entry i lists the faces_of() ids along edge i of edges_of(), each
|
||||
// once. A seam (the line down a cylinder's side) lists its one face; a degenerate edge (a
|
||||
// cone's apex) lists none.
|
||||
static std::vector<std::vector<int>> edge_faces(const TopoDS_Shape& shape);
|
||||
// How the two faces along `edge` meet, as OCCT's fillet code judges it: +1 convex (an outside
|
||||
// corner), -1 concave (an inside corner), 0 when they meet tangentially, as along a fillet's
|
||||
// boundary, or the edge cannot be judged.
|
||||
static int edge_convexity(const TopoDS_Edge& edge, const TopoDS_Face& f1, const TopoDS_Face& f2);
|
||||
// The shortest distance between two shapes (faces, edges, vertices), and the nearest point on
|
||||
// each. Negative when OCCT finds none.
|
||||
static double min_distance(const TopoDS_Shape& a, const TopoDS_Shape& b, Vec3d& pa, Vec3d& pb);
|
||||
|
||||
// Plane-coordinate (u,v) bounding box of a face's vertices, measured from `origin` along
|
||||
// `x_axis`/`y_axis`. Lets the Hole tool dimension the hole from the face SIDES (umin/vmin =
|
||||
// two adjacent edges) instead of from the centre. Returns false if the face has no vertices.
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@
|
|||
#include <BRepBuilderAPI_Transform.hxx>
|
||||
#include <BRepPrimAPI_MakeRevol.hxx>
|
||||
#include <BRepOffsetAPI_MakePipe.hxx>
|
||||
#include <BRepOffsetAPI_MakePipeShell.hxx>
|
||||
#include <BRepAlgoAPI_Fuse.hxx>
|
||||
#include <BRepAlgoAPI_Cut.hxx>
|
||||
#include <BRepAdaptor_Surface.hxx>
|
||||
|
|
@ -408,6 +409,19 @@ TopoDS_Shape SketchEngine::make_sweep(const TopoDS_Wire& profile, const TopoDS_W
|
|||
return pipe.Shape();
|
||||
}
|
||||
|
||||
TopoDS_Shape SketchEngine::make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path, const gp_Dir& binormal)
|
||||
{
|
||||
if (!BRepBuilderAPI_MakeFace(profile).IsDone()) // a closed planar profile, as above
|
||||
throw std::runtime_error(_u8L("Failed to make face from sweep profile"));
|
||||
BRepOffsetAPI_MakePipeShell pipe(path);
|
||||
pipe.SetMode(binormal);
|
||||
pipe.Add(profile);
|
||||
pipe.Build();
|
||||
if (!pipe.IsDone() || !pipe.MakeSolid())
|
||||
throw std::runtime_error(_u8L("Failed to sweep profile along path"));
|
||||
return pipe.Shape();
|
||||
}
|
||||
|
||||
TopoDS_Shape SketchEngine::make_loft(const std::vector<TopoDS_Wire>& profiles, bool ruled)
|
||||
{
|
||||
if (profiles.size() < 2)
|
||||
|
|
@ -991,15 +1005,14 @@ TopoDS_Face SketchEngine::wires_to_face(const std::vector<TopoDS_Wire>& wires,
|
|||
// Reversing it here only works when the sketch happened to wind both loops the same
|
||||
// way: a circle drawn clockwise inside a counter-clockwise rectangle comes out matching
|
||||
// the outer boundary, OCCT sweeps it as a second contour, and the prism is the plate
|
||||
// with the bore FILLED and the disc's volume counted twice. Measured on the rig:
|
||||
// bbox 67.17 x 219.67 x 10 (the whole plate) with volume 152088 mm3 against a solid-box
|
||||
// 147520 — a body larger than its own bounding box, which is the signature of it.
|
||||
// with the bore FILLED and the disc's volume counted twice: a bbox of 67.17 x 219.67 x 10
|
||||
// (the whole plate) with a volume of 152088 mm3 against the solid box's 147520 — a body
|
||||
// larger than its own bounding box, which is the signature of it.
|
||||
fm.Add(wires[i]);
|
||||
}
|
||||
if (!fm.IsDone()) throw std::runtime_error(_u8L("sketch loop does not bound a face"));
|
||||
// Winding-independent classification of outer vs holes — the same idiom make_extrude_regions
|
||||
// already uses for imported glyphs, which is why holed TEXT extruded correctly all along
|
||||
// while a holed SKETCH did not.
|
||||
// uses for imported glyphs, so a holed sketch extrudes as holed text does.
|
||||
ShapeFix_Face sff(fm.Face());
|
||||
sff.FixOrientation();
|
||||
return checked_profile_face(sff.Face());
|
||||
|
|
@ -1077,8 +1090,8 @@ std::vector<SketchEntity> SketchEngine::mirror_entities(
|
|||
// Reflection reverses orientation. Like the Arc branch above, this pass keeps
|
||||
// each angle with ITS point (start with p0) and lets the sweep run clockwise;
|
||||
// the reversal pass below then swaps points and angles together, giving a CCW
|
||||
// arc whose start is p0. Pairing them crosswise here, as this used to, was
|
||||
// undone by that same swap and produced the complementary arc.
|
||||
// arc whose start is p0. Pairing them crosswise here would be undone by that
|
||||
// same swap and produce the complementary arc.
|
||||
auto param = [&](const Vec2d& P) {
|
||||
const Vec2d d = P - m.center;
|
||||
const double cu = std::cos(m.rotation), su = std::sin(m.rotation);
|
||||
|
|
@ -1262,8 +1275,8 @@ bool off_one(const SketchEntity& e, double d, SketchEntity& out)
|
|||
}
|
||||
case SketchEntity::Type::Circle: {
|
||||
// A circle runs CCW (it is what a 360° CCW arc chain closes into), so the rule below
|
||||
// applies to it too: +d is the left side, the inside, and the radius SHRINKS. It used to
|
||||
// grow, so a full circle and the same outline drawn as arcs offset opposite ways.
|
||||
// applies to it too: +d is the left side, the inside, and the radius SHRINKS. Were it to
|
||||
// grow, a full circle and the same outline drawn as arcs would offset opposite ways.
|
||||
const double r = e.radius - d;
|
||||
if (r <= 1e-9) return false;
|
||||
out = e; out.radius = r; out.p0 = out.center;
|
||||
|
|
@ -2437,8 +2450,8 @@ ConstraintPlan plan_entity_constraint(const std::vector<SketchEntity>& ents,
|
|||
}
|
||||
case T::Angle: {
|
||||
// Angle between two line segments. "Line segments" is a check, not an assumption:
|
||||
// p1-p0 on a Circle is (0,0)-centre, so two circles used to pre-fill with the angle
|
||||
// between their centre POSITION vectors.
|
||||
// p1-p0 on a Circle is (0,0)-centre, so without it two circles would pre-fill with the
|
||||
// angle between their centre POSITION vectors.
|
||||
if (ents[e0].type != SketchEntity::Type::Line ||
|
||||
ents[e1].type != SketchEntity::Type::Line) {
|
||||
plan.kind = ConstraintPlan::Kind::Reject;
|
||||
|
|
@ -2574,4 +2587,10 @@ ConstraintPlan plan_entity_constraint(const std::vector<SketchEntity>& ents,
|
|||
return plan;
|
||||
}
|
||||
|
||||
void write_plan_value(std::vector<SketchEntityConstraintDef>& defs, double v)
|
||||
{
|
||||
for (auto& d : defs)
|
||||
d.value = (d.type == SketchConstraintType::Angle) ? v * M_PI / 180.0 : v;
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
#include <gp_Pln.hxx>
|
||||
#include <gp_Ax1.hxx>
|
||||
#include <gp_Ax3.hxx>
|
||||
#include <gp_Dir.hxx>
|
||||
#include <gp_Vec.hxx>
|
||||
#include <TopoDS_Wire.hxx>
|
||||
#include <TopoDS_Shape.hxx>
|
||||
|
|
@ -202,6 +203,10 @@ struct ConstraintPlan {
|
|||
// e2 is the axis-line pick Symmetric needs (def.ec); every other type ignores it.
|
||||
ConstraintPlan plan_entity_constraint(const std::vector<SketchEntity>& ents,
|
||||
int e0, int e1, int e2, SketchConstraintType type);
|
||||
// Write the value for a planned constraint into every def. The planner's prefill, and the value a
|
||||
// person types, are in display units; Angle is the one type stored otherwise (degrees shown,
|
||||
// radians stored).
|
||||
void write_plan_value(std::vector<SketchEntityConstraintDef>& defs, double v);
|
||||
|
||||
// Solve a bare entity list in place against entity-form constraints. Shared by
|
||||
// CadDocument::solve_sketch_feature (committed features) and the in-session GUI
|
||||
|
|
@ -251,6 +256,11 @@ public:
|
|||
// perpendicular to the spine along its length. The path may be open or closed;
|
||||
// for a clean solid the path's first point should sit on/near the profile plane.
|
||||
static TopoDS_Shape make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path);
|
||||
// Sweep along a helix whose axis is `binormal`: the profile keeps its angle to that axis the
|
||||
// whole way round, as a spring's or a thread's wire does (BRepOffsetAPI_MakePipeShell with a
|
||||
// fixed binormal). The moving frame of the sweep above turns a profile about a helix, so a
|
||||
// square wire would twist on its way up.
|
||||
static TopoDS_Shape make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path, const gp_Dir& binormal);
|
||||
|
||||
// Loft a solid through 2+ closed profile wires (each on its own plane), in the
|
||||
// given order. ruled=true => straight (ruled) sections; false => smooth (C2).
|
||||
|
|
|
|||
|
|
@ -168,7 +168,7 @@ infer_relations(const std::vector<SketchEntity>& entities, int new_ei,
|
|||
// function is quadratic in the sketch: a drawing with 200 equal holes yields ~20000
|
||||
// EqualRadius candidates, the batch is rejected as over-constrained, and the caller's
|
||||
// one-at-a-time fallback then runs a solve per constraint. Measured 2026-08-31: that
|
||||
// pinned the app at 95% of a core with the MCP socket unresponsive -- the same failure
|
||||
// pinned the app at 95% of a core and left it unresponsive -- the same failure
|
||||
// the axes batch above already carries a warning about. Keep the best candidate only.
|
||||
int best_ang_j = -1, best_rad_j = -1, best_tan_j = -1;
|
||||
double best_ang_err = 1e30, best_rad_err = 1e30, best_tan_err = 1e30;
|
||||
|
|
|
|||
|
|
@ -118,9 +118,9 @@ static SketchSolveResult solve_system(std::vector<SketchEntity>& entities,
|
|||
s.center = b.pt2d(G_SK, e.center.x(), e.center.y());
|
||||
s.p0 = s.center; // p0 mirrors centre for circles
|
||||
// A zero-radius circle is degenerate everywhere else (the wire builder, offset and
|
||||
// inference all reject it). It used to be seeded with radius 1 here and written
|
||||
// back, so any unrelated solve silently turned it into a 1 mm circle. It gets no
|
||||
// primitive: its centre still solves, anything needing the rim is skipped.
|
||||
// inference all reject it). It gets no primitive rather than a placeholder radius,
|
||||
// which the write-back would store, so that an unrelated solve cannot silently turn
|
||||
// it into a real circle: its centre still solves, anything needing the rim is skipped.
|
||||
if (e.radius > 1e-9) {
|
||||
s.rparam = b.P(G_SK, e.radius);
|
||||
Slvs_hEntity dist = b.E(Slvs_MakeDistance(++b.eh, G_SK, b.wp, s.rparam));
|
||||
|
|
@ -364,9 +364,9 @@ static SketchSolveResult solve_system(std::vector<SketchEntity>& entities,
|
|||
b.C(SLVS_C_PT_LINE_DISTANCE, side_of(ci, Role::Center, li) * entities[ci].radius,
|
||||
ptOf(ci, Role::Center), 0, primOf(li), 0);
|
||||
} else {
|
||||
// The arc endpoint that touches the line is the one the tangency is at. The
|
||||
// constraint used to bind the START point always, so a fillet — its start on
|
||||
// one leg, its end on the other — forced both legs parallel.
|
||||
// The arc endpoint that touches the line is the one the tangency is at.
|
||||
// Binding the START point regardless would force both legs of a fillet — its
|
||||
// start on one leg, its end on the other — parallel.
|
||||
int other = 0;
|
||||
if (valid(ci) && valid(li)) {
|
||||
const SketchEntity& A = entities[ci];
|
||||
|
|
@ -387,8 +387,8 @@ static SketchSolveResult solve_system(std::vector<SketchEntity>& entities,
|
|||
case CT::PointOnLine:
|
||||
// slvs' in-workplane point-line distance is SIGNED. A negative stored value is an
|
||||
// explicit side; a positive one (what the UI stores) keeps the side the point is on
|
||||
// now. Passing |value| forced every point to the positive side, flipping any that
|
||||
// sat on the other one across the line.
|
||||
// now. Passing |value| would force every point to the positive side, flipping any
|
||||
// that sits on the other one across the line.
|
||||
if (std::abs(c.value) < 1e-9)
|
||||
b.C(SLVS_C_PT_ON_LINE, 0, ptOf(c.ea, c.ra), 0, primOf(c.eb), 0);
|
||||
else
|
||||
|
|
@ -398,7 +398,7 @@ static SketchSolveResult solve_system(std::vector<SketchEntity>& entities,
|
|||
break;
|
||||
case CT::PointOnObject:
|
||||
// Point (ea,ra) lies on entity edge eb: a circle or arc rim -> PT_ON_CIRCLE (slvs
|
||||
// takes both), otherwise the segment line -> PT_ON_LINE. An arc used to fall to
|
||||
// takes both), otherwise the segment line -> PT_ON_LINE. An arc must not fall to
|
||||
// PT_ON_LINE, which is not an equation about an arc at all.
|
||||
if (valid(c.eb) && (entities[c.eb].type == SketchEntity::Type::Circle ||
|
||||
entities[c.eb].type == SketchEntity::Type::Arc))
|
||||
|
|
@ -546,20 +546,20 @@ static SketchSolveResult solve_system(std::vector<SketchEntity>& entities,
|
|||
// entity in the sketch, constrained or not, at 2 params per point — so a sketch of about 480 lines
|
||||
// is the last one that fits, and the very next one comes back TOO_MANY_UNKNOWNS.
|
||||
//
|
||||
// What that did, before this: DesignSketchTool::try_add_constraints rolls the whole batch back
|
||||
// when the solve fails, so the auto-constraint pass over a large sketch dropped EVERY constraint
|
||||
// it had just inferred. Measured on the rig — 480 lines: 960 constraints, dof 480. 520 lines:
|
||||
// 0 constraints, dof unknown. Nothing was said, and from there on no dimension and no constraint
|
||||
// could ever be applied to that sketch, because each attempt re-solved the same oversized system
|
||||
// and was rejected in turn. A typed length simply did nothing.
|
||||
// A failed solve is not local: DesignSketchTool::try_add_constraints rolls the whole batch back
|
||||
// when the solve fails, so solving an oversized sketch as one system drops EVERY constraint the
|
||||
// auto-constraint pass just inferred. Solved whole, 480 lines keep all 960 inferred constraints
|
||||
// (dof 480); 520 lines keep 0 (dof unknown). Nothing says so, and from there on no dimension and
|
||||
// no constraint can be applied to that sketch, because each attempt re-solves the same oversized
|
||||
// system and is rejected in turn: a typed length simply does nothing.
|
||||
//
|
||||
// Constraints only couple entities that SHARE a point, so a sketch is naturally a set of
|
||||
// independent systems — a plate with 300 cut-outs is 301 little problems, not one big one.
|
||||
// Solving them separately keeps every one of them far under the ceiling AND is faster, since the
|
||||
// solver's work is superlinear in system size.
|
||||
//
|
||||
// The whole system is still tried FIRST, and this runs only on TOO_MANY_UNKNOWNS, so every sketch
|
||||
// that fits today keeps its exact current behaviour, including its reported degrees of freedom.
|
||||
// The whole system is tried FIRST, and this runs only on TOO_MANY_UNKNOWNS, so a sketch that fits
|
||||
// is solved as one system and reports the degrees of freedom that solve finds.
|
||||
// A genuinely over-constrained sketch still fails: the conflict lives inside one component and
|
||||
// that component still rejects it.
|
||||
// Degrees of freedom an entity has on its own, as the whole-system solve counts them.
|
||||
|
|
@ -577,6 +577,13 @@ static int natural_dof(const SketchEntity& e)
|
|||
return 0;
|
||||
}
|
||||
|
||||
int sketch_unconstrained_dof(const std::vector<SketchEntity>& entities)
|
||||
{
|
||||
int dof = 0;
|
||||
for (const SketchEntity& e : entities) dof += natural_dof(e);
|
||||
return dof;
|
||||
}
|
||||
|
||||
static SketchSolveResult solve_partitioned(std::vector<SketchEntity>& entities,
|
||||
const std::vector<SketchEntityConstraintDef>& constraints,
|
||||
int dragged_ei, Role dragged_role)
|
||||
|
|
|
|||
|
|
@ -39,6 +39,11 @@ SketchSolveResult sketch_solve_drag(std::vector<SketchEntity>& entities,
|
|||
const std::vector<SketchEntityConstraintDef>& constraints,
|
||||
int dragged_ei, SketchPointRole dragged_role);
|
||||
|
||||
// The degrees of freedom `entities` have with no constraint on them, counted as a solve counts them
|
||||
// (an ellipse is only its centre to the solver). sketch_solve answers -1 for an empty constraint
|
||||
// list, since it does not run then; this is the count such a sketch has.
|
||||
int sketch_unconstrained_dof(const std::vector<SketchEntity>& entities);
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
#include "libslic3r/CAD/ThreadStandards.hpp"
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
|
|
@ -94,4 +95,18 @@ const ThreadSpec* find_thread_standard(const std::string& name)
|
|||
return nullptr;
|
||||
}
|
||||
|
||||
const ThreadSpec* nearest_thread_standard(double diameter, bool internal)
|
||||
{
|
||||
const ThreadSpec* best = nullptr;
|
||||
double best_err = 0.0;
|
||||
for (const ThreadSpec& s : thread_standards()) {
|
||||
const double err = std::abs((internal ? s.minor_diameter_mm() : s.major_diameter_mm) - diameter);
|
||||
if (best == nullptr || err < best_err) {
|
||||
best = &s;
|
||||
best_err = err;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
|
|
|
|||
|
|
@ -36,6 +36,13 @@ const std::vector<ThreadSpec>& thread_standards();
|
|||
// Exact case-sensitive designation lookup; nullptr if not a known standard.
|
||||
const ThreadSpec* find_thread_standard(const std::string& name);
|
||||
|
||||
// The standard nearest a measured cylinder of `diameter`, as the Thread tool infers it from a
|
||||
// picked face or rim: a boss is matched on the major (nominal) diameter, a bore on the minor one,
|
||||
// since a hole to be tapped is drilled at the tap-drill size. Every series is scanned together, so
|
||||
// a 5 mm bore gives 1/4-20 UNC (minor 4.975) rather than M6 (minor 4.918); the first of equally
|
||||
// near sizes wins. nullptr only for an empty table.
|
||||
const ThreadSpec* nearest_thread_standard(double diameter, bool internal);
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -21,6 +21,9 @@ enum class LoadStrategy
|
|||
// Geometry-import policies are opt-in; opening existing projects retains its defaults.
|
||||
KeepOriginalNames = 128,
|
||||
AssembleParts = 256,
|
||||
// One of Orca's own models, such as a calibration test, loads as written: the geometry-import choices and
|
||||
// their dialogs are for a person's files, and a calibration reads values from its objects' names.
|
||||
BundledModel = 512,
|
||||
|
||||
Restore = 0x10000 | LoadModel | LoadConfig | LoadAuxiliary | Silence,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5963,12 +5963,25 @@ DynamicPrintConfig PresetBundle::config_from_gcode(const std::string &path, Forw
|
|||
if (const ConfigOption *below = base.option(key); below != nullptr && static_cast<const ConfigOptionVectorBase *>(below)->size() > 0)
|
||||
config.set_key_value(key, below->clone());
|
||||
Preset::normalize(config);
|
||||
// The block holds flush_volumes_matrix already multiplied by the multiplier the slice used, so a
|
||||
// multiplier of 1 keeps the purge volumes the file was sliced with. G-code from before 2.3.2 held the
|
||||
// plain matrix and loses a multiplier other than 1.
|
||||
for (const char *key : { "flush_multiplier", "flush_multiplier_fast" })
|
||||
if (auto *multiplier = config.option<ConfigOptionFloats>(key))
|
||||
std::fill(multiplier->values.begin(), multiplier->values.end(), 1.);
|
||||
// The block holds flush_volumes_matrix already multiplied by the multiplier the slice used
|
||||
// (GCode::append_full_config). Dividing that multiplier back out keeps the purge volumes the file was
|
||||
// sliced with while the project keeps the file's own multiplier: these settings stay with the project and
|
||||
// the printer after the preview, and every table the app recalculates later, as on a colour change, is
|
||||
// scaled by that multiplier. prime_volume_mode is not in the block, so the multiplier divided out is the
|
||||
// one this bundle's mode slices with. A nozzle with a multiplier of 0 purged nothing and keeps its empty
|
||||
// block. G-code from before 2.3.2 held the plain table, which this enlarges, so it purges what the plain
|
||||
// table does.
|
||||
const bool fast = config.opt_enum<PrimeVolumeMode>("prime_volume_mode") == PrimeVolumeMode::pvmFast;
|
||||
const auto &multipliers = config.option<ConfigOptionFloats>(fast ? "flush_multiplier_fast" : "flush_multiplier")->values;
|
||||
auto &matrix = config.option<ConfigOptionFloats>("flush_volumes_matrix")->values;
|
||||
const size_t filaments = config.option<ConfigOptionStrings>("filament_colour")->size();
|
||||
const size_t block = filaments * filaments;
|
||||
// The block is multiplied only when the matrix has one filaments x filaments block per nozzle.
|
||||
if (block > 1 && block * multipliers.size() == matrix.size())
|
||||
for (size_t nozzle = 0; nozzle < multipliers.size(); ++nozzle)
|
||||
if (multipliers[nozzle] > 0.)
|
||||
for (size_t i = nozzle * block; i < (nozzle + 1) * block; ++i)
|
||||
matrix[i] /= multipliers[nozzle];
|
||||
return config;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -679,6 +679,9 @@ public:
|
|||
// based on the user configuration.
|
||||
// If the "vendor" section is missing, enable all models and variants of the particular vendor.
|
||||
void load_installed_printers(const AppConfig &config);
|
||||
// Set the is_visible flag for filaments from the user configuration's filaments section,
|
||||
// first adding there the default filaments of each installed printer that no installed filament fits.
|
||||
void load_installed_filaments(AppConfig &config);
|
||||
|
||||
const std::string& get_preset_name_by_alias(const Preset::Type& preset_type, const std::string& alias) const;
|
||||
|
||||
|
|
@ -937,9 +940,8 @@ private:
|
|||
// Update renamed_from and alias maps of system profiles.
|
||||
void update_system_maps();
|
||||
|
||||
// Set the is_visible flag for filaments and sla materials,
|
||||
// apply defaults based on enabled printers when no filaments/materials are installed.
|
||||
void load_installed_filaments(AppConfig &config);
|
||||
// Set the is_visible flag for sla materials,
|
||||
// apply defaults based on enabled printers when no materials are installed.
|
||||
void load_installed_sla_materials(AppConfig &config);
|
||||
|
||||
// Load print, filament & printer presets from a config. If it is an external config, then the name is extracted from the external path.
|
||||
|
|
|
|||
|
|
@ -13394,9 +13394,43 @@ CLIMiscConfigDef::CLIMiscConfigDef()
|
|||
def->tooltip = L("Load and store settings at the given directory. This is useful for maintaining different profiles or including configurations from a network storage.");
|
||||
|
||||
|
||||
def = this->add("mcp", coBool);
|
||||
def->label = L("MCP server");
|
||||
def->tooltip = L("Start the MCP server for AI agents on 127.0.0.1 for this run, whatever the preference says.");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("mcp_port", coInt);
|
||||
def->label = L("MCP server port");
|
||||
def->tooltip = L("Start the MCP server for this run on this port, as --mcp does. 0 takes the port from the preference, or 13619.");
|
||||
def->cli_params = "port";
|
||||
def->min = 0;
|
||||
def->max = 65535;
|
||||
def->set_default_value(new ConfigOptionInt(0));
|
||||
|
||||
def = this->add("mcp_stdio", coBool);
|
||||
def->label = L("MCP stdio bridge");
|
||||
def->tooltip = L("Act as an MCP server on standard input and output for clients that cannot use HTTP, forwarding to the running OrcaSlicer (started with --mcp when none answers).");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("run", coString);
|
||||
def->label = L("Run a replay or script");
|
||||
def->tooltip = L("Run a replay (.json) or a Python script (.py) once the GUI is ready, then exit: 0 when it passed or finished, 1 when a step failed or the script did not finish, 2 when the file is invalid or cannot be read.");
|
||||
def->cli_params = "file";
|
||||
def->set_default_value(new ConfigOptionString());
|
||||
|
||||
def = this->add("unrestricted_scripts", coBool);
|
||||
def->label = L("Unrestricted Python scripts");
|
||||
def->tooltip = L("Let Python scripts bypass the permission checks for this run, whatever the preference says.");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("cad", coBool);
|
||||
def->label = L("Design tab");
|
||||
def->tooltip = L("Show the Design tab and offer its commands for this run, whatever the CAD feature preference says.");
|
||||
def->set_default_value(new ConfigOptionBool(false));
|
||||
|
||||
def = this->add("outputdir", coString);
|
||||
def->label = L("Output directory");
|
||||
def->tooltip = L("This is the output directory for exported files.");
|
||||
def->tooltip = L("This is the output directory for exported files. With --run, it is where the run's files go: a replay's result.json and screenshots, and the files saved without a path.");
|
||||
def->cli_params = "dir";
|
||||
def->set_default_value(new ConfigOptionString());
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@
|
|||
#include "Model.hpp"
|
||||
#include "GCode.hpp"
|
||||
#include "PrintConfig.hpp"
|
||||
#include "Preset.hpp"
|
||||
#include "Utils.hpp"
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include "Point.hpp"
|
||||
#include "libslic3r.h"
|
||||
#include <cmath>
|
||||
|
|
@ -26,6 +29,198 @@
|
|||
|
||||
namespace Slic3r {
|
||||
|
||||
namespace {
|
||||
|
||||
// A per-extruder value: the extruder's entry, the last one past the end, or `fallback` without any.
|
||||
double extruder_value(const ConfigOptionFloats* opt, int extruder_id, double fallback)
|
||||
{
|
||||
if (opt == nullptr || opt->values.empty())
|
||||
return fallback;
|
||||
return opt->values[std::min(static_cast<size_t>(std::max(extruder_id, 0)), opt->values.size() - 1)];
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool has_junction_deviation(const DynamicPrintConfig& printer)
|
||||
{
|
||||
const auto* gcode_flavor = printer.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor");
|
||||
const auto* junction_dev = printer.option<ConfigOptionFloats>("machine_max_junction_deviation");
|
||||
return gcode_flavor != nullptr && gcode_flavor->value == GCodeFlavor::gcfMarlinFirmware && junction_dev != nullptr &&
|
||||
!junction_dev->values.empty() && junction_dev->values.front() > 0.0;
|
||||
}
|
||||
|
||||
Calib_Params calib_default_params(CalibMode mode, const DynamicPrintConfig& printer, bool bowden)
|
||||
{
|
||||
Calib_Params p;
|
||||
p.mode = mode;
|
||||
switch (mode) {
|
||||
case CalibMode::Calib_Temp_Tower: p.start = 230; p.end = 190; break; // in fixed 5 °C blocks
|
||||
case CalibMode::Calib_Vol_speed_Tower: p.start = 5; p.end = 20; p.step = 0.5; break;
|
||||
case CalibMode::Calib_PA_Tower:
|
||||
case CalibMode::Calib_PA_Line:
|
||||
case CalibMode::Calib_PA_Pattern: {
|
||||
const bool pattern = mode == CalibMode::Calib_PA_Pattern;
|
||||
p.start = 0.;
|
||||
p.end = bowden ? 1.0 : pattern ? 0.08 : 0.1;
|
||||
p.step = pattern ? (bowden ? 0.05 : 0.005) : (bowden ? 0.02 : 0.002);
|
||||
p.print_numbers = mode != CalibMode::Calib_PA_Tower;
|
||||
break;
|
||||
}
|
||||
case CalibMode::Calib_Retraction_tower: p.start = 0; p.end = 2; p.step = 0.1; break;
|
||||
case CalibMode::Calib_VFA_Tower: p.start = 40; p.end = 200; p.step = 10; break;
|
||||
case CalibMode::Calib_Input_shaping_freq:
|
||||
p.freqStartX = p.freqStartY = 15;
|
||||
p.freqEndX = p.freqEndY = 110;
|
||||
p.start = 0.15; // the damping ratio the test prints with
|
||||
break;
|
||||
case CalibMode::Calib_Input_shaping_damp:
|
||||
p.freqStartX = p.freqStartY = 30;
|
||||
p.start = 0.;
|
||||
p.end = 0.4;
|
||||
break;
|
||||
case CalibMode::Calib_Cornering:
|
||||
if (has_junction_deviation(printer)) {
|
||||
p.start = 0.;
|
||||
p.end = 0.25;
|
||||
} else {
|
||||
p.start = 1.;
|
||||
p.end = 15.;
|
||||
}
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
std::pair<double, double> cornering_end_limits(const DynamicPrintConfig& printer)
|
||||
{
|
||||
return has_junction_deviation(printer) ? std::make_pair(0.3, 0.25) : std::make_pair(100., 20.);
|
||||
}
|
||||
|
||||
double clamp_calib_temp(double temperature) { return std::clamp(temperature, kCalibTempMin, kCalibTempMax); }
|
||||
|
||||
double round_calib_temp(double temperature) { return std::floor(temperature / kCalibTempBlock) * kCalibTempBlock; }
|
||||
|
||||
CalibParamsError check_calib_params(const Calib_Params& p, const DynamicPrintConfig& printer)
|
||||
{
|
||||
using E = CalibParamsError;
|
||||
// RepRapFirmware takes one frequency range for both axes, so its dialogs have no Y fields.
|
||||
const auto* flavor = printer.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor");
|
||||
const bool rrf = flavor != nullptr && flavor->value == GCodeFlavor::gcfRepRapFirmware;
|
||||
switch (p.mode) {
|
||||
case CalibMode::Calib_Temp_Tower:
|
||||
return p.start > kCalibTempMax || p.end < kCalibTempMin || p.end > p.start - kCalibTempBlock ? E::Range : E::None;
|
||||
case CalibMode::Calib_Vol_speed_Tower: return p.start <= 0 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None;
|
||||
case CalibMode::Calib_PA_Tower:
|
||||
case CalibMode::Calib_PA_Line:
|
||||
case CalibMode::Calib_PA_Pattern: {
|
||||
if (p.start < 0 || p.step < 10 * EPSILON || p.end < p.start + p.step)
|
||||
return E::Range;
|
||||
// PA Line and PA Pattern are drawn on the belt but not validated there yet.
|
||||
const auto* belt = printer.option<ConfigOptionBool>("belt_printer");
|
||||
if (belt != nullptr && belt->value && p.mode != CalibMode::Calib_PA_Tower)
|
||||
return E::BeltMethod;
|
||||
// Accelerations are larger than speeds, so this catches the two lists swapped.
|
||||
if (!p.accelerations.empty() && !p.speeds.empty() &&
|
||||
*std::min_element(p.accelerations.begin(), p.accelerations.end()) <= *std::max_element(p.speeds.begin(), p.speeds.end()))
|
||||
return E::AccelBelowSpeed;
|
||||
return E::None;
|
||||
}
|
||||
case CalibMode::Calib_Retraction_tower: return p.start < 0 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None;
|
||||
case CalibMode::Calib_VFA_Tower: return p.start <= 10 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None;
|
||||
case CalibMode::Calib_Input_shaping_freq:
|
||||
if (p.freqStartX < 0 || p.freqEndX > 500 || p.freqStartX >= p.freqEndX ||
|
||||
(!rrf && (p.freqStartY < 0 || p.freqEndY > 500 || p.freqStartY >= p.freqEndY)))
|
||||
return E::Range;
|
||||
return p.start < 0 || p.start >= 1 ? E::Damping : E::None;
|
||||
case CalibMode::Calib_Input_shaping_damp:
|
||||
if (p.freqStartX < 0 || p.freqStartX > 500 || (!rrf && (p.freqStartY < 0 || p.freqStartY > 500)))
|
||||
return E::Range;
|
||||
return p.start < 0 || p.end > 1 || p.start >= p.end ? E::Damping : E::None;
|
||||
case CalibMode::Calib_Cornering:
|
||||
return p.start < 0 || p.end > cornering_end_limits(printer).first || p.start >= p.end ? E::Range : E::None;
|
||||
default: return E::None;
|
||||
}
|
||||
}
|
||||
|
||||
std::string belt_temp_tower_asset(const Calib_Params& params)
|
||||
{
|
||||
const int t_start = (int) lround(params.start);
|
||||
const int t_end = (int) lround(params.end);
|
||||
return Slic3r::resources_dir() + "/calib/temperature_tower/belt_temp_tower_" + std::to_string(t_start) + "_" +
|
||||
std::to_string(t_end) + ".stl";
|
||||
}
|
||||
|
||||
std::vector<double> vfa_candidate_layer_heights(const PresetCollection& prints, const DynamicPrintConfig& printer, int extruder_id)
|
||||
{
|
||||
const double machine_min_lh = extruder_value(printer.option<ConfigOptionFloats>("min_layer_height"), extruder_id, 0.0);
|
||||
const double machine_max_lh = extruder_value(printer.option<ConfigOptionFloats>("max_layer_height"), extruder_id, 0.0);
|
||||
std::vector<double> candidates;
|
||||
for (const Preset& preset : prints.get_presets()) {
|
||||
if (!preset.is_compatible || preset.is_default)
|
||||
continue;
|
||||
const auto* lh_opt = preset.config.option<ConfigOptionFloat>("layer_height");
|
||||
if (lh_opt == nullptr || lh_opt->value <= 0.0)
|
||||
continue;
|
||||
const double lh = lh_opt->value;
|
||||
if ((machine_min_lh > 0.0 && lh < machine_min_lh - 1e-6) || (machine_max_lh > 0.0 && lh > machine_max_lh + 1e-6))
|
||||
continue;
|
||||
candidates.push_back(lh);
|
||||
}
|
||||
std::sort(candidates.begin(), candidates.end());
|
||||
candidates.erase(std::unique(candidates.begin(), candidates.end(), [](double a, double b) { return std::abs(a - b) < 1e-6; }),
|
||||
candidates.end());
|
||||
return candidates;
|
||||
}
|
||||
|
||||
VfaSpeedFit fit_vfa_speed(const Calib_Params& params, const DynamicPrintConfig& printer, const DynamicPrintConfig& print,
|
||||
const DynamicPrintConfig& filament, bool auto_adjust, const std::vector<double>& candidate_layer_heights)
|
||||
{
|
||||
const int extruder_id = std::max(params.extruder_id, 0);
|
||||
const double nozzle_diameter = extruder_value(printer.option<ConfigOptionFloats>("nozzle_diameter"), extruder_id, vfa_base_nozzle_diameter);
|
||||
double preset_lh = nozzle_diameter / 2.0;
|
||||
if (const auto* lh_opt = print.option<ConfigOptionFloat>("layer_height"))
|
||||
if (lh_opt->value > 0.0)
|
||||
preset_lh = lh_opt->value;
|
||||
double line_width = print.get_abs_value("outer_wall_line_width", nozzle_diameter);
|
||||
if (line_width <= 0.0)
|
||||
line_width = print.get_abs_value("line_width", nozzle_diameter);
|
||||
if (line_width <= 0.0)
|
||||
line_width = nozzle_diameter;
|
||||
|
||||
VfaSpeedFit fit;
|
||||
fit.max_vol_speed = extruder_value(filament.option<ConfigOptionFloats>("filament_max_volumetric_speed"), extruder_id, 0.0);
|
||||
// The tower prints at half the nozzle diameter when scaled to the nozzle, else at the process's layer height.
|
||||
fit.default_lh = params.nozzle_based_resize ? nozzle_diameter / 2.0 : preset_lh;
|
||||
// The fastest outer wall the volumetric limit allows at a layer height.
|
||||
auto speed_limit = [&](double lh) -> double {
|
||||
const double mm3_per_mm = Flow(line_width, lh, nozzle_diameter).mm3_per_mm();
|
||||
return mm3_per_mm > 0.0 ? fit.max_vol_speed / mm3_per_mm : 1e9;
|
||||
};
|
||||
if (fit.max_vol_speed <= 0.0 || nozzle_diameter <= 0.0)
|
||||
return fit;
|
||||
fit.speed_limit = speed_limit(fit.default_lh);
|
||||
if (params.end <= fit.speed_limit)
|
||||
return fit;
|
||||
fit.kind = VfaSpeedFit::Clamped;
|
||||
// Only a tower scaled to the nozzle may change its layer height.
|
||||
if (!auto_adjust || !params.nozzle_based_resize || candidate_layer_heights.empty())
|
||||
return fit;
|
||||
// The largest candidate up to the default layer height that reaches the end speed, the smallest change.
|
||||
for (auto it = candidate_layer_heights.rbegin(); it != candidate_layer_heights.rend(); ++it)
|
||||
if (*it <= fit.default_lh + 1e-6 && speed_limit(*it) >= params.end) {
|
||||
fit.kind = VfaSpeedFit::ReducedLayerHeight;
|
||||
fit.layer_height = *it;
|
||||
return fit;
|
||||
}
|
||||
fit.kind = VfaSpeedFit::LoweredEnd;
|
||||
fit.layer_height = candidate_layer_heights.front();
|
||||
fit.end = std::floor(speed_limit(fit.layer_height) / params.step) * params.step; // a step multiple it reaches
|
||||
if (fit.end < params.start + params.step)
|
||||
fit.end = params.start + params.step;
|
||||
return fit;
|
||||
}
|
||||
|
||||
// Calculate the optimal Pressure Advance speed
|
||||
float CalibPressureAdvance::find_optimal_PA_speed(const DynamicPrintConfig &config, double line_width, double layer_height, int extruder_id, int filament_idx)
|
||||
{
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue