From afd6a5c5848cd12209a4d382c237efbf0d8f0b38 Mon Sep 17 00:00:00 2001 From: The Nomad Date: Mon, 26 Oct 2026 19:59:35 -0400 Subject: [PATCH] Send to Slicer: send the selected bodies to a slicer (#2595) (#3600) * Add Open in Slicer for the selected bodies (#2595) One command saves the selected bodies as a 3MF in millimetres (an STL if the 3MF can not be written) and opens it in the last slicer used. It is on the File menu, the Mesh tab and the body right-click menu. The first time, or when that slicer is gone, it asks which one with the same list Save as mesh uses. The Save as mesh dialog is unchanged. * Send slicer files to a private per-user folder (#2595) Files sent to a slicer used to go to a shared folder in the temp directory. They now go to the user cache folder (mode 0700 on Unix), under a name that stays the same for the same design and bodies, so sending again replaces the file and the slicer can reload it. The file is written to a temporary name and renamed into place. If the name can not be replaced, as on Windows while the slicer holds the file open, the copy gets a number and the status line says so. Files older than seven days are deleted at startup. The first send tells the user that sending again replaces the open file, and so does the tooltip of Open in Slicer. Send to slicer in Save as mesh uses the same path. * Open files in a running slicer (#2595) PrusaSlicer, SuperSlicer, Bambu Studio and Cura are started with --single-instance, so a slicer that is already open loads the file instead of opening a second window. OrcaSlicer has no such flag and is left alone, and macOS bundles are single-instance already. PrusaSlicer 3.0 ships a launcher entry that already carries --single-instance-on-url; it keeps that one and never gets a second flag. It is a preference, on by default, and scripts can pass single_instance. Preferences also gets a button to forget the slicer Open in Slicer remembers. * List slicers the desktop entries say open 3MF or STL (#2595) On Linux the scan of desktop entries now also lists a program that claims 3MF or STL in MimeType, even when it is not in our table of known slicers. The table still supplies names, ids, icons and flags for the ones it knows. Entries marked NoDisplay or Hidden are skipped, and so are terminal programs and SolidCraft itself. The existing size and count limits stay. The Windows scan now looks inside a Prusa3D folder, where PrusaSlicer installs itself. * Only start slicers the user can see or chose (#2595) file.save_mesh took a slicer parameter that could be any executable path, so a script or an MCP client could run any program. The slicer now has to be one of the detected slicers (by id or name) or a program the user already added under Custom, which the app hands to the engine from its settings. The same rule holds for file.open_in_slicer. The agent chat already asked before any file command; its question now also names the slicer. * Review fixes for Open in Slicer (#2595) The file name hash keeps all 64 bits instead of 32. When Open in Slicer has to fall back to an STL, the status line now says so. The engine test that sets the chosen programs clears them again. The unused "could not make the folder" message is gone from the catalogs, and the docs say plainly that finding slicers by file type is Linux only. * Keep unsaved designs apart and hide Open in Slicer in the browser (#2595) Two unsaved designs with the same name and body names got the same file in the slicer folder. Every document now has a uid that is new for each New, Open and Recover and stays the same for the life of the document, and the file name uses it (with the process id) until the design has a path. At the first Save As the name changes to the path-based one, so the slicer gets one new file; the old one goes with the seven-day sweep. The browser can not start a program, so Open in Slicer is now disabled there: the engine command reports why, the File menu item and the body and component right-click items are greyed, and starting it anyway says so on the status line instead of opening a dialog. The Save as mesh dialog keeps its browser guard for the open flow too. * Put the Session doc comment back on Session (#2595) The new NEXT_UID static had landed between the doc comment and the struct it describes. * List every install of a slicer, and test the first Save As (#2595) Detection kept one entry per known slicer, so a system PrusaSlicer 2.9 and a Flatpak 3.0 beta showed up as one. Every distinct install is listed now. The same program found twice, through a desktop entry and through PATH, is still one. When a slicer has several installs, each gets an id made from where it was found (prusa#comprusa3dprusaslicer) that stays the same on every run, and a name worked out from its command and location without running anything: PrusaSlicer (system), PrusaSlicer (Flatpak, beta), PrusaSlicer (AppImage). A lone install keeps its plain id and name. The plain id or name still picks the first install, so a remembered "prusa" keeps working. Single-instance flags and the other per-slicer behaviour go by the id without the install part. Also a test that the first Save As changes the file name once and later sends keep the name that comes from the saved path. * Start PrusaSlicer 3.0 first and send the file once it is ready (#2595) PrusaSlicer 3.0 starts through slic3r-app-launcher, which ignores a file given at a cold start whatever the flag, and loads it over D-Bus when an instance is already running. A small table in slicers.rs names such slicers by their command; today it holds that launcher, so PrusaSlicer 2.9 and OrcaSlicer are untouched. Ready means a name starting with com.prusa3d.prusaslicer.BroadcastListener. is on the session bus, read from busctl --user list with no new dependency. If busctl is missing or fails, nobody waits and the file is sent as before. When the slicer is not ready, Open in Slicer starts it without the file and looks every 200 ms for up to 10 seconds. The wait runs on another thread, so the window stays live, and the status line says Starting PrusaSlicer. Once the name appears the file is sent with the same arguments as before. If the limit passes, the status line says the slicer did not respond, that the file is already saved, and to send again. A second click during the wait only repeats the Starting line, so there is one launch and one send. Scripts calling file.open_in_slicer wait inside the command by default, or pass wait: return or no. * Always show the slicer picker for Open in Slicer (#2595) File > Open in Slicer, the Mesh tab entry and the right-click entry now always open the picker, with the slicer used last time pre-selected, so the usual case is one click or Enter. Scripts and file.open_in_slicer with a slicer still send without a dialog. The preference button that forgot the remembered slicer is gone: it could no longer make anything ask again, and it did not clear the pre-selection either. The guide says how it works now. * Leave Bambu Studio out of the single-instance list (#2595) Open files in a running slicer now adds --single-instance for PrusaSlicer, SuperSlicer and Cura only. Bambu Studio is started as it is, so it may open a second window. A test pins that, for the detected slicer and for one the user picked as a custom program. The guide and the preference tooltip no longer name Bambu Studio as getting the flag. * Sort the English catalog and leave features.md to the generator (#2595) cargo xtask lists wanted one message moved in en.json after the rebase. docs/features.md is written by the Generated files workflow on main, so the row I had added by hand is gone from this branch; the workflow adds Open in Slicer when it lands. * Drop the unused folder message from the Vietnamese catalog (#2595) Vietnamese arrived on main after I removed ui.save_mesh_temp_failed from the other catalogs, so the check that every translated id exists in English failed on it. Nothing uses the message any more. * Say so when a started slicer can not be found again (#2595) After Open in Slicer had started a slicer on its own, a failure to look it up again to send the file just returned, so the status line stayed on Starting and then nothing. It now says the slicer was started, that it can not be found to send the file, and where the file is saved. A test covers it. * Say why a failed busctl ends the wait (#2595) If busctl fails partway through a wait, the wait stops and the file is sent, the same as when busctl can not be run at all. That is on purpose: a file sent too early is dropped quietly and costs one more send. A comment in wait_for_ready says so. * Keep the readiness wait inside its limit (#2595) wait_until asked the probe before checking the deadline, including right after a sleep, so a yes could be accepted after the limit, and busctl ran with no timeout, so one look could outlast the whole wait. The deadline is checked first now, the probe is told how much time is left, and busctl is given at most two seconds (less near the end of a wait) and is killed after that. A hung busctl counts as not telling, which sends the file as before. This covers the first look on the UI thread too. Tests cover a slow probe, the shrinking time left, and a fake busctl that hangs, answers and fails. * Send the file that was already written once the slicer is ready (#2595) When the wait for a started slicer ended, the UI ran file.open_in_slicer a second time. That exported the design again on the UI thread, from whatever the session looked like by then, and could write a numbered copy while the timeout message still named the first file. The wait now keeps the slicer it found and the answer of the first call, and opens the file that was written. A test changes the design during the wait and shows the same file is sent, is not written again, no command runs, and no second file appears. * Send with the single-instance flag after starting a slicer (#2595) After Open in Slicer has started a launcher that needs a start first, the file has to reach the instance that is now running, so the send that follows a start carries --single-instance whatever the preference says. A normal send, to a slicer that was already up, still follows the preference. A comment in both places says why. The test uses a plain launcher command with the preference off: the normal send has no flag and the send after a start has it. * Find the remembered slicer again after an uninstall (#2595) With two installs the remembered key is prusa#prusaslicer. Remove the other install and the lone one is plain prusa, which matched neither the exact key nor the plain-key fallback, so the picker fell back to the first slicer in the list, maybe a different one. The key is now also matched by the part before the #, so the same slicer is pre-selected. A test covers the lone install, a plain key with two installs, an exact key, and that another slicer is never picked. * Say a second click did not send anything while a slicer starts (#2595) While a started slicer is being waited for, another click showed Starting even when it had picked another slicer or other bodies. It now says it is still waiting for that slicer and that nothing else was sent. The test checks the wording and that it names the slicer being waited for. * Label macOS installs by their application (#2595) An open -a command resolved its program to /usr/bin/open, so every application on a Mac was labelled system. Labels for open commands now come from the .app path: /Applications is system and a folder under home is shown as ~/Applications. A test with two PrusaSlicer.app bundles and a made-up home checks both labels and that the ids differ. * Pick the same place for a program found twice every time (#2595) When two desktop files, or a desktop file and PATH, pointed at one program, the first one read was kept and its file name went into the id, so the ids could change with the order the folders were read in even though nothing was installed or removed. The place that sorts first now speaks for the program. A test with two aliases and a second install lists them with the folders in both orders and gets the same ids and commands. * Treat flatpak run spelled two ways as one install (#2595) flatpak run ... and /path/to/flatpak run ... with the same arguments had different install keys, so one invocation could be listed twice. The launcher is now compared by its file name and the arguments are kept, so both give the same key, while a different branch is still its own install. The test uses a real launcher file so the full-path entry is not skipped as stale. * Say plainly that a late yes is accepted on purpose (#2595) The comment on wait_until said a slow probe could not accept a yes that came too late. That was not what the code does: no probe is started after the limit, but one already running may finish and its yes is taken, because the file should still go. The comment now says so, with the bound: the limit plus that last probe, which in production is given the time left and so ends by the limit. A test has a probe that runs past the limit and says yes, and checks it is accepted and the wait stays within limit plus the probe time, and that a probe that says no is not followed by another. * Give reading busctl the same deadline as running it (#2595) After busctl exited, the output was read with a join that could wait forever if a process it left behind kept the pipe open. The reader now hands the text back over a channel and the wait uses the time that is left of the same limit, and gives up with nothing otherwise. The polling sleep no longer overshoots the time left either. A test uses a fake busctl that backgrounds a sleep with its output inherited and exits at once: the call returns within its limit. * Tell two different flatpak launchers apart (#2595) Comparing only the file name of the launcher made /opt/tool-a/flatpak run ... and /usr/bin/flatpak run ... with the same arguments one install even when they are different programs. The launcher is now found the way any program is, through PATH and with links followed, and its name stands in only where it can not be found. The test has flatpak on PATH and the same file by its path as one install, a different executable of the same name as a second, a different branch as a third, and the fallback when there is no PATH. * Keep waiting when busctl is slow, send only when it is missing or fails (#2595) Since the busctl timeout, a slow busctl came back as "can not tell", and that was read as send now. One slow look, likely just when a cold PrusaSlicer 3.0 is starting under load, ended the wait and sent the file early, which gets dropped. The look now says why it has nothing: slow means not up yet, so the wait goes on to its limit and then reports that the slicer did not respond; a missing or failing busctl still means it can not be told and the file is sent. The comments name only those two cases. Tests use fake busctl programs: one that hangs keeps the wait going to the limit and times out, a missing one sends at once, one that says not up and then fails sends, and one that names the slicer is ready. * Do not open an empty path when the answer had no file (#2595) If the answer kept for a started slicer had no path, the send ran open with an empty string. The tick now says there is no file to send and starts nothing. The test gives a wait with no path, checks the error line, and that the fake slicer was never run. * Drop the unused folder message from the Danish catalog (#2595) Danish arrived on main with ui.save_mesh_temp_failed, which this branch removed from English because nothing uses it any more, so the check that every translated id exists in English failed. The entry is gone from the Danish catalog too. * Always start the 3.0 launcher with the single-instance flag (#2595) A hand run showed that starting the PrusaSlicer 3.0 launcher with no file while a 3.0 is already running forwards to it and exits when the flag is there, but opens a second full window when it is not. A slow first look at the bus can start the launcher twice, and with the preference off the flag was stripped. A slicer that has to be started first now keeps the flag on that start whatever the preference says, the same reasoning as the send after a start; when nothing runs the flag does no harm. A normal send with the preference off still has none. The test covers the launcher entry, a bare launcher command, a normal send and a slicer that is not on the table. * Swap --single-instance-on-url where it does not hand the file over (#2595) A hand run on the PrusaSlicer 2.9.6 Flatpak showed that its entry's --single-instance-on-url does not forward a file to the running instance: every send opened a new one, three after a cold start and two sends. With plain --single-instance the second process finds the first, forwards, and exits. So when a command carries --single-instance-on-url and the slicer is not on the wait table, that is, not the 3.0 launcher, it is replaced by --single-instance, with the file markers handled as before, when the preference is on, and stripped when it is off. On the 3.0 launcher the flag does forward and stays. The comment on the rule says why. A test uses the real 2.9.6 and 3.0 Flatpak command lines. * Cut long slicer names to fit the picker (#2595) With installs listed on their own, a name like PrusaSlicer (Flatpak, master) is wider than its row. The list painted it with no limit, so it ran out of the popup, and the closed selector wrapped it onto a second line. The list now lays the name out on one line that ends in an ellipsis when it does not fit, the selector truncates, and the full name is in the tooltip when it was cut (for a program the user added, ahead of the delete hint). A test checks that a long name is cut to one line within the width and a short one is left alone. * Keep the 3.0 launcher's flag on a send whatever the preference says (#2595) A hand run with the single-instance preference off showed the 3.0 launcher needs its flag on a send too, not only on a start: a cold start with a file and no flag loaded nothing, and a send to a running 3.0 left a launcher process that never forwarded. A slicer on the wait table now gets the flag on every launch, as it already did when started alone. The doc comment says why. The preference text, in English, Japanese and Chinese, and the guide now say that PrusaSlicer 3.0 is the exception to turning this off. The tests that took the flag away with the preference off now expect it, for the launcher entry, a bare launcher command and the 3.0 Flatpak line; the test of the send in the UI checks the first send carries it. * Keep the install-flag swap to PrusaSlicer, found by what it is (#2595) The swap of --single-instance-on-url for --single-instance ran for any program whose command had the flag, so another program with that flag would have been rewritten. It is now a PrusaSlicer rule: it applies to a slicer recognised as PrusaSlicer by its identity, its id or, for a program the user picked, the name it goes by, never by a version number. The single-instance table uses the same identity check. A test keeps the flag of a program that is not PrusaSlicer, strips it when the preference is off, and swaps it for a picked program named PrusaSlicer. * Do not promise a hard bound in the wait comment (#2595) The comment on wait_until said the production probe ends by the limit. Its clock starts after the process is spawned, and killing and reaping the process and scheduling are not bounded by it, so it is a polling and read budget with process overhead on top. The comment says that. Comment only. * Tell PrusaSlicer 2 from 3 by the installed version (#2595) PrusaSlicer 2 and 3 need different handling, and the rules had to guess from the command line. Each install of PrusaSlicer now carries its major version, read when it is detected from the release at the top of its appstream metadata and never by running the program: a Flatpak's own files (the branch the command names, else the current one), or the metainfo file beside a desktop entry. PrusaSlicer older than 3 is sent the file with --single-instance in place of --single-instance-on-url, which does not hand a file over there, and is not waited for. PrusaSlicer 3 and newer keeps the launcher's flag, is started on its own, waited for, and sent the file. When the version can not be read, the command decides as before: the slic3r-app-launcher launcher counts as 3, and any other entry is left as it is. A program that is not PrusaSlicer is untouched whatever its flags. Tests use metadata fixtures, no Flatpak: 2.9.6, 3.0.0-alpha10, a branch that is not installed, a system package, an unreadable version with and without the launcher, and a non-PrusaSlicer program with the same flag. * Make the busctl wait tests steady under load (#2595) One of them failed once in a full run at its first assertion and passed alone. A script that has only just been written can fail to start (text file busy) while another test forks, and that reads as a busctl that is missing. The fake programs are now started once, patiently, with a flag they answer at once, before a test relies on them; a hanging one uses exec so it is killed cleanly. The time bounds that could trip on a busy machine are several seconds now, and the checks are on outcomes: not ready and keeps waiting, send now, and the number of looks. Thirty runs alone, thirty of the whole slicers filter and thirty of the busctl tests under eight busy loops all pass. * Say what the busctl reader thread leaves behind (#2595) The thread that reads busctl output is left to end when the pipe closes. A busctl that answered but left a process holding its stdout reads as slow, and every poll of such a bus can leave one blocked reader behind until that process lets go. A comment next to the thread says so. Comment only. * Make Save as mesh a plain export (#2595) Save as mesh asked for the bodies and the format, and could also send the file to a slicer with a checkbox and a slicer list. Sending now has its own command, so the checkbox, the list and the Send label are gone from this dialog: bodies, format, a file dialog, Save. The two settings that only the checkbox used, save_mesh_send and save_mesh_slicer, are no longer kept; a settings file that still has them loads, and they are ignored. The strings only they used are gone from the catalogs. The slicer list stays in the dialog of Open in Slicer. file.save_mesh keeps its slicer parameter for scripts. The guide describes the two as separate. * Rename Open in Slicer to Send to Slicer (#2595) The command sends a file to a slicer rather than opening one, and a later Send to App can share the name. File menu, Mesh tab, right-click menus, the dialog button, status lines, the guide and the English, Japanese and Chinese strings now say Send to Slicer, and the command id file.open_in_slicer is file.send_to_slicer. It is new in this change, so there is no alias. The remembered slicer is stored as send_slicer, and the question the agent chat asks says send to. Module and type names stay as they are. * Put the send targets in one table and one send pipeline (#2595) The known slicers, the list of slicers with a single-instance flag and the rule for slicers that must be started and waited for were three separate things. They are one table of targets now: id, label, kind, names and program files, accepted formats and the default, how the file is handed over, the single-instance flag, the version from which PrusaSlicer's on-url flag hands a file over, and the wait-for-ready rule. Programs that are not in the table are slicers with the same defaults. The kind is slicer, the only one so far; its comment says it is where a later Send to App would plug in. The send itself is one function: write the bodies, find the target, start it and wait if its rule says so, hand the file over, report. Detection and resolution take a kind. Nothing changes for what already worked. file.save_mesh keeps its slicer parameter, now through the same function, with its export arguments and result unchanged: a cold PrusaSlicer 3 is started and waited for before the file goes, and it accepts the program path of a detected slicer as file.slicers lists it (file.slicers gives it as program). A path is accepted only when it is the program of exactly one detected target, and that target's own command and arguments run; a launcher several entries share, such as /usr/bin/flatpak, is refused as ambiguous, and any path nobody listed or chose is refused. The parameter and the code say it may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, which is a possibility and not a plan. Tests go through file.save_mesh itself for the two reported failures, a listed AppImage path and a cold PrusaSlicer 3 that is waited for, with the slicers and the busctl made up; and they check that the result and the file are what an export without a slicer gives, and that a path that is not listed, or is shared by two entries, writes nothing. The pipeline has its own tests: a cold launcher waited for, one already up, wait return, and one that never comes up. A test of save_mesh that shared a file name with another is given its own. * Keep an AppImage's id through an upgrade (#2595) When a slicer has several installs, each gets an id made from where it was found. For an AppImage that was its file name, which carries the version, so upgrading it changed the id and the remembered choice missed. The id is now made of the slicer's id, the fact that it is an AppImage and a short hash of its folder, so a new version that replaces the old one in the same folder keeps the id, and the same AppImage in another folder is its own install. Two versions kept side by side in one folder are two installs: while both are there, their file names are added to their ids to tell them apart. A remembered id is found again only when it names exactly one install. An id that was one AppImage and is now two versions, or a plain id that is now several installs, is treated as not remembered, so the picker starts from the first entry as on a first run and does not quietly pick another install; a single install left of the same slicer is still found, as before. Installs that are not AppImages are told apart as before. An id from before this change no longer matches. Tests cover an upgrade, two versions side by side, a second folder, and the picker's side of each case. * Add Open with EasyPrint to Send to Slicer EasyPrint is Printables' slicer in the browser. It's a plain text row in the Send to Slicer dialog, backed by a new file.open_in_easyprint command. The command exports the bodies as a 3MF (or STL), hands them to the host to upload to slicer.printables.com/import, and the app opens the link that comes back. The desktop app uploads with ureq and the browser build with fetch, so this is the one send target that works on the web. The model leaves the machine, so the command refuses without consent: true, the dialog asks once and remembers, and an AI agent's request asks first. A model over 100 MB is refused before anything is sent, and a failed upload shows as an error with the reason. The chat's privacy note said SolidCraft sends nothing anywhere, which isn't true any more, so it now says that about the chat. New strings are in every catalog. * Place Send to Slicer on the Insert Files panel --- apps/solidcraft-web/Cargo.toml | 2 +- apps/solidcraft-web/src/easyprint.rs | 40 + apps/solidcraft-web/src/main.rs | 3 + apps/solidcraft/src/main.rs | 19 + assets/locales/cs.json | 12 +- assets/locales/da.json | 12 +- assets/locales/de.json | 12 +- assets/locales/en.json | 25 +- assets/locales/es.json | 12 +- assets/locales/fr.json | 18 +- assets/locales/gl.json | 12 +- assets/locales/hu.json | 12 +- assets/locales/id.json | 12 +- assets/locales/it.json | 12 +- assets/locales/ja.json | 25 +- assets/locales/ko.json | 12 +- assets/locales/ms.json | 12 +- assets/locales/nb.json | 3 - assets/locales/nl.json | 12 +- assets/locales/pl.json | 12 +- assets/locales/pt-BR.json | 12 +- assets/locales/ro.json | 12 +- assets/locales/ru.json | 12 +- assets/locales/sv.json | 12 +- assets/locales/tr.json | 12 +- assets/locales/uk.json | 12 +- assets/locales/vi.json | 12 +- assets/locales/zh-TW.json | 12 +- assets/locales/zh.json | 25 +- crates/engine/src/cmd/file.rs | 104 +- crates/engine/src/cmd/file_easyprint.rs | 68 + crates/engine/src/cmd/file_send.rs | 225 ++++ crates/engine/src/easyprint.rs | 116 ++ crates/engine/src/lib.rs | 23 + crates/engine/src/slicer_files.rs | 178 +++ crates/engine/src/slicers.rs | 1526 +++++++++++++++++++++-- crates/engine/src/tests/mesh_convert.rs | 326 ++++- crates/ui-egui/src/agent_chat/gate.rs | 30 +- crates/ui-egui/src/context_menu.rs | 12 +- crates/ui-egui/src/dialogs_dense.rs | 2 +- crates/ui-egui/src/dialogs_save_mesh.rs | 649 +++++++++- crates/ui-egui/src/easyprint_ui.rs | 236 ++++ crates/ui-egui/src/lib.rs | 30 +- crates/ui-egui/src/prefs.rs | 16 +- crates/ui-egui/src/prefs/general.rs | 6 + crates/ui-egui/src/toolbar.rs | 6 + crates/ui-egui/src/workspace.rs | 2 +- docs/book/src/guide/files.md | 49 +- 48 files changed, 3727 insertions(+), 277 deletions(-) create mode 100644 apps/solidcraft-web/src/easyprint.rs create mode 100644 crates/engine/src/cmd/file_easyprint.rs create mode 100644 crates/engine/src/cmd/file_send.rs create mode 100644 crates/engine/src/easyprint.rs create mode 100644 crates/engine/src/slicer_files.rs create mode 100644 crates/ui-egui/src/easyprint_ui.rs diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.toml index b42a04ce7..2339990a3 100644 --- a/apps/solidcraft-web/Cargo.toml +++ b/apps/solidcraft-web/Cargo.toml @@ -37,5 +37,5 @@ web-sys = { version = "0.3", features = [ "WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage", "IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "Headers", "ReadableStream", "ReadableStreamDefaultReader", - "BeforeUnloadEvent", "Event", "EventTarget", "KeyboardEvent", "Response", "MediaQueryList", "Gamepad", "Performance", + "BeforeUnloadEvent", "Event", "EventTarget", "KeyboardEvent", "Response", "FormData", "RequestInit", "MediaQueryList", "Gamepad", "Performance", ] } diff --git a/apps/solidcraft-web/src/easyprint.rs b/apps/solidcraft-web/src/easyprint.rs new file mode 100644 index 000000000..4b53c306f --- /dev/null +++ b/apps/solidcraft-web/src/easyprint.rs @@ -0,0 +1,40 @@ +//! Open with EasyPrint in the browser: upload the model to Printables' import endpoint with +//! `fetch` (it allows any origin) and answer with the address to open. + +use std::sync::mpsc::Sender; + +use js_sys::{Array, Uint8Array}; +use solidcraft_engine::easyprint::{IMPORT_URL, parse_import_response}; +use wasm_bindgen::JsCast as _; +use wasm_bindgen_futures::{JsFuture, spawn_local}; + +use crate::files::err; + +/// Start the upload; the answer arrives on `done`. +pub fn upload(name: &str, bytes: Vec, done: Sender>) { + let name = name.to_string(); + spawn_local(async move { + let _ = done.send(post(&name, &bytes).await); + }); +} + +async fn post(name: &str, bytes: &[u8]) -> Result { + let window = web_sys::window().ok_or("no window")?; + let parts = Array::new(); + parts.push(&Uint8Array::from(bytes)); + let blob = web_sys::Blob::new_with_u8_array_sequence(&parts).map_err(err)?; + let form = web_sys::FormData::new().map_err(err)?; + form.append_with_blob_and_filename("file", &blob, name).map_err(err)?; + form.append_with_str("file_name", name).map_err(err)?; + let headers = web_sys::Headers::new().map_err(err)?; + headers.set("Accept", "application/json").map_err(err)?; + let init = web_sys::RequestInit::new(); + init.set_method("POST"); + init.set_body(&form); + init.set_headers(&headers); + let response = JsFuture::from(window.fetch_with_str_and_init(IMPORT_URL, &init)).await.map_err(err)?; + let response: web_sys::Response = response.dyn_into().map_err(|_| "response cast failed".to_string())?; + let status = response.status(); + let text = JsFuture::from(response.text().map_err(err)?).await.map_err(err)?; + parse_import_response(status, text.as_string().unwrap_or_default().as_bytes()) +} diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index b7c76e1bc..113a0ffc5 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -11,6 +11,8 @@ mod api; #[cfg(any(target_arch = "wasm32", test))] mod disk; #[cfg(target_arch = "wasm32")] +mod easyprint; +#[cfg(target_arch = "wasm32")] mod files; #[cfg(target_arch = "wasm32")] mod install; @@ -777,6 +779,7 @@ mod web { })), restore_file: Some(Box::new(move |path: &str| disk::restore(&restorer, path))), download_design: Some(Box::new(files::download)), + easyprint_upload: Some(std::sync::Arc::new(crate::easyprint::upload)), browser_files: Some(Box::new(move || shown.panel.set(true))), install_app: Some(crate::install::service(&cc.egui_ctx)), ..Default::default() diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index f97ff0994..7e64e362e 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -356,6 +356,7 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services { can_restore: None, restore_file: None, download_design: None, + easyprint_upload: Some(std::sync::Arc::new(easyprint_upload)), browser_files: None, agent_http: Some(std::sync::Arc::new(agent_http)), secrets: Some(std::sync::Arc::new(Keychain)), @@ -452,6 +453,24 @@ fn agent_http(r: &solidcraft_ui_egui::agent_chat::backend::HttpRequest) -> Resul Ok((status, body)) } +/// Open with EasyPrint: upload the model to Printables' import endpoint on a worker and answer on +/// `done` with the address to open. Through [`agent_http`]: no redirects, a timeout, no cookies. +fn easyprint_upload(name: &str, bytes: Vec, done: std::sync::mpsc::Sender>) { + use solidcraft_engine::easyprint; + let name = name.to_string(); + std::thread::spawn(move || { + let (content_type, body) = easyprint::multipart(&name, &bytes); + let request = solidcraft_ui_egui::agent_chat::backend::HttpRequest { + method: "POST", + url: easyprint::IMPORT_URL.into(), + headers: vec![("Content-Type".into(), content_type), ("Accept".into(), "application/json".into())], + body: Some(body), + timeout_s: 180, + }; + let _ = done.send(agent_http(&request).and_then(|(status, body)| easyprint::parse_import_response(status, &body))); + }); +} + /// API keys in the system keychain (service "SolidCraft agent chat", one entry per agent). struct Keychain; diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 297d55ef7..c8a510f82 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -534,6 +534,7 @@ "cmd.file_export": "Exportovat", "cmd.file_insert_mesh": "Vložit síť", "cmd.file_insert_step": "Vložit STEP", + "cmd.file_open_in_easyprint": "Otevřít v EasyPrint", "cmd.file_save_mesh": "Uložit jako síť", "cmd.file_slicers": "Nainstalované slicery", "cmd.frame_member": "Prvek rámu", @@ -1493,7 +1494,7 @@ "ui.agent_chat_pop_out": "Otevřít ve vlastním okně, které lze přesunout na jinou obrazovku", "ui.agent_chat_previous_picture": "Předchozí obrázek", "ui.agent_chat_privacy": "Nic se nikam neodesílá, jen agentovi, kterého spouštíte pod vlastním účtem.", - "ui.agent_chat_privacy_note": "SolidCraft nic nikam neodesílá: agent, kterého spouštíte, komunikuje se svou službou pod vaším účtem. SolidCraft nikdy nevidí ani neukládá klíč či heslo.", + "ui.agent_chat_privacy_note": "Chat sám nic nikam neodesílá: agent, kterého spouštíte, komunikuje se svou službou pod vaším účtem. SolidCraft nikdy nevidí ani neukládá klíč či heslo.", "ui.agent_chat_queue": "Zařadit", "ui.agent_chat_queue_full": "Čeká příliš mnoho zpráv: některou odeberte nebo počkejte na agenta.", "ui.agent_chat_queued": "Ve frontě", @@ -1736,6 +1737,11 @@ "ui.draft": "Úkos", "ui.drawing": "Výkres", "ui.drill_point": "Špička vrtáku", + "ui.easyprint_consent": "EasyPrint je slicer od Printables v prohlížeči. Aby se v něm model otevřel, SolidCraft jej nahraje na servery Printables. Odkaz vyprší po 30 minutách a musíte být přihlášeni k Printables. Pokračovat?", + "ui.easyprint_failed": "Nahrání do EasyPrint se nezdařilo: {error}", + "ui.easyprint_opened": "Otevřeno v EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, v prohlížeči)", + "ui.easyprint_uploading": "Nahrávám na Printables…", "ui.edit": "Upravit", "ui.editJointLimits": "Upravit limity kloubu", "ui.edit_section_analysis": "Upravit analýzu řezu", @@ -2030,9 +2036,7 @@ "ui.right": "Zprava", "ui.save": "Uložit", "ui.save_as": "Uložit jako", - "ui.save_mesh_no_slicer": "Nebyl nalezen žádný slicer: zvolte Vlastní… a vyberte svůj slicer, nebo vypněte Odeslat do sliceru", "ui.save_mesh_pick_bodies": "Vyberte tělesa k uložení", - "ui.save_mesh_temp_failed": "Nelze vytvořit {folder}: {error}", "ui.saved_to": "Uloženo {path}", "ui.sbox_pin": "Připnout nahoru ve vyhledávání S", "ui.sbox_unpin": "Odepnout", @@ -2047,7 +2051,6 @@ "ui.selection_shift_add_only": "Shift+klik pouze přidává", "ui.selection_shift_add_only_tip": "Zapnuto: Shift přidává položky, Ctrl/Cmd přepíná. Vypnuto (výchozí): Shift i Ctrl/Cmd přepínají.", "ui.send": "Odeslat", - "ui.send_to_slicer": "Odeslat do sliceru", "ui.sent_to_slicer": "Odesláno do {slicer}", "ui.sheet_gap": "Mezera", "ui.shell": "Skořepina", @@ -2139,6 +2142,7 @@ "ui.untitled": "Bez názvu", "ui.up_axis_note": "Která osa v pohledech míří nahoru (pohled podél osy, výchozí pohled, pohled kolmo). Návrhy se nemění.", "ui.updateToCurrentView": "Aktualizovat na aktuální pohled", + "ui.upload": "Nahrát", "ui.view_centre": "Střed pohledu", "ui.visual_shaded_hidden_edges": "Stínovaný se skrytými hranami", "ui.visual_shaded_with_edges": "Stínovaný s hranami", diff --git a/assets/locales/da.json b/assets/locales/da.json index b223792da..f9693212f 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -729,6 +729,7 @@ "cmd.file_export": "Eksportér", "cmd.file_insert_mesh": "Indsæt mesh", "cmd.file_insert_step": "Indsæt STEP", + "cmd.file_open_in_easyprint": "Åbn med EasyPrint", "cmd.file_save_mesh": "Gem som mesh", "cmd.file_slicers": "Installerede slicere", "cmd.frame_member": "Rammeelement", @@ -1670,7 +1671,7 @@ "ui.agent_chat_pop_out": "Åbn i eget vindue, som du kan flytte til en anden skærm", "ui.agent_chat_previous_picture": "Forrige billede", "ui.agent_chat_privacy": "Intet sendes andre steder end til den agent, du kører, under din egen konto.", - "ui.agent_chat_privacy_note": "SolidCraft sender intet nogen steder: Agenten, du kører, kommunikerer med sin egen tjeneste under din egen konto. SolidCraft ser eller gemmer aldrig en nøgle eller adgangskode.", + "ui.agent_chat_privacy_note": "Chatten sender selv intet nogen steder: Agenten, du kører, kommunikerer med sin egen tjeneste under din egen konto. SolidCraft ser eller gemmer aldrig en nøgle eller adgangskode.", "ui.agent_chat_queue": "Sæt i kø", "ui.agent_chat_queue_full": "For mange beskeder venter: Fjern en, eller vent på agenten.", "ui.agent_chat_queued": "I kø", @@ -1921,6 +1922,11 @@ "ui.draft": "Slipvinkel", "ui.drawing": "Tegning", "ui.drill_point": "Borspids", + "ui.easyprint_consent": "EasyPrint er Printables' slicer i browseren. For at åbne modellen der uploader SolidCraft den til Printables' servere. Linket udløber efter 30 minutter, og du skal være logget ind på Printables. Fortsæt?", + "ui.easyprint_failed": "Upload til EasyPrint mislykkedes: {error}", + "ui.easyprint_opened": "Åbnet i EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, i browseren)", + "ui.easyprint_uploading": "Uploader til Printables…", "ui.edit": "Redigér", "ui.editJointLimits": "Redigér ledgrænser", "ui.edit_section_analysis": "Redigér snitanalyse", @@ -2232,9 +2238,7 @@ "ui.right": "Fra højre", "ui.save": "Gem", "ui.save_as": "Gem som", - "ui.save_mesh_no_slicer": "Ingen slicer fundet: Vælg Brugerdefineret…, og vælg dit slicerprogram, eller slå Send til slicer fra", "ui.save_mesh_pick_bodies": "Vælg de emner, der skal gemmes", - "ui.save_mesh_temp_failed": "Kunne ikke oprette {folder}: {error}", "ui.saved_to": "Gemt: {path}", "ui.sbox_pin": "Fastgør øverst i S-menuen", "ui.sbox_unpin": "Fjern fastgørelse", @@ -2249,7 +2253,6 @@ "ui.selection_shift_add_only": "Shift+klik tilføjer uden at fjerne", "ui.selection_shift_add_only_tip": "Slået til: Shift tilføjer til markeringen. Ctrl/Cmd tilføjer eller fjerner. Slået fra (standard): Både Shift og Ctrl/Cmd tilføjer eller fjerner.", "ui.send": "Send", - "ui.send_to_slicer": "Send til slicer", "ui.sent_to_slicer": "Sendt til {slicer}", "ui.sheet_gap": "Mellemrum", "ui.shell": "Udhulning", @@ -2347,6 +2350,7 @@ "ui.untitled": "Uden titel", "ui.up_axis_note": "Hvilken akse der peger opad i visningerne (aksevisning, Hjem, Se på). Designs ændres ikke.", "ui.updateToCurrentView": "Opdatér til aktuel visning", + "ui.upload": "Upload", "ui.view_centre": "Visningens centrum", "ui.visual_shaded_hidden_edges": "Skyggelagt med skjulte kanter", "ui.visual_shaded_with_edges": "Skyggelagt med kanter", diff --git a/assets/locales/de.json b/assets/locales/de.json index b377fe297..64511ed50 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -646,6 +646,7 @@ "cmd.file_export": "Exportieren", "cmd.file_insert_mesh": "Netz einfügen", "cmd.file_insert_step": "STEP einfügen", + "cmd.file_open_in_easyprint": "Mit EasyPrint öffnen", "cmd.file_save_mesh": "Als Netz speichern", "cmd.file_slicers": "Installierte Slicer", "cmd.frame_member": "Rahmenelement", @@ -1580,7 +1581,7 @@ "ui.agent_chat_pop_out": "In eigenem Fenster öffnen, das Sie auf einen anderen Bildschirm verschieben können", "ui.agent_chat_previous_picture": "Vorheriges Bild", "ui.agent_chat_privacy": "Nichts geht irgendwohin außer an den Agenten, den Sie unter Ihrem eigenen Konto ausführen.", - "ui.agent_chat_privacy_note": "SolidCraft sendet nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.", + "ui.agent_chat_privacy_note": "Der Chat sendet von sich aus nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.", "ui.agent_chat_queue": "Einreihen", "ui.agent_chat_queue_full": "Zu viele Nachrichten warten: Entfernen Sie eine oder warten Sie auf den Agenten.", "ui.agent_chat_queued": "Eingereiht", @@ -1823,6 +1824,11 @@ "ui.draft": "Abziehen", "ui.drawing": "Zeichnung", "ui.drill_point": "Bohrpunkt", + "ui.easyprint_consent": "EasyPrint ist der Slicer von Printables im Browser. Um das Modell dort zu öffnen, lädt SolidCraft es auf die Server von Printables hoch. Der Link läuft nach 30 Minuten ab, und Sie müssen bei Printables angemeldet sein. Fortfahren?", + "ui.easyprint_failed": "Upload zu EasyPrint fehlgeschlagen: {error}", + "ui.easyprint_opened": "In EasyPrint geöffnet", + "ui.easyprint_row": "EasyPrint (Printables, im Browser)", + "ui.easyprint_uploading": "Wird zu Printables hochgeladen …", "ui.edit": "Bearbeiten", "ui.editJointLimits": "Gelenkgrenzen bearbeiten", "ui.edit_section_analysis": "Querschnittsanalyse bearbeiten", @@ -2123,9 +2129,7 @@ "ui.right": "Rechts", "ui.save": "Speichern", "ui.save_as": "Speichern unter", - "ui.save_mesh_no_slicer": "Kein Slicer gefunden: „Benutzerdefiniert…“ wählen und das Slicer-Programm angeben, oder „An Slicer senden“ ausschalten", "ui.save_mesh_pick_bodies": "Wähle die Körper zum Speichern aus", - "ui.save_mesh_temp_failed": "{folder} konnte nicht angelegt werden: {error}", "ui.saved_to": "Gespeichert: {path}", "ui.sbox_pin": "Oben im S-Feld anheften", "ui.sbox_unpin": "Lösen", @@ -2140,7 +2144,6 @@ "ui.selection_shift_add_only": "Umschalt+Klick fügt hinzu, ohne zu entfernen", "ui.selection_shift_add_only_tip": "An: Umschalt fügt Elemente hinzu, Strg/Cmd schaltet um. Aus (Standard): Umschalt und Strg/Cmd schalten beide um.", "ui.send": "Senden", - "ui.send_to_slicer": "An Slicer senden", "ui.sent_to_slicer": "An {slicer} gesendet", "ui.sheet_gap": "Spalt", "ui.shell": "Hülle", @@ -2238,6 +2241,7 @@ "ui.untitled": "Ohne Titel", "ui.up_axis_note": "Welche Achse in den Ansichten nach oben zeigt (Achsenansicht, Home, Ansehen). Designs bleiben unverändert.", "ui.updateToCurrentView": "Auf aktuelle Ansicht aktualisieren", + "ui.upload": "Hochladen", "ui.view_centre": "Ansichtszentrum", "ui.viewport_theme_follow": "Dem Design folgen", "ui.visual_shaded_hidden_edges": "Schattiert mit verdeckten Kanten", diff --git a/assets/locales/en.json b/assets/locales/en.json index 7e9605a04..f7b208b26 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -774,7 +774,9 @@ "cmd.file_export": "Export", "cmd.file_insert_mesh": "Insert Mesh", "cmd.file_insert_step": "Insert STEP", + "cmd.file_open_in_easyprint": "Open with EasyPrint", "cmd.file_save_mesh": "Save As Mesh", + "cmd.file_send_to_slicer": "Send to Slicer", "cmd.file_slicers": "Installed Slicers", "cmd.frame_member": "Frame Member", "cmd.frame_profile_insert": "Insert Profile", @@ -2477,7 +2479,7 @@ "ui.agent_chat_pop_out": "Open in its own window, which you can move to another screen", "ui.agent_chat_previous_picture": "Previous picture", "ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.", - "ui.agent_chat_privacy_note": "SolidCraft sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", + "ui.agent_chat_privacy_note": "The chat itself sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", "ui.agent_chat_provider_models": "{count} models", "ui.agent_chat_provider_other": "Other", "ui.agent_chat_provider_tip": "The provider whose models the next list shows.", @@ -2755,6 +2757,11 @@ "ui.draft": "Draft", "ui.drawing": "Drawing", "ui.drill_point": "Drill Point", + "ui.easyprint_consent": "EasyPrint is Printables' slicer in the browser. To open the model there, SolidCraft uploads it to Printables' servers. The link expires after 30 minutes, and you'll need to be signed in to Printables. Continue?", + "ui.easyprint_failed": "EasyPrint upload failed: {error}", + "ui.easyprint_opened": "Opened in EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, in the browser)", + "ui.easyprint_uploading": "Uploading to Printables…", "ui.edit": "Edit", "ui.editJointLimits": "Edit Joint Limits", "ui.edit_section_analysis": "Edit Section Analysis", @@ -3085,9 +3092,8 @@ "ui.right": "Right", "ui.save": "Save", "ui.save_as": "Save As", - "ui.save_mesh_no_slicer": "No slicer found: choose Custom… and pick your slicer program, or turn off Send to slicer", + "ui.save_mesh_no_slicer_open": "No slicer found: choose Custom… and pick your slicer program", "ui.save_mesh_pick_bodies": "Select the bodies to save", - "ui.save_mesh_temp_failed": "Couldn't make {folder}: {error}", "ui.saved_to": "Saved {path}", "ui.sbox_pin": "Pin to the top of the S box", "ui.sbox_unpin": "Unpin", @@ -3102,8 +3108,9 @@ "ui.selection_shift_add_only": "Shift+click adds without removing", "ui.selection_shift_add_only_tip": "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", "ui.send": "Send", - "ui.send_to_slicer": "Send to slicer", + "ui.send_to_slicer_unavailable": "Send to Slicer needs the desktop app: a browser can't start a program", "ui.sent_to_slicer": "Sent to {slicer}", + "ui.sent_to_slicer_copy": "Sent to {slicer} as {file}, because the first file is still open there", "ui.sheet_gap": "Gap", "ui.shell": "Shell", "ui.shortcut_capture_add_key": "Add one ordinary key. Escape cancels.", @@ -3138,6 +3145,15 @@ "ui.slice": "Slice", "ui.slicer": "Slicer", "ui.slicer_delete_tip": "{program}\nPress Delete to remove it from the list", + "ui.slicer_lost": "{slicer} was started but can't be found again to send it the file. The file is saved at {path}: open it from there.", + "ui.slicer_no_file": "{slicer} is ready, but there is no file to send to it.", + "ui.slicer_no_response": "{slicer} didn't respond in time. The file is already saved at {path}: send it again once the slicer has started.", + "ui.slicer_resend_hint": "Sending again replaces the file the slicer has open.", + "ui.slicer_single_instance": "Open files in a slicer that is already running", + "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer and Cura load the file in the window that is open instead of starting another. Other slicers are started as they are. PrusaSlicer 3.0 always does this: its launcher can't take a file any other way.", + "ui.slicer_starting": "Starting {slicer}…", + "ui.slicer_still_starting": "Still waiting for {slicer} to start. Nothing else was sent.", + "ui.slicer_stl_fallback": "The 3MF could not be written, so this is an STL.", "ui.slot": "Slot", "ui.smooth": "Smooth", "ui.smooth_wheel_zoom": "Smooth wheel zoom", @@ -3205,6 +3221,7 @@ "ui.untitled": "Untitled", "ui.up_axis_note": "Which axis points up in the views (axis view, Home, Look At). Designs are unchanged.", "ui.updateToCurrentView": "Update to Current View", + "ui.upload": "Upload", "ui.vertical_constraint": "Vertical Constraint", "ui.view_centre": "View centre", "ui.viewport_theme_follow": "Follow theme", diff --git a/assets/locales/es.json b/assets/locales/es.json index 0422ee653..c767ee380 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -540,6 +540,7 @@ "cmd.file_export": "Exportar", "cmd.file_insert_mesh": "Insertar malla", "cmd.file_insert_step": "Insertar STEP", + "cmd.file_open_in_easyprint": "Abrir con EasyPrint", "cmd.file_save_mesh": "Guardar como malla", "cmd.file_slicers": "Laminadores instalados", "cmd.frame_member": "Miembro estructural", @@ -1975,7 +1976,7 @@ "ui.agent_chat_pop_out": "Abrir en su propia ventana, que puedes mover a otra pantalla", "ui.agent_chat_previous_picture": "Imagen anterior", "ui.agent_chat_privacy": "Solo se envían datos al agente que ejecutes, con tu propia cuenta.", - "ui.agent_chat_privacy_note": "SolidCraft no envía nada a otros destinos: el agente que ejecutas se comunica con su propio servicio utilizando tu cuenta. SolidCraft nunca ve ni almacena claves o contraseñas.", + "ui.agent_chat_privacy_note": "El chat no envía nada por sí mismo a otros destinos: el agente que ejecutas se comunica con su propio servicio utilizando tu cuenta. SolidCraft nunca ve ni almacena claves o contraseñas.", "ui.agent_chat_queue": "Poner en cola", "ui.agent_chat_queue_full": "Hay demasiados mensajes en espera: elimina uno o espera a que termine el agente.", "ui.agent_chat_queued": "En cola", @@ -2220,6 +2221,11 @@ "ui.draft": "Ángulo de salida", "ui.drawing": "Dibujo", "ui.drill_point": "Punta de broca", + "ui.easyprint_consent": "EasyPrint es el slicer de Printables en el navegador. Para abrir el modelo allí, SolidCraft lo sube a los servidores de Printables. El enlace caduca a los 30 minutos y tendrás que haber iniciado sesión en Printables. ¿Continuar?", + "ui.easyprint_failed": "No se pudo subir a EasyPrint: {error}", + "ui.easyprint_opened": "Abierto en EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, en el navegador)", + "ui.easyprint_uploading": "Subiendo a Printables…", "ui.edit": "Editar", "ui.editJointLimits": "Editar límites de unión", "ui.edit_section_analysis": "Editar análisis de sección", @@ -2512,9 +2518,7 @@ "ui.right": "Derecha", "ui.save": "Guardar", "ui.save_as": "Guardar como", - "ui.save_mesh_no_slicer": "No se ha encontrado ningún laminador: elige Personalizado… y selecciona tu laminador, o desactiva Enviar al laminador", "ui.save_mesh_pick_bodies": "Selecciona los cuerpos que se van a guardar", - "ui.save_mesh_temp_failed": "No se ha podido crear {folder}: {error}", "ui.saved_to": "Guardado en {path}", "ui.sbox_pin": "Fijar arriba en la búsqueda S", "ui.sbox_unpin": "Desfijar", @@ -2529,7 +2533,6 @@ "ui.selection_shift_add_only": "Mayús+clic añade sin quitar", "ui.selection_shift_add_only_tip": "Activado: Mayús añade elementos, Ctrl/Cmd alterna. Desactivado (predeterminado): Mayús y Ctrl/Cmd alternan.", "ui.send": "Enviar", - "ui.send_to_slicer": "Enviar al laminador", "ui.sent_to_slicer": "Enviado a {slicer}", "ui.sheet_gap": "Separación", "ui.shell": "Vaciado", @@ -2621,6 +2624,7 @@ "ui.untitled": "Sin título", "ui.up_axis_note": "Eje que apunta hacia arriba en las vistas (vista de eje, Inicio, Mirar hacia). Los diseños no cambian.", "ui.updateToCurrentView": "Actualizar a vista actual", + "ui.upload": "Subir", "ui.view_centre": "Centro de la vista", "ui.visual_shaded_hidden_edges": "Sombreado con aristas ocultas", "ui.visual_shaded_with_edges": "Sombreado con aristas", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index c8950986b..8e88cb927 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -534,6 +534,7 @@ "cmd.file_export": "Exporter", "cmd.file_insert_mesh": "Insérer un maillage", "cmd.file_insert_step": "Insérer un STEP", + "cmd.file_open_in_easyprint": "Ouvrir avec EasyPrint", "cmd.file_save_mesh": "Enregistrer comme maillage", "cmd.file_slicers": "Slicers installés", "cmd.frame_member": "Élément de structure", @@ -949,7 +950,7 @@ "issue.note_opened_copied": "Rapport copié. Collez-le dans le brouillon GitHub, joignez la capture d’écran, puis cliquez sur Submit new issue sur GitHub.", "issue.note_removed": "Capture d’écran retirée de ce brouillon.", "issue.note_report_copied": "Rapport copié. Collez-le dans le brouillon GitHub si nécessaire.", - "issue.note_save_failed": "Impossible d’enregistrer la capture d’écran : {error}", + "issue.note_save_failed": "Impossible d’enregistrer la capture d’écran : {error}", "issue.note_saved": "Capture d’écran enregistrée. Joignez le PNG dans le brouillon GitHub.", "issue.save_screenshot": "Enregistrer la capture d’écran…", "joint.from_bodies_hint": "Chaque corps sélectionné passe dans un nouveau composant à lui et reste où il est.", @@ -1080,7 +1081,7 @@ "search.parameter": "Paramètre", "search.recent": "Récents", "search.run": "Exécuter la commande", - "search.suggest": "Vouliez-vous dire {label} ?", + "search.suggest": "Vouliez-vous dire {label} ?", "search.try": "Saisissez un nom de commande, une entité de cette conception ou un paramètre. Pour exécuter une commande avec des valeurs, saisissez son id et un objet JSON : {example}", "search.valid": "Valide", "settings.display_quality_note": "Les niveaux plus fins affichent plus lisses les faces et arêtes courbes, mais leur maillage prend plus de temps. Seule la vue change, jamais la conception ni les exports.", @@ -1095,7 +1096,7 @@ "settings.reset_intro": "Ces réglages ne fonctionnent pas sur cet ordinateur et empêcheraient SolidCraft de démarrer ; ils ont donc été modifiés :", "settings.reset_title": "Des réglages ont été modifiés", "settings.supersampling_note": "Dessine la vue à une résolution plus élevée puis la réduit : arêtes, lignes et grille plus lisses sur les écrans de définition inférieure à la 4K. Cela coûte du temps GPU : environ 2,25× plus de pixels à 1,5× et 4× plus à 2×.", - "shortcut.json_error": "les paramètres doivent être au format JSON : {error}", + "shortcut.json_error": "les paramètres doivent être au format JSON : {error}", "shortcut.no_command": "la commande `{id}` n’existe pas ; le texte avant le JSON doit être un ID de commande", "shortcut.pin": "Épingler en haut de la boîte S", "shortcut.unpin": "Désépingler", @@ -1340,7 +1341,7 @@ "ui.agent_chat_pop_out": "Ouvrir dans une fenêtre séparée, déplaçable vers un autre écran", "ui.agent_chat_previous_picture": "Image précédente", "ui.agent_chat_privacy": "Rien n'est envoyé ailleurs qu'à l'agent que vous lancez, sous votre propre compte.", - "ui.agent_chat_privacy_note": "SolidCraft n'envoie rien nulle part : l'agent que vous lancez dialogue avec son propre service, sous votre propre compte. SolidCraft ne voit ni ne stocke jamais de clé ni de mot de passe.", + "ui.agent_chat_privacy_note": "Le chat n'envoie rien nulle part de lui-même : l'agent que vous lancez dialogue avec son propre service, sous votre propre compte. SolidCraft ne voit ni ne stocke jamais de clé ni de mot de passe.", "ui.agent_chat_queue": "Mettre en file", "ui.agent_chat_queue_full": "Trop de messages sont en attente : retirez-en un ou attendez l'agent.", "ui.agent_chat_queued": "En file d'attente", @@ -1583,6 +1584,11 @@ "ui.draft": "Dépouille", "ui.drawing": "Mise en plan", "ui.drill_point": "Pointe de foret", + "ui.easyprint_consent": "EasyPrint est le slicer de Printables dans le navigateur. Pour y ouvrir le modèle, SolidCraft l'envoie sur les serveurs de Printables. Le lien expire au bout de 30 minutes et vous devrez être connecté à Printables. Continuer ?", + "ui.easyprint_failed": "Échec de l'envoi vers EasyPrint : {error}", + "ui.easyprint_opened": "Ouvert dans EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, dans le navigateur)", + "ui.easyprint_uploading": "Envoi vers Printables…", "ui.edit": "Modifier", "ui.editJointLimits": "Modifier les limites de liaison", "ui.edit_section_analysis": "Modifier l'analyse de coupe", @@ -1874,9 +1880,7 @@ "ui.right": "Droite", "ui.save": "Enregistrer", "ui.save_as": "Enregistrer sous", - "ui.save_mesh_no_slicer": "Aucun slicer trouvé : choisissez Personnalisé… et sélectionnez votre slicer, ou désactivez Envoyer au slicer", "ui.save_mesh_pick_bodies": "Sélectionner les corps à enregistrer", - "ui.save_mesh_temp_failed": "Impossible de créer {folder} : {error}", "ui.saved_to": "Enregistré : {path}", "ui.sbox_pin": "Épingler en haut de la boîte S", "ui.sbox_unpin": "Désépingler", @@ -1891,7 +1895,6 @@ "ui.selection_shift_add_only": "Maj+clic ajoute sans retirer", "ui.selection_shift_add_only_tip": "Activé : Maj ajoute des éléments, Ctrl/Cmd bascule. Désactivé (par défaut) : Maj et Ctrl/Cmd basculent tous deux.", "ui.send": "Envoyer", - "ui.send_to_slicer": "Envoyer au slicer", "ui.sent_to_slicer": "Envoyé à {slicer}", "ui.sheet_gap": "Jeu", "ui.shell": "Coque", @@ -1983,6 +1986,7 @@ "ui.untitled": "Sans titre", "ui.up_axis_note": "Axe orienté vers le haut dans les vues (vue d'axe, Accueil, Vue normale). Les conceptions ne sont pas modifiées.", "ui.updateToCurrentView": "Mettre à jour avec la vue actuelle", + "ui.upload": "Envoyer", "ui.view_centre": "Centre de la vue", "ui.visual_shaded_hidden_edges": "Ombré avec arêtes cachées", "ui.visual_shaded_with_edges": "Ombré avec arêtes", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index 6ed41e7af..193f356d3 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -534,6 +534,7 @@ "cmd.file_export": "Exportar", "cmd.file_insert_mesh": "Inserir malla", "cmd.file_insert_step": "Inserir STEP", + "cmd.file_open_in_easyprint": "Abrir con EasyPrint", "cmd.file_save_mesh": "Gardar como malla", "cmd.file_slicers": "Laminadores instalados", "cmd.frame_member": "Membro estrutural", @@ -1326,7 +1327,7 @@ "ui.agent_chat_pop_out": "Abrir nunha xanela propia, que podes mover a outra pantalla", "ui.agent_chat_previous_picture": "Imaxe anterior", "ui.agent_chat_privacy": "Nada vai a ningún sitio agás ao axente que executas, coa túa propia conta.", - "ui.agent_chat_privacy_note": "SolidCraft non envía nada a ningún sitio: o axente que executas fala co seu propio servizo coa túa propia conta. SolidCraft nunca ve nin garda ningunha clave nin contrasinal.", + "ui.agent_chat_privacy_note": "O chat non envía nada por si mesmo a ningún sitio: o axente que executas fala co seu propio servizo coa túa propia conta. SolidCraft nunca ve nin garda ningunha clave nin contrasinal.", "ui.agent_chat_queue": "Pór na cola", "ui.agent_chat_queue_full": "Hai demasiadas mensaxes agardando: quita unha ou agarda polo axente.", "ui.agent_chat_queued": "Na cola", @@ -1569,6 +1570,11 @@ "ui.draft": "Ángulo de desmoldaxe", "ui.drawing": "Debuxo", "ui.drill_point": "Punta de broca", + "ui.easyprint_consent": "EasyPrint é o slicer de Printables no navegador. Para abrir o modelo alí, SolidCraft cárgao nos servidores de Printables. A ligazón caduca aos 30 minutos e terás que ter a sesión iniciada en Printables. Continuar?", + "ui.easyprint_failed": "Non se puido cargar a EasyPrint: {error}", + "ui.easyprint_opened": "Aberto en EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, no navegador)", + "ui.easyprint_uploading": "Cargando a Printables…", "ui.edit": "Editar", "ui.editJointLimits": "Editar os límites da unión", "ui.edit_section_analysis": "Editar a análise de sección", @@ -1860,9 +1866,7 @@ "ui.right": "Dereita", "ui.save": "Gardar", "ui.save_as": "Gardar como", - "ui.save_mesh_no_slicer": "Non se atopou ningún laminador: escolle Personalizado… e selecciona o teu programa laminador, ou desactiva Enviar ao laminador", "ui.save_mesh_pick_bodies": "Selecciona os corpos que queres gardar", - "ui.save_mesh_temp_failed": "Non se puido crear {folder}: {error}", "ui.saved_to": "Gardado {path}", "ui.sbox_pin": "Fixar arriba na caixa S", "ui.sbox_unpin": "Desfixar", @@ -1877,7 +1881,6 @@ "ui.selection_shift_add_only": "Maiús+clic engade sen quitar", "ui.selection_shift_add_only_tip": "Activado: Maiús engade elementos, Ctrl/Cmd alterna. Desactivado (predeterminado): Maiús e Ctrl/Cmd alternan ambos.", "ui.send": "Enviar", - "ui.send_to_slicer": "Enviar ao laminador", "ui.sent_to_slicer": "Enviado a {slicer}", "ui.sheet_gap": "Separación", "ui.shell": "Baleirado", @@ -1969,6 +1972,7 @@ "ui.untitled": "Sen título", "ui.up_axis_note": "Que eixe apunta cara arriba nas vistas (vista de eixe, Inicio, Mirar cara a). Os deseños non cambian.", "ui.updateToCurrentView": "Actualizar á vista actual", + "ui.upload": "Cargar", "ui.view_centre": "Centro da vista", "ui.visual_shaded_hidden_edges": "Sombreado con arestas ocultas", "ui.visual_shaded_with_edges": "Sombreado con arestas", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index 185c7764b..b738dab01 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -533,6 +533,7 @@ "cmd.file_export": "Exportálás", "cmd.file_insert_mesh": "Háló beszúrása", "cmd.file_insert_step": "STEP beszúrása", + "cmd.file_open_in_easyprint": "Megnyitás EasyPrinttel", "cmd.file_save_mesh": "Mentés hálóként", "cmd.file_slicers": "Telepített szeletelők", "cmd.frame_member": "Szerkezeti elem", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "Megnyitás saját ablakban, amelyet másik képernyőre mozgathat", "ui.agent_chat_previous_picture": "Előző kép", "ui.agent_chat_privacy": "Semmi sem megy sehová, csak az Ön által futtatott ügynökhöz, az Ön saját fiókja alatt.", - "ui.agent_chat_privacy_note": "A SolidCraft semmit sem küld sehová: az Ön által futtatott ügynök a saját szolgáltatásával kommunikál, az Ön saját fiókja alatt. A SolidCraft soha nem lát és nem tárol kulcsot vagy jelszót.", + "ui.agent_chat_privacy_note": "A csevegés önmagától semmit sem küld sehová: az Ön által futtatott ügynök a saját szolgáltatásával kommunikál, az Ön saját fiókja alatt. A SolidCraft soha nem lát és nem tárol kulcsot vagy jelszót.", "ui.agent_chat_queue": "Sorba", "ui.agent_chat_queue_full": "Túl sok üzenet vár: távolítson el egyet, vagy várja meg az ügynököt.", "ui.agent_chat_queued": "Sorban", @@ -1511,6 +1512,11 @@ "ui.draft": "Dőlés", "ui.drawing": "Rajz", "ui.drill_point": "Fúrócsúcs", + "ui.easyprint_consent": "Az EasyPrint a Printables szeletelője a böngészőben. A modell ott való megnyitásához a SolidCraft feltölti azt a Printables szervereire. A hivatkozás 30 perc után lejár, és be kell jelentkeznie a Printablesbe. Folytatja?", + "ui.easyprint_failed": "Az EasyPrintre feltöltés sikertelen: {error}", + "ui.easyprint_opened": "Megnyitva az EasyPrintben", + "ui.easyprint_row": "EasyPrint (Printables, a böngészőben)", + "ui.easyprint_uploading": "Feltöltés a Printablesbe…", "ui.edit": "Szerkesztés", "ui.editJointLimits": "Csuklókorlátok szerkesztése", "ui.edit_section_analysis": "Metszetelemzés szerkesztése", @@ -1802,9 +1808,7 @@ "ui.right": "Jobb", "ui.save": "Mentés", "ui.save_as": "Mentés másként", - "ui.save_mesh_no_slicer": "Nem található szeletelő: válassza az Egyéni… lehetőséget és jelölje ki a szeletelőprogramot, vagy kapcsolja ki a Küldés szeletelőnek beállítást", "ui.save_mesh_pick_bodies": "Jelölje ki a mentendő testeket", - "ui.save_mesh_temp_failed": "A(z) {folder} nem hozható létre: {error}", "ui.saved_to": "Mentve: {path}", "ui.sbox_pin": "Rögzítés az S doboz tetejére", "ui.sbox_unpin": "Rögzítés feloldása", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+kattintás eltávolítás nélkül hozzáad", "ui.selection_shift_add_only_tip": "Be: a Shift hozzáad, a Ctrl/Cmd vált. Ki (alapért.): a Shift és a Ctrl/Cmd is vált.", "ui.send": "Küldés", - "ui.send_to_slicer": "Küldés szeletelőnek", "ui.sent_to_slicer": "Elküldve ide: {slicer}", "ui.sheet_gap": "Rés", "ui.shell": "Héjazás", @@ -1911,6 +1914,7 @@ "ui.untitled": "Névtelen", "ui.up_axis_note": "Melyik tengely mutat felfelé a nézetekben (tengelynézet, Kezdőlap, Ránézés). A tervek változatlanok.", "ui.updateToCurrentView": "Frissítés az aktuális nézetre", + "ui.upload": "Feltöltés", "ui.view_centre": "Nézet középpontja", "ui.visual_shaded_hidden_edges": "Árnyalt rejtett élekkel", "ui.visual_shaded_with_edges": "Árnyalt élekkel", diff --git a/assets/locales/id.json b/assets/locales/id.json index bdc4af34d..92e7eb3a6 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -533,6 +533,7 @@ "cmd.file_export": "Ekspor", "cmd.file_insert_mesh": "Sisipkan Mesh", "cmd.file_insert_step": "Sisipkan STEP", + "cmd.file_open_in_easyprint": "Buka dengan EasyPrint", "cmd.file_save_mesh": "Simpan Sebagai Mesh", "cmd.file_slicers": "Slicer Terpasang", "cmd.frame_member": "Batang Rangka", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "Buka di jendela sendiri, yang dapat dipindah ke layar lain", "ui.agent_chat_previous_picture": "Gambar sebelumnya", "ui.agent_chat_privacy": "Tidak ada yang dikirim ke mana pun kecuali ke agen yang Anda jalankan, di bawah akun Anda sendiri.", - "ui.agent_chat_privacy_note": "SolidCraft tidak mengirim apa pun ke mana pun: agen yang Anda jalankan berbicara ke layanannya sendiri di bawah akun Anda sendiri. SolidCraft tidak pernah melihat atau menyimpan key atau kata sandi.", + "ui.agent_chat_privacy_note": "Obrolan tidak mengirim apa pun ke mana pun dengan sendirinya: agen yang Anda jalankan berbicara ke layanannya sendiri di bawah akun Anda sendiri. SolidCraft tidak pernah melihat atau menyimpan key atau kata sandi.", "ui.agent_chat_queue": "Antre", "ui.agent_chat_queue_full": "Terlalu banyak pesan menunggu: hapus satu atau tunggu agen.", "ui.agent_chat_queued": "Mengantre", @@ -1511,6 +1512,11 @@ "ui.draft": "Draft", "ui.drawing": "Gambar Kerja", "ui.drill_point": "Ujung Bor", + "ui.easyprint_consent": "EasyPrint adalah slicer Printables di browser. Untuk membuka model di sana, SolidCraft mengunggahnya ke server Printables. Tautan kedaluwarsa setelah 30 menit, dan Anda harus masuk ke Printables. Lanjutkan?", + "ui.easyprint_failed": "Gagal mengunggah ke EasyPrint: {error}", + "ui.easyprint_opened": "Dibuka di EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, di browser)", + "ui.easyprint_uploading": "Mengunggah ke Printables…", "ui.edit": "Edit", "ui.editJointLimits": "Edit Batas Sambungan", "ui.edit_section_analysis": "Edit Analisis Penampang", @@ -1802,9 +1808,7 @@ "ui.right": "Kanan", "ui.save": "Simpan", "ui.save_as": "Simpan Sebagai", - "ui.save_mesh_no_slicer": "Slicer tidak ditemukan: pilih Kustom… dan tunjuk program slicer Anda, atau matikan Kirim ke slicer", "ui.save_mesh_pick_bodies": "Pilih bodi yang akan disimpan", - "ui.save_mesh_temp_failed": "Tidak dapat membuat {folder}: {error}", "ui.saved_to": "Disimpan {path}", "ui.sbox_pin": "Sematkan di atas kotak S", "ui.sbox_unpin": "Lepas sematan", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+klik menambah tanpa menghapus", "ui.selection_shift_add_only_tip": "Aktif: Shift menambah item, Ctrl/Cmd mengalihkan. Mati (default): Shift dan Ctrl/Cmd sama-sama mengalihkan.", "ui.send": "Kirim", - "ui.send_to_slicer": "Kirim ke slicer", "ui.sent_to_slicer": "Dikirim ke {slicer}", "ui.sheet_gap": "Celah", "ui.shell": "Shell", @@ -1911,6 +1914,7 @@ "ui.untitled": "Tanpa judul", "ui.up_axis_note": "Sumbu mana yang mengarah ke atas di tampilan (tampilan sumbu, Home, Look At). Desain tidak berubah.", "ui.updateToCurrentView": "Perbarui ke Tampilan Saat Ini", + "ui.upload": "Unggah", "ui.view_centre": "Pusat tampilan", "ui.visual_shaded_hidden_edges": "Shaded dengan tepi tersembunyi", "ui.visual_shaded_with_edges": "Shaded dengan tepi", diff --git a/assets/locales/it.json b/assets/locales/it.json index 9731fc67c..8cba00839 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -539,6 +539,7 @@ "cmd.file_export": "Esporta", "cmd.file_insert_mesh": "Inserisci mesh", "cmd.file_insert_step": "Inserisci STEP", + "cmd.file_open_in_easyprint": "Apri con EasyPrint", "cmd.file_save_mesh": "Salva come mesh", "cmd.file_slicers": "Slicer installati", "cmd.frame_member": "Membro strutturale", @@ -1365,7 +1366,7 @@ "ui.agent_chat_pop_out": "Apri in una finestra separata, che puoi spostare su un altro schermo", "ui.agent_chat_previous_picture": "Immagine precedente", "ui.agent_chat_privacy": "I dati vengono inviati solo all'agente che esegui, con il tuo account.", - "ui.agent_chat_privacy_note": "SolidCraft non invia dati ad alcun servizio: l'agente che esegui comunica con il proprio servizio usando il tuo account. SolidCraft non vede né memorizza mai chiavi o password.", + "ui.agent_chat_privacy_note": "La chat non invia da sola dati ad alcun servizio: l'agente che esegui comunica con il proprio servizio usando il tuo account. SolidCraft non vede né memorizza mai chiavi o password.", "ui.agent_chat_queue": "Metti in coda", "ui.agent_chat_queue_full": "Troppi messaggi in attesa: rimuovine uno o attendi l'agente.", "ui.agent_chat_queued": "In coda", @@ -1608,6 +1609,11 @@ "ui.draft": "Sformo", "ui.drawing": "Disegno", "ui.drill_point": "Punta del trapano", + "ui.easyprint_consent": "EasyPrint è lo slicer di Printables nel browser. Per aprire lì il modello, SolidCraft lo carica sui server di Printables. Il link scade dopo 30 minuti e dovrai aver effettuato l'accesso a Printables. Continuare?", + "ui.easyprint_failed": "Caricamento su EasyPrint non riuscito: {error}", + "ui.easyprint_opened": "Aperto in EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, nel browser)", + "ui.easyprint_uploading": "Caricamento su Printables…", "ui.edit": "Modifica", "ui.editJointLimits": "Modifica limiti del giunto", "ui.edit_section_analysis": "Modifica analisi in sezione", @@ -1900,9 +1906,7 @@ "ui.right": "Destra", "ui.save": "Salva", "ui.save_as": "Salva con nome", - "ui.save_mesh_no_slicer": "Nessuno slicer trovato: scegli Personalizzato… e seleziona lo slicer, oppure disattiva Invia allo slicer", "ui.save_mesh_pick_bodies": "Seleziona i corpi da salvare", - "ui.save_mesh_temp_failed": "Impossibile creare {folder}: {error}", "ui.saved_to": "Salvato {path}", "ui.sbox_pin": "Fissa in cima al riquadro S", "ui.sbox_unpin": "Sblocca", @@ -1917,7 +1921,6 @@ "ui.selection_shift_add_only": "Maiusc+clic aggiunge senza rimuovere", "ui.selection_shift_add_only_tip": "Attivo: Maiusc aggiunge elementi, Ctrl/Cmd commuta. Disattivo (predefinito): Maiusc e Ctrl/Cmd commutano entrambi.", "ui.send": "Invia", - "ui.send_to_slicer": "Invia allo slicer", "ui.sent_to_slicer": "Inviato a {slicer}", "ui.sheet_gap": "Gioco", "ui.shell": "Svuota", @@ -2009,6 +2012,7 @@ "ui.untitled": "Senza titolo", "ui.up_axis_note": "L'asse verticale nelle viste (viste degli assi, Vista iniziale, Vista normale). I progetti restano invariati.", "ui.updateToCurrentView": "Aggiorna alla vista corrente", + "ui.upload": "Carica", "ui.view_centre": "Centro della vista", "ui.visual_shaded_hidden_edges": "Ombreggiato con spigoli nascosti", "ui.visual_shaded_with_edges": "Ombreggiato con spigoli", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index c3454262f..e2eaf8501 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -774,7 +774,9 @@ "cmd.file_export": "エクスポート", "cmd.file_insert_mesh": "メッシュを挿入", "cmd.file_insert_step": "STEP を挿入", + "cmd.file_open_in_easyprint": "EasyPrint で開く", "cmd.file_save_mesh": "メッシュとして保存", + "cmd.file_send_to_slicer": "スライサーに送る", "cmd.file_slicers": "インストール済みのスライサー", "cmd.frame_member": "フレーム部材", "cmd.frame_profile_insert": "形材を挿入", @@ -2477,7 +2479,7 @@ "ui.agent_chat_pop_out": "独立したウィンドウで開く(別の画面に移動できます)", "ui.agent_chat_previous_picture": "前の画像", "ui.agent_chat_privacy": "あなたのアカウントで実行するエージェント以外には、何も送信されません。", - "ui.agent_chat_privacy_note": "SolidCraft はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。", + "ui.agent_chat_privacy_note": "チャット自体はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。", "ui.agent_chat_provider_models": "{count} 個のモデル", "ui.agent_chat_provider_other": "その他", "ui.agent_chat_provider_tip": "隣の一覧にモデルを表示するプロバイダー。", @@ -2755,6 +2757,11 @@ "ui.draft": "勾配", "ui.drawing": "図面", "ui.drill_point": "ドリル先端", + "ui.easyprint_consent": "EasyPrint は Printables のブラウザ版スライサーです。モデルを EasyPrint で開くため、SolidCraft はモデルを Printables のサーバーにアップロードします。リンクは 30 分で期限切れになり、Printables にサインインしている必要があります。続行しますか?", + "ui.easyprint_failed": "EasyPrint へのアップロードに失敗しました: {error}", + "ui.easyprint_opened": "EasyPrint で開きました", + "ui.easyprint_row": "EasyPrint(Printables、ブラウザ上)", + "ui.easyprint_uploading": "Printables にアップロード中…", "ui.edit": "編集", "ui.editJointLimits": "ジョイント制限を編集", "ui.edit_section_analysis": "断面解析を編集", @@ -3085,9 +3092,8 @@ "ui.right": "右側面", "ui.save": "保存", "ui.save_as": "名前を付けて保存", - "ui.save_mesh_no_slicer": "スライサーが見つかりません。「カスタム…」でスライサーのプログラムを選ぶか、「スライサーに送る」をオフにしてください", + "ui.save_mesh_no_slicer_open": "スライサーが見つかりません。「カスタム…」でスライサーのプログラムを選んでください", "ui.save_mesh_pick_bodies": "保存するボディを選択してください", - "ui.save_mesh_temp_failed": "{folder} を作成できません: {error}", "ui.saved_to": "保存しました: {path}", "ui.sbox_pin": "Sボックスの上部に固定", "ui.sbox_unpin": "固定を解除", @@ -3102,8 +3108,9 @@ "ui.selection_shift_add_only": "Shift+クリックで追加のみ(解除なし)", "ui.selection_shift_add_only_tip": "オン: Shift は追加、Ctrl/Cmd はトグル。オフ(既定): Shift と Ctrl/Cmd の両方がトグル。", "ui.send": "送信", - "ui.send_to_slicer": "スライサーに送る", + "ui.send_to_slicer_unavailable": "「スライサーに送る」にはデスクトップアプリが必要です。ブラウザーではプログラムを起動できません", "ui.sent_to_slicer": "{slicer} に送信しました", + "ui.sent_to_slicer_copy": "{slicer} に {file} として送信しました(元のファイルがまだ開かれているため)", "ui.sheet_gap": "ギャップ", "ui.shell": "シェル", "ui.shortcut_capture_add_key": "通常のキーを1つ追加してください。Escでキャンセルします。", @@ -3138,6 +3145,15 @@ "ui.slice": "スライス", "ui.slicer": "スライサー", "ui.slicer_delete_tip": "{program}\nDelete キーでリストから削除", + "ui.slicer_lost": "{slicer} は起動しましたが、ファイルを送るために再び見つけられませんでした。ファイルは {path} に保存されています。そこから開いてください。", + "ui.slicer_no_file": "{slicer} は準備できましたが、送信するファイルがありません。", + "ui.slicer_no_response": "{slicer} が時間内に応答しませんでした。ファイルは {path} に保存済みです。スライサーが起動したら、もう一度送ってください。", + "ui.slicer_resend_hint": "もう一度送ると、スライサーで開いているファイルが置き換わります。", + "ui.slicer_single_instance": "すでに起動しているスライサーでファイルを開く", + "ui.slicer_single_instance_tip": "PrusaSlicer、SuperSlicer、Cura は、別のウィンドウを起動せず、開いているウィンドウでファイルを読み込みます。ほかのスライサーはそのまま起動します。PrusaSlicer 3.0 は常にこの動作です。ランチャーはほかの方法ではファイルを受け取れません。", + "ui.slicer_starting": "{slicer} を起動しています…", + "ui.slicer_still_starting": "まだ {slicer} の起動を待っています。ほかには何も送信していません。", + "ui.slicer_stl_fallback": "3MF を書き込めなかったため、STL で送信しました。", "ui.slot": "スロット", "ui.smooth": "スムーズ", "ui.smooth_wheel_zoom": "滑らかなホイールズーム", @@ -3205,6 +3221,7 @@ "ui.untitled": "無題", "ui.up_axis_note": "ビュー(軸ビュー、ホーム、正面視)で上向きにする軸を指定します。デザインデータ自体は変更されません。", "ui.updateToCurrentView": "現在のビューに更新", + "ui.upload": "アップロード", "ui.vertical_constraint": "垂直拘束", "ui.view_centre": "ビュー中心", "ui.viewport_theme_follow": "テーマに従う", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index a34009b8a..a84741f26 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -688,6 +688,7 @@ "cmd.file_export": "내보내기", "cmd.file_insert_mesh": "메쉬 삽입", "cmd.file_insert_step": "STEP 삽입", + "cmd.file_open_in_easyprint": "EasyPrint로 열기", "cmd.file_save_mesh": "메쉬로 저장", "cmd.file_slicers": "설치된 슬라이서", "cmd.frame_member": "프레임 부재", @@ -1748,7 +1749,7 @@ "ui.agent_chat_pop_out": "다른 화면으로 옮길 수 있는 별도 창으로 열기", "ui.agent_chat_previous_picture": "이전 이미지", "ui.agent_chat_privacy": "사용자의 계정으로 실행하는 에이전트 외에는 아무 데도 전송되지 않습니다.", - "ui.agent_chat_privacy_note": "SolidCraft는 아무것도 어디로도 보내지 않습니다. 실행한 에이전트가 사용자의 계정으로 자신의 서비스와 통신합니다. SolidCraft는 키나 비밀번호를 보거나 저장하지 않습니다.", + "ui.agent_chat_privacy_note": "채팅 자체는 아무것도 어디로도 보내지 않습니다. 실행한 에이전트가 사용자의 계정으로 자신의 서비스와 통신합니다. SolidCraft는 키나 비밀번호를 보거나 저장하지 않습니다.", "ui.agent_chat_queue": "대기열", "ui.agent_chat_queue_full": "대기 중인 메시지가 너무 많습니다. 하나를 제거하거나 에이전트를 기다리세요.", "ui.agent_chat_queued": "대기 중", @@ -1993,6 +1994,11 @@ "ui.draft": "구배", "ui.drawing": "도면", "ui.drill_point": "드릴 선단", + "ui.easyprint_consent": "EasyPrint는 Printables의 브라우저용 슬라이서입니다. 모델을 그곳에서 열기 위해 SolidCraft가 모델을 Printables 서버에 업로드합니다. 링크는 30분 후 만료되며 Printables에 로그인되어 있어야 합니다. 계속할까요?", + "ui.easyprint_failed": "EasyPrint 업로드 실패: {error}", + "ui.easyprint_opened": "EasyPrint에서 열었습니다", + "ui.easyprint_row": "EasyPrint (Printables, 브라우저)", + "ui.easyprint_uploading": "Printables에 업로드하는 중…", "ui.edit": "편집", "ui.editJointLimits": "조인트 제한 편집", "ui.edit_section_analysis": "단면 분석 편집", @@ -2292,9 +2298,7 @@ "ui.right": "우측면", "ui.save": "저장", "ui.save_as": "다른 이름으로 저장", - "ui.save_mesh_no_slicer": "슬라이서를 찾을 수 없습니다. '사용자 지정…'에서 슬라이서 프로그램을 선택하거나 '슬라이서로 보내기'를 끄세요", "ui.save_mesh_pick_bodies": "저장할 바디를 선택하세요", - "ui.save_mesh_temp_failed": "{folder}을(를) 만들 수 없습니다: {error}", "ui.saved_to": "저장됨: {path}", "ui.sbox_pin": "S 상자 맨 위에 고정", "ui.sbox_unpin": "고정 해제", @@ -2309,7 +2313,6 @@ "ui.selection_shift_add_only": "Shift+클릭은 추가만 함", "ui.selection_shift_add_only_tip": "켬: Shift는 항목을 추가하고 Ctrl/Cmd는 토글합니다. 끔(기본값): Shift와 Ctrl/Cmd 모두 토글합니다.", "ui.send": "보내기", - "ui.send_to_slicer": "슬라이서로 보내기", "ui.sent_to_slicer": "{slicer}(으)로 보냈습니다", "ui.sheet_gap": "틈", "ui.shell": "쉘", @@ -2407,6 +2410,7 @@ "ui.untitled": "제목 없음", "ui.up_axis_note": "뷰(축 뷰, 홈, 보기)에서 위쪽을 가리키는 축입니다. 디자인은 변경되지 않습니다.", "ui.updateToCurrentView": "현재 보기로 업데이트", + "ui.upload": "업로드", "ui.view_centre": "뷰 중심", "ui.viewport_theme_follow": "테마 따르기", "ui.visual_shaded_hidden_edges": "음영 처리 및 숨겨진 모서리", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 2986165d8..f861d8911 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -534,6 +534,7 @@ "cmd.file_export": "Eksport", "cmd.file_insert_mesh": "Sisip Mesh", "cmd.file_insert_step": "Sisip STEP", + "cmd.file_open_in_easyprint": "Buka dengan EasyPrint", "cmd.file_save_mesh": "Simpan sebagai Mesh", "cmd.file_slicers": "Penghiris Terpasang", "cmd.frame_member": "Anggota Rangka", @@ -1326,7 +1327,7 @@ "ui.agent_chat_pop_out": "Buka dalam tetingkap sendiri, yang boleh dialihkan ke skrin lain", "ui.agent_chat_previous_picture": "Gambar sebelumnya", "ui.agent_chat_privacy": "Data hanya dihantar kepada ejen yang anda jalankan, melalui akaun anda sendiri.", - "ui.agent_chat_privacy_note": "SolidCraft tidak menghantar data. Ejen berhubung dengan perkhidmatannya melalui akaun anda. SolidCraft tidak melihat atau menyimpan kunci atau kata laluan.", + "ui.agent_chat_privacy_note": "Sembang tidak menghantar data dengan sendirinya. Ejen berhubung dengan perkhidmatannya melalui akaun anda. SolidCraft tidak melihat atau menyimpan kunci atau kata laluan.", "ui.agent_chat_queue": "Hantar Nanti", "ui.agent_chat_queue_full": "Terlalu banyak mesej menunggu: buang satu atau tunggu ejen selesai.", "ui.agent_chat_queued": "Menunggu", @@ -1569,6 +1570,11 @@ "ui.draft": "Sudut Draf", "ui.drawing": "Lukisan", "ui.drill_point": "Hujung Gerudi", + "ui.easyprint_consent": "EasyPrint ialah slicer Printables dalam pelayar. Untuk membuka model di sana, SolidCraft memuat naiknya ke pelayan Printables. Pautan tamat tempoh selepas 30 minit, dan anda perlu log masuk ke Printables. Teruskan?", + "ui.easyprint_failed": "Muat naik ke EasyPrint gagal: {error}", + "ui.easyprint_opened": "Dibuka dalam EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, dalam pelayar)", + "ui.easyprint_uploading": "Memuat naik ke Printables…", "ui.edit": "Sunting", "ui.editJointLimits": "Sunting Had Sendi", "ui.edit_section_analysis": "Sunting Analisis Keratan", @@ -1860,9 +1866,7 @@ "ui.right": "Kanan", "ui.save": "Simpan", "ui.save_as": "Simpan Sebagai", - "ui.save_mesh_no_slicer": "Tiada penghiris: pilih program melalui Tersuai… atau matikan Hantar ke penghiris", "ui.save_mesh_pick_bodies": "Pilih jasad untuk disimpan", - "ui.save_mesh_temp_failed": "Tidak dapat mencipta {folder}: {error}", "ui.saved_to": "{path} disimpan", "ui.sbox_pin": "Semat di atas kotak S", "ui.sbox_unpin": "Nyahsemat", @@ -1877,7 +1881,6 @@ "ui.selection_shift_add_only": "Shift+klik menambah tanpa membuang", "ui.selection_shift_add_only_tip": "Hidup: Shift menambah item, Ctrl/Cmd menogol. Mati (lalai): Shift dan Ctrl/Cmd kedua-duanya menogol.", "ui.send": "Hantar", - "ui.send_to_slicer": "Hantar ke penghiris", "ui.sent_to_slicer": "Dihantar ke {slicer}", "ui.sheet_gap": "Jarak", "ui.shell": "Ronggakan", @@ -1969,6 +1972,7 @@ "ui.untitled": "Tanpa Tajuk", "ui.up_axis_note": "Paksi yang menghala ke atas dalam pandangan paksi, Utama dan Pandang Tepat. Reka bentuk tidak berubah.", "ui.updateToCurrentView": "Kemas Kini Pandangan Semasa", + "ui.upload": "Muat naik", "ui.view_centre": "Pusat pandangan", "ui.visual_shaded_hidden_edges": "Berlorek dengan tepi tersembunyi", "ui.visual_shaded_with_edges": "Berlorek dengan tepi", diff --git a/assets/locales/nb.json b/assets/locales/nb.json index 5522fbf41..eeed3247d 100644 --- a/assets/locales/nb.json +++ b/assets/locales/nb.json @@ -2066,9 +2066,7 @@ "ui.right": "Høyre", "ui.save": "Lagre", "ui.save_as": "Lagre som", - "ui.save_mesh_no_slicer": "Ingen slicer funnet: velg Egendefinert… og velg slicer-programmet ditt, eller slå av Send til slicer", "ui.save_mesh_pick_bodies": "Velg kroppene som skal lagres", - "ui.save_mesh_temp_failed": "Kunne ikke lage {folder}: {error}", "ui.saved_to": "Lagret {path}", "ui.sbox_pin": "Fest øverst i S-boksen", "ui.sbox_unpin": "Løsne", @@ -2083,7 +2081,6 @@ "ui.selection_shift_add_only": "Shift+klikk legger til uten å fjerne", "ui.selection_shift_add_only_tip": "På: Shift legger til elementer, Ctrl/Cmd veksler. Av (standard): Shift og Ctrl/Cmd veksler begge.", "ui.send": "Send", - "ui.send_to_slicer": "Send til slicer", "ui.sent_to_slicer": "Sendt til {slicer}", "ui.sheet_gap": "Mellomrom", "ui.shell": "Skall", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 6249afd9a..0754534ff 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -533,6 +533,7 @@ "cmd.file_export": "Exporteren", "cmd.file_insert_mesh": "Mesh invoegen", "cmd.file_insert_step": "STEP invoegen", + "cmd.file_open_in_easyprint": "Openen met EasyPrint", "cmd.file_save_mesh": "Opslaan als mesh", "cmd.file_slicers": "Geïnstalleerde slicers", "cmd.frame_member": "Constructiedeel", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "Openen in een eigen venster, dat u naar een ander scherm kunt verplaatsen", "ui.agent_chat_previous_picture": "Vorige afbeelding", "ui.agent_chat_privacy": "Er gaat niets naar buiten behalve naar de agent die u uitvoert, onder uw eigen account.", - "ui.agent_chat_privacy_note": "SolidCraft verstuurt niets: de agent die u uitvoert praat met zijn eigen service onder uw eigen account. SolidCraft ziet of bewaart nooit een sleutel of wachtwoord.", + "ui.agent_chat_privacy_note": "De chat verstuurt zelf niets: de agent die u uitvoert praat met zijn eigen service onder uw eigen account. SolidCraft ziet of bewaart nooit een sleutel of wachtwoord.", "ui.agent_chat_queue": "In wachtrij", "ui.agent_chat_queue_full": "Te veel berichten wachten: verwijder er een of wacht op de agent.", "ui.agent_chat_queued": "In wachtrij", @@ -1511,6 +1512,11 @@ "ui.draft": "Aanzet", "ui.drawing": "Tekening", "ui.drill_point": "Boorpunt", + "ui.easyprint_consent": "EasyPrint is de slicer van Printables in de browser. Om het model daar te openen, uploadt SolidCraft het naar de servers van Printables. De link verloopt na 30 minuten en u moet bij Printables zijn ingelogd. Doorgaan?", + "ui.easyprint_failed": "Uploaden naar EasyPrint mislukt: {error}", + "ui.easyprint_opened": "Geopend in EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, in de browser)", + "ui.easyprint_uploading": "Uploaden naar Printables…", "ui.edit": "Bewerken", "ui.editJointLimits": "Verbindingslimieten bewerken", "ui.edit_section_analysis": "Doorsnedeanalyse bewerken", @@ -1802,9 +1808,7 @@ "ui.right": "Rechts", "ui.save": "Opslaan", "ui.save_as": "Opslaan als", - "ui.save_mesh_no_slicer": "Geen slicer gevonden: kies Aangepast… en selecteer uw slicerprogramma, of schakel Naar slicer verzenden uit", "ui.save_mesh_pick_bodies": "Selecteer de op te slaan lichamen", - "ui.save_mesh_temp_failed": "{folder} kon niet worden gemaakt: {error}", "ui.saved_to": "{path} opgeslagen", "ui.sbox_pin": "Bovenaan het S-vak vastpinnen", "ui.sbox_unpin": "Losmaken", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+klik voegt toe zonder te verwijderen", "ui.selection_shift_add_only_tip": "Aan: Shift voegt items toe, Ctrl/Cmd schakelt om. Uit (standaard): Shift en Ctrl/Cmd schakelen beide om.", "ui.send": "Verzenden", - "ui.send_to_slicer": "Naar slicer verzenden", "ui.sent_to_slicer": "Verzonden naar {slicer}", "ui.sheet_gap": "Opening", "ui.shell": "Schalen", @@ -1911,6 +1914,7 @@ "ui.untitled": "Naamloos", "ui.up_axis_note": "Welke as in de weergaven omhoog wijst (aanzicht op as, Home, Kijken naar). Ontwerpen blijven ongewijzigd.", "ui.updateToCurrentView": "Bijwerken naar huidige weergave", + "ui.upload": "Uploaden", "ui.view_centre": "Weergavemidden", "ui.visual_shaded_hidden_edges": "Gearceerd met verborgen randen", "ui.visual_shaded_with_edges": "Gearceerd met randen", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 82f088b7f..873f5b346 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -588,6 +588,7 @@ "cmd.file_export": "Eksportuj", "cmd.file_insert_mesh": "Wstaw siatkę", "cmd.file_insert_step": "Wstaw STEP", + "cmd.file_open_in_easyprint": "Otwórz w EasyPrint", "cmd.file_save_mesh": "Zapisz jako siatkę", "cmd.file_slicers": "Zainstalowane slicery", "cmd.frame_member": "Element ramy", @@ -1517,7 +1518,7 @@ "ui.agent_chat_pop_out": "Otwórz w osobnym oknie, które możesz przenieść na inny ekran", "ui.agent_chat_previous_picture": "Poprzedni obraz", "ui.agent_chat_privacy": "Nic nie trafia nigdzie poza uruchomionym przez Ciebie agentem, na Twoim własnym koncie.", - "ui.agent_chat_privacy_note": "SolidCraft nigdzie niczego nie wysyła: uruchomiony przez Ciebie agent łączy się z własną usługą na Twoim koncie. SolidCraft nigdy nie widzi ani nie przechowuje klucza ani hasła.", + "ui.agent_chat_privacy_note": "Czat sam z siebie nigdzie niczego nie wysyła: uruchomiony przez Ciebie agent łączy się z własną usługą na Twoim koncie. SolidCraft nigdy nie widzi ani nie przechowuje klucza ani hasła.", "ui.agent_chat_queue": "Kolejka", "ui.agent_chat_queue_full": "Za dużo wiadomości czeka: usuń jedną lub poczekaj na agenta.", "ui.agent_chat_queued": "W kolejce", @@ -1762,6 +1763,11 @@ "ui.draft": "Pochylenie", "ui.drawing": "Rysunek", "ui.drill_point": "Wierzchołek wiertła", + "ui.easyprint_consent": "EasyPrint to slicer Printables w przeglądarce. Aby otworzyć w nim model, SolidCraft wysyła go na serwery Printables. Link wygasa po 30 minutach, a Ty musisz być zalogowany w Printables. Kontynuować?", + "ui.easyprint_failed": "Nie udało się wysłać do EasyPrint: {error}", + "ui.easyprint_opened": "Otwarto w EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, w przeglądarce)", + "ui.easyprint_uploading": "Wysyłanie do Printables…", "ui.edit": "Edytuj", "ui.editJointLimits": "Edytuj limity złącza", "ui.edit_section_analysis": "Edytuj analizę przekroju", @@ -2067,9 +2073,7 @@ "ui.right": "Prawy", "ui.save": "Zapisz", "ui.save_as": "Zapisz jako", - "ui.save_mesh_no_slicer": "Nie znaleziono slicera: wybierz Niestandardowy… i wskaż program slicera albo wyłącz Wyślij do slicera", "ui.save_mesh_pick_bodies": "Zaznacz bryły do zapisania", - "ui.save_mesh_temp_failed": "Nie udało się utworzyć {folder}: {error}", "ui.saved_to": "Zapisano {path}", "ui.sbox_pin": "Przypnij na górze okna S", "ui.sbox_unpin": "Odepnij", @@ -2084,7 +2088,6 @@ "ui.selection_shift_add_only": "Shift+kliknięcie tylko dodaje", "ui.selection_shift_add_only_tip": "Wł.: Shift dodaje elementy, Ctrl/Cmd przełącza. Wył. (domyślnie): Shift i Ctrl/Cmd przełączają.", "ui.send": "Wyślij", - "ui.send_to_slicer": "Wyślij do slicera", "ui.sent_to_slicer": "Wysłano do {slicer}", "ui.sheet_gap": "Szczelina", "ui.shell": "Skorupa", @@ -2176,6 +2179,7 @@ "ui.untitled": "Bez tytułu", "ui.up_axis_note": "Która oś wskazuje górę w widokach (widok osi, Widok główny, Patrz na). Projekty pozostają bez zmian.", "ui.updateToCurrentView": "Aktualizuj do bieżącego widoku", + "ui.upload": "Wyślij", "ui.view_centre": "Środek widoku", "ui.visual_shaded_hidden_edges": "Cieniowany z krawędziami niewidocznymi", "ui.visual_shaded_with_edges": "Cieniowany z krawędziami", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index ac7331be5..2c6597731 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -693,6 +693,7 @@ "cmd.file_export": "Exportar", "cmd.file_insert_mesh": "Inserir malha", "cmd.file_insert_step": "Inserir STEP", + "cmd.file_open_in_easyprint": "Abrir com o EasyPrint", "cmd.file_save_mesh": "Salvar como malha", "cmd.file_slicers": "Fatiadores instalados", "cmd.frame_member": "Membro estrutural", @@ -1637,7 +1638,7 @@ "ui.agent_chat_pop_out": "Abrir em janela própria, que você pode mover para outra tela", "ui.agent_chat_previous_picture": "Imagem anterior", "ui.agent_chat_privacy": "Nada vai para lugar algum além do agente que você executa, na sua própria conta.", - "ui.agent_chat_privacy_note": "O SolidCraft não envia nada a lugar nenhum: o agente que você executa fala com o próprio serviço, na sua própria conta. O SolidCraft nunca vê nem guarda chaves ou senhas.", + "ui.agent_chat_privacy_note": "O chat não envia nada a lugar nenhum por conta própria: o agente que você executa fala com o próprio serviço, na sua própria conta. O SolidCraft nunca vê nem guarda chaves ou senhas.", "ui.agent_chat_queue": "Fila", "ui.agent_chat_queue_full": "Há mensagens demais esperando: remova uma ou aguarde o agente.", "ui.agent_chat_queued": "Na fila", @@ -1888,6 +1889,11 @@ "ui.draft": "Ângulo de saída", "ui.drawing": "Desenho", "ui.drill_point": "Ponta de broca", + "ui.easyprint_consent": "O EasyPrint é o slicer do Printables no navegador. Para abrir o modelo lá, o SolidCraft o envia para os servidores do Printables. O link expira em 30 minutos e você precisa estar conectado ao Printables. Continuar?", + "ui.easyprint_failed": "Falha ao enviar para o EasyPrint: {error}", + "ui.easyprint_opened": "Aberto no EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, no navegador)", + "ui.easyprint_uploading": "Enviando para o Printables…", "ui.edit": "Editar", "ui.editJointLimits": "Editar limites da junta", "ui.edit_section_analysis": "Editar análise de seção", @@ -2194,9 +2200,7 @@ "ui.right": "Direita", "ui.save": "Salvar", "ui.save_as": "Salvar como", - "ui.save_mesh_no_slicer": "Nenhum fatiador encontrado: escolha Personalizado… e selecione seu programa fatiador, ou desative Enviar ao fatiador", "ui.save_mesh_pick_bodies": "Selecione os corpos a salvar", - "ui.save_mesh_temp_failed": "Não foi possível criar {folder}: {error}", "ui.saved_to": "Salvo {path}", "ui.sbox_pin": "Fixar no topo da caixa S", "ui.sbox_unpin": "Desafixar", @@ -2211,7 +2215,6 @@ "ui.selection_shift_add_only": "Shift+clique adiciona sem remover", "ui.selection_shift_add_only_tip": "Ativado: Shift adiciona itens, Ctrl/Cmd alterna. Desativado (padrão): Shift e Ctrl/Cmd alternam.", "ui.send": "Enviar", - "ui.send_to_slicer": "Enviar ao fatiador", "ui.sent_to_slicer": "Enviado para {slicer}", "ui.sheet_gap": "Folga", "ui.shell": "Casca", @@ -2303,6 +2306,7 @@ "ui.untitled": "Sem título", "ui.up_axis_note": "Qual eixo aponta para cima nas vistas (vista do eixo, Início, Olhar para). Os projetos não mudam.", "ui.updateToCurrentView": "Atualizar para a vista atual", + "ui.upload": "Enviar", "ui.view_centre": "Centro da vista", "ui.visual_shaded_hidden_edges": "Sombreado com arestas ocultas", "ui.visual_shaded_with_edges": "Sombreado com arestas", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 124d1361b..caa9740f3 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -533,6 +533,7 @@ "cmd.file_export": "Exportă", "cmd.file_insert_mesh": "Inserează plasă", "cmd.file_insert_step": "Inserează STEP", + "cmd.file_open_in_easyprint": "Deschide cu EasyPrint", "cmd.file_save_mesh": "Salvează ca plasă", "cmd.file_slicers": "Slicere instalate", "cmd.frame_member": "Element de cadru", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "Deschide în propria fereastră, pe care o puteți muta pe alt ecran", "ui.agent_chat_previous_picture": "Imaginea anterioară", "ui.agent_chat_privacy": "Nimic nu merge nicăieri în afară de agentul pe care îl rulați, sub propriul cont.", - "ui.agent_chat_privacy_note": "SolidCraft nu trimite nimic nicăieri: agentul pe care îl rulați comunică cu propriul serviciu sub contul dumneavoastră. SolidCraft nu vede și nu stochează niciodată o cheie sau o parolă.", + "ui.agent_chat_privacy_note": "Chatul nu trimite nimic nicăieri de la sine: agentul pe care îl rulați comunică cu propriul serviciu sub contul dumneavoastră. SolidCraft nu vede și nu stochează niciodată o cheie sau o parolă.", "ui.agent_chat_queue": "Coadă", "ui.agent_chat_queue_full": "Prea multe mesaje așteaptă: eliminați unul sau așteptați agentul.", "ui.agent_chat_queued": "În coadă", @@ -1511,6 +1512,11 @@ "ui.draft": "Înclinare", "ui.drawing": "Desen", "ui.drill_point": "Vârf de burghiu", + "ui.easyprint_consent": "EasyPrint este slicerul Printables din browser. Pentru a deschide modelul acolo, SolidCraft îl încarcă pe serverele Printables. Linkul expiră după 30 de minute, iar dumneavoastră trebuie să fiți autentificat pe Printables. Continuați?", + "ui.easyprint_failed": "Încărcarea în EasyPrint a eșuat: {error}", + "ui.easyprint_opened": "Deschis în EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, în browser)", + "ui.easyprint_uploading": "Se încarcă pe Printables…", "ui.edit": "Editează", "ui.editJointLimits": "Editează limitele îmbinării", "ui.edit_section_analysis": "Editează analiza secțiunii", @@ -1802,9 +1808,7 @@ "ui.right": "Dreapta", "ui.save": "Salvează", "ui.save_as": "Salvează ca", - "ui.save_mesh_no_slicer": "Niciun slicer găsit: alegeți Personalizat… și selectați programul slicer sau dezactivați Trimite la slicer", "ui.save_mesh_pick_bodies": "Selectați corpurile de salvat", - "ui.save_mesh_temp_failed": "Nu s-a putut crea {folder}: {error}", "ui.saved_to": "Salvat {path}", "ui.sbox_pin": "Fixează în partea de sus a casetei S", "ui.sbox_unpin": "Defixează", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+clic adaugă fără a elimina", "ui.selection_shift_add_only_tip": "Activat: Shift adaugă elemente, Ctrl/Cmd comută. Dezactivat (implicit): Shift și Ctrl/Cmd comută ambele.", "ui.send": "Trimite", - "ui.send_to_slicer": "Trimite la slicer", "ui.sent_to_slicer": "Trimis la {slicer}", "ui.sheet_gap": "Spațiu", "ui.shell": "Scobire", @@ -1911,6 +1914,7 @@ "ui.untitled": "Fără titlu", "ui.up_axis_note": "Ce axă indică în sus în vizualizări (vizualizare pe axă, Acasă, Privește spre). Proiectele rămân neschimbate.", "ui.updateToCurrentView": "Actualizează la vizualizarea curentă", + "ui.upload": "Încarcă", "ui.view_centre": "Centrul vizualizării", "ui.visual_shaded_hidden_edges": "Umbrit cu muchii ascunse", "ui.visual_shaded_with_edges": "Umbrit cu muchii", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index cf4586fec..f60c74b9e 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -533,6 +533,7 @@ "cmd.file_export": "Экспорт", "cmd.file_insert_mesh": "Вставить меш", "cmd.file_insert_step": "Вставить STEP", + "cmd.file_open_in_easyprint": "Открыть в EasyPrint", "cmd.file_save_mesh": "Сохранить как меш", "cmd.file_slicers": "Установленные слайсеры", "cmd.frame_member": "Элемент рамы", @@ -1325,7 +1326,7 @@ "ui.agent_chat_pop_out": "Открыть в отдельном окне, которое можно перенести на другой экран", "ui.agent_chat_previous_picture": "Предыдущее изображение", "ui.agent_chat_privacy": "Ничего не уходит никуда, кроме запускаемого вами агента, под вашей учётной записью.", - "ui.agent_chat_privacy_note": "SolidCraft ничего никуда не отправляет: запускаемый вами агент обращается к своему сервису под вашей учётной записью. SolidCraft никогда не видит и не хранит ключ или пароль.", + "ui.agent_chat_privacy_note": "Чат сам ничего никуда не отправляет: запускаемый вами агент обращается к своему сервису под вашей учётной записью. SolidCraft никогда не видит и не хранит ключ или пароль.", "ui.agent_chat_queue": "В очередь", "ui.agent_chat_queue_full": "Слишком много сообщений в ожидании: удалите одно или дождитесь агента.", "ui.agent_chat_queued": "В очереди", @@ -1568,6 +1569,11 @@ "ui.draft": "Уклон", "ui.drawing": "Чертёж", "ui.drill_point": "Конус сверла", + "ui.easyprint_consent": "EasyPrint — это слайсер Printables в браузере. Чтобы открыть модель там, SolidCraft загружает её на серверы Printables. Ссылка действует 30 минут, и вам нужно войти в Printables. Продолжить?", + "ui.easyprint_failed": "Не удалось загрузить в EasyPrint: {error}", + "ui.easyprint_opened": "Открыто в EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, в браузере)", + "ui.easyprint_uploading": "Загрузка в Printables…", "ui.edit": "Изменить", "ui.editJointLimits": "Изменить ограничения сопряжения", "ui.edit_section_analysis": "Изменить анализ сечения", @@ -1859,9 +1865,7 @@ "ui.right": "Справа", "ui.save": "Сохранить", "ui.save_as": "Сохранить как", - "ui.save_mesh_no_slicer": "Слайсер не найден: выберите «Другая…» и укажите программу или отключите «Отправить в слайсер»", "ui.save_mesh_pick_bodies": "Выберите тела для сохранения", - "ui.save_mesh_temp_failed": "Не удалось создать {folder}: {error}", "ui.saved_to": "Сохранено: {path}", "ui.sbox_pin": "Закрепить вверху панели S", "ui.sbox_unpin": "Открепить", @@ -1876,7 +1880,6 @@ "ui.selection_shift_add_only": "Shift+щелчок добавляет без удаления", "ui.selection_shift_add_only_tip": "Вкл.: Shift добавляет объекты, Ctrl/Cmd переключает. Выкл. (по умолчанию): Shift и Ctrl/Cmd оба переключают.", "ui.send": "Отправить", - "ui.send_to_slicer": "Отправить в слайсер", "ui.sent_to_slicer": "Отправлено в {slicer}", "ui.sheet_gap": "Зазор", "ui.shell": "Оболочка", @@ -1968,6 +1971,7 @@ "ui.untitled": "Без имени", "ui.up_axis_note": "Какая ось направлена вверх в видах (осевые виды, «Главная», «Взгляд на»). Дизайны не меняются.", "ui.updateToCurrentView": "Обновить до текущего вида", + "ui.upload": "Загрузить", "ui.view_centre": "Центр вида", "ui.visual_shaded_hidden_edges": "Заполненный с невидимыми рёбрами", "ui.visual_shaded_with_edges": "Заполненный с рёбрами", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 8c527e5e9..a0bb89c4e 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -533,6 +533,7 @@ "cmd.file_export": "Exportera", "cmd.file_insert_mesh": "Infoga mesh", "cmd.file_insert_step": "Infoga STEP", + "cmd.file_open_in_easyprint": "Öppna med EasyPrint", "cmd.file_save_mesh": "Spara som mesh", "cmd.file_slicers": "Installerade slicers", "cmd.frame_member": "Ramdel", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "Öppna i ett eget fönster som du kan flytta till en annan skärm", "ui.agent_chat_previous_picture": "Föregående bild", "ui.agent_chat_privacy": "Inget skickas någonstans utom till agenten du kör, under ditt eget konto.", - "ui.agent_chat_privacy_note": "SolidCraft skickar ingenting någonstans: agenten du kör talar med sin egen tjänst under ditt eget konto. SolidCraft ser eller lagrar aldrig en nyckel eller ett lösenord.", + "ui.agent_chat_privacy_note": "Chatten skickar inget någonstans av sig själv: agenten du kör talar med sin egen tjänst under ditt eget konto. SolidCraft ser eller lagrar aldrig en nyckel eller ett lösenord.", "ui.agent_chat_queue": "Kö", "ui.agent_chat_queue_full": "För många meddelanden väntar: ta bort ett eller vänta på agenten.", "ui.agent_chat_queued": "Köad", @@ -1511,6 +1512,11 @@ "ui.draft": "Släppvinkel", "ui.drawing": "Ritning", "ui.drill_point": "Borrspets", + "ui.easyprint_consent": "EasyPrint är Printables slicer i webbläsaren. För att öppna modellen där laddar SolidCraft upp den till Printables servrar. Länken upphör efter 30 minuter och du måste vara inloggad på Printables. Fortsätta?", + "ui.easyprint_failed": "Uppladdningen till EasyPrint misslyckades: {error}", + "ui.easyprint_opened": "Öppnad i EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, i webbläsaren)", + "ui.easyprint_uploading": "Laddar upp till Printables…", "ui.edit": "Redigera", "ui.editJointLimits": "Redigera ledgränser", "ui.edit_section_analysis": "Redigera sektionsanalys", @@ -1802,9 +1808,7 @@ "ui.right": "Höger", "ui.save": "Spara", "ui.save_as": "Spara som", - "ui.save_mesh_no_slicer": "Ingen slicer hittades: välj Egen… och välj ditt slicer-program, eller stäng av Skicka till slicer", "ui.save_mesh_pick_bodies": "Markera kropparna som ska sparas", - "ui.save_mesh_temp_failed": "Kunde inte skapa {folder}: {error}", "ui.saved_to": "Sparade {path}", "ui.sbox_pin": "Fäst överst i S-rutan", "ui.sbox_unpin": "Lossa", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+klick lägger till utan att ta bort", "ui.selection_shift_add_only_tip": "På: Shift lägger till objekt, Ctrl/Cmd växlar. Av (standard): Shift och Ctrl/Cmd växlar båda.", "ui.send": "Skicka", - "ui.send_to_slicer": "Skicka till slicer", "ui.sent_to_slicer": "Skickat till {slicer}", "ui.sheet_gap": "Spalt", "ui.shell": "Urholka", @@ -1911,6 +1914,7 @@ "ui.untitled": "Namnlös", "ui.up_axis_note": "Vilken axel som pekar uppåt i vyerna (axelvy, Hem, Titta på). Konstruktioner ändras inte.", "ui.updateToCurrentView": "Uppdatera till aktuell vy", + "ui.upload": "Ladda upp", "ui.view_centre": "Vycentrum", "ui.visual_shaded_hidden_edges": "Skuggad med dolda kanter", "ui.visual_shaded_with_edges": "Skuggad med kanter", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index a36053cab..aba75bfe5 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -533,6 +533,7 @@ "cmd.file_export": "Dışa aktar", "cmd.file_insert_mesh": "Ağ ekle", "cmd.file_insert_step": "STEP ekle", + "cmd.file_open_in_easyprint": "EasyPrint ile aç", "cmd.file_save_mesh": "Ağ olarak kaydet", "cmd.file_slicers": "Yüklü dilimleyiciler", "cmd.frame_member": "Çerçeve Elemanı", @@ -1325,7 +1326,7 @@ "ui.agent_chat_pop_out": "Başka bir ekrana taşıyabileceğiniz ayrı bir pencerede aç", "ui.agent_chat_previous_picture": "Önceki resim", "ui.agent_chat_privacy": "Kendi hesabınızla çalıştırdığınız ajan dışında hiçbir yere bir şey gitmez.", - "ui.agent_chat_privacy_note": "SolidCraft hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.", + "ui.agent_chat_privacy_note": "Sohbet kendi başına hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.", "ui.agent_chat_queue": "Sıraya al", "ui.agent_chat_queue_full": "Çok fazla ileti bekliyor: birini kaldırın veya ajanı bekleyin.", "ui.agent_chat_queued": "Sırada", @@ -1568,6 +1569,11 @@ "ui.draft": "Koniklik", "ui.drawing": "Teknik resim", "ui.drill_point": "Matkap ucu", + "ui.easyprint_consent": "EasyPrint, Printables'ın tarayıcıdaki dilimleyicisidir. Modeli orada açmak için SolidCraft onu Printables sunucularına yükler. Bağlantı 30 dakika sonra sona erer ve Printables'ta oturum açmış olmanız gerekir. Devam edilsin mi?", + "ui.easyprint_failed": "EasyPrint'e yükleme başarısız: {error}", + "ui.easyprint_opened": "EasyPrint içinde açıldı", + "ui.easyprint_row": "EasyPrint (Printables, tarayıcıda)", + "ui.easyprint_uploading": "Printables'a yükleniyor…", "ui.edit": "Düzenle", "ui.editJointLimits": "Bağlantı sınırlarını düzenle", "ui.edit_section_analysis": "Kesit analizini düzenle", @@ -1859,9 +1865,7 @@ "ui.right": "Sağ", "ui.save": "Kaydet", "ui.save_as": "Farklı kaydet", - "ui.save_mesh_no_slicer": "Dilimleyici bulunamadı: “Özel…” seçeneğini seçip dilimleyici programını belirtin veya “Dilimleyiciye gönder” seçeneğini kapatın", "ui.save_mesh_pick_bodies": "Kaydedilecek gövdeleri seçin", - "ui.save_mesh_temp_failed": "{folder} oluşturulamadı: {error}", "ui.saved_to": "{path} konumuna kaydedildi", "ui.sbox_pin": "S kutusunun en üstüne sabitle", "ui.sbox_unpin": "Sabitlemeyi kaldır", @@ -1876,7 +1880,6 @@ "ui.selection_shift_add_only": "Shift+tıklama kaldırmadan ekler", "ui.selection_shift_add_only_tip": "Açık: Shift öğe ekler, Ctrl/Cmd açıp kapatır. Kapalı (varsayılan): Shift ve Ctrl/Cmd ikisi de açıp kapatır.", "ui.send": "Gönder", - "ui.send_to_slicer": "Dilimleyiciye gönder", "ui.sent_to_slicer": "{slicer} uygulamasına gönderildi", "ui.sheet_gap": "Boşluk", "ui.shell": "Kabuk", @@ -1968,6 +1971,7 @@ "ui.untitled": "Adsız", "ui.up_axis_note": "Görünümlerde (eksen görünümü, Başlangıç, Bak) hangi eksenin yukarıyı gösterdiğini belirler. Tasarımlar değişmez.", "ui.updateToCurrentView": "Geçerli görünüme güncelle", + "ui.upload": "Yükle", "ui.view_centre": "Görünüm merkezi", "ui.visual_shaded_hidden_edges": "Gizli kenarlarla gölgeli", "ui.visual_shaded_with_edges": "Kenarlarla gölgeli", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index a4d89b48b..1edb2c94a 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -689,6 +689,7 @@ "cmd.file_export": "Експорт", "cmd.file_insert_mesh": "Вставити сітку", "cmd.file_insert_step": "Вставити STEP", + "cmd.file_open_in_easyprint": "Відкрити в EasyPrint", "cmd.file_save_mesh": "Зберегти як сітку", "cmd.file_slicers": "Встановлені слайсери", "cmd.frame_member": "Елемент рами", @@ -1619,7 +1620,7 @@ "ui.agent_chat_pop_out": "Відкрити у власному вікні, яке можна перемістити на інший екран", "ui.agent_chat_previous_picture": "Попереднє зображення", "ui.agent_chat_privacy": "Нічого нікуди не надсилається, крім агента, який ви запускаєте, під вашим власним обліковим записом.", - "ui.agent_chat_privacy_note": "SolidCraft нічого нікуди не надсилає: агент, який ви запускаєте, спілкується з власним сервісом під вашим обліковим записом. SolidCraft ніколи не бачить і не зберігає ключ чи пароль.", + "ui.agent_chat_privacy_note": "Чат сам нічого нікуди не надсилає: агент, який ви запускаєте, спілкується з власним сервісом під вашим обліковим записом. SolidCraft ніколи не бачить і не зберігає ключ чи пароль.", "ui.agent_chat_queue": "У чергу", "ui.agent_chat_queue_full": "Забагато повідомлень в очікуванні: приберіть одне або зачекайте на агента.", "ui.agent_chat_queued": "У черзі", @@ -1864,6 +1865,11 @@ "ui.draft": "Ухил", "ui.drawing": "Креслення", "ui.drill_point": "Вістря свердла", + "ui.easyprint_consent": "EasyPrint — це слайсер Printables у браузері. Щоб відкрити модель там, SolidCraft завантажує її на сервери Printables. Посилання діє 30 хвилин, і вам потрібно увійти в Printables. Продовжити?", + "ui.easyprint_failed": "Не вдалося завантажити в EasyPrint: {error}", + "ui.easyprint_opened": "Відкрито в EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, у браузері)", + "ui.easyprint_uploading": "Завантаження на Printables…", "ui.edit": "Редагувати", "ui.editJointLimits": "Редагувати обмеження з'єднання", "ui.edit_section_analysis": "Редагувати аналіз перерізу", @@ -2162,9 +2168,7 @@ "ui.right": "Справа", "ui.save": "Зберегти", "ui.save_as": "Зберегти як", - "ui.save_mesh_no_slicer": "Слайсер не знайдено: виберіть «Власна…» і вкажіть свою програму-слайсер або вимкніть «Надіслати в слайсер»", "ui.save_mesh_pick_bodies": "Виберіть тіла для збереження", - "ui.save_mesh_temp_failed": "Не вдалося створити {folder}: {error}", "ui.saved_to": "Збережено {path}", "ui.sbox_pin": "Закріпити вгорі поля S", "ui.sbox_unpin": "Відкріпити", @@ -2179,7 +2183,6 @@ "ui.selection_shift_add_only": "Shift+клацання додає без вилучення", "ui.selection_shift_add_only_tip": "Увімк.: Shift додає елементи, Ctrl/Cmd перемикає. Вимк. (типово): Shift і Ctrl/Cmd обидва перемикають.", "ui.send": "Надіслати", - "ui.send_to_slicer": "Надіслати в слайсер", "ui.sent_to_slicer": "Надіслано в {slicer}", "ui.sheet_gap": "Проміжок", "ui.shell": "Оболонка", @@ -2271,6 +2274,7 @@ "ui.untitled": "Без назви", "ui.up_axis_note": "Яка вісь спрямована вгору у видах (вид осі, головний, наведення). Проєкти не змінюються.", "ui.updateToCurrentView": "Оновити до поточного виду", + "ui.upload": "Завантажити", "ui.view_centre": "Центр виду", "ui.visual_shaded_hidden_edges": "Затінений із прихованими ребрами", "ui.visual_shaded_with_edges": "Затінений із ребрами", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index df12ada4c..e81b24128 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -534,6 +534,7 @@ "cmd.file_export": "Xuất tệp", "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", "cmd.file_insert_step": "Chèn tệp STEP", + "cmd.file_open_in_easyprint": "Mở bằng EasyPrint", "cmd.file_save_mesh": "Lưu dưới dạng lưới đa giác", "cmd.file_slicers": "Phần mềm cắt lớp đã cài đặt", "cmd.frame_member": "Thanh khung", @@ -1326,7 +1327,7 @@ "ui.agent_chat_pop_out": "Mở trong cửa sổ riêng để bạn có thể di chuyển sang màn hình khác", "ui.agent_chat_previous_picture": "Ảnh trước", "ui.agent_chat_privacy": "Không có dữ liệu nào được gửi đi bất cứ đâu ngoại trừ tới tác tử bạn chạy, theo tài khoản của chính bạn.", - "ui.agent_chat_privacy_note": "SolidCraft không gửi bất kỳ dữ liệu nào ra ngoài: AI Agent giao tiếp trực tiếp với dịch vụ bằng tài khoản của bạn. SolidCraft không bao giờ thấy hay lưu khóa/mật khẩu.", + "ui.agent_chat_privacy_note": "Khung chat tự nó không gửi bất kỳ dữ liệu nào ra ngoài: AI Agent giao tiếp trực tiếp với dịch vụ bằng tài khoản của bạn. SolidCraft không bao giờ thấy hay lưu khóa/mật khẩu.", "ui.agent_chat_queue": "Hàng đợi", "ui.agent_chat_queue_full": "Quá nhiều tin nhắn đang chờ: hãy xóa bớt hoặc chờ AI hoàn thành.", "ui.agent_chat_queued": "Đã vào hàng đợi", @@ -1569,6 +1570,11 @@ "ui.draft": "Độ côn thoát khuôn", "ui.drawing": "Bản vẽ 2D", "ui.drill_point": "Đỉnh mũi khoan (Drill Point)", + "ui.easyprint_consent": "EasyPrint là trình cắt lớp (slicer) của Printables chạy trong trình duyệt. Để mở mô hình ở đó, SolidCraft tải mô hình lên máy chủ của Printables. Liên kết hết hạn sau 30 phút và bạn cần đăng nhập Printables. Tiếp tục?", + "ui.easyprint_failed": "Tải lên EasyPrint thất bại: {error}", + "ui.easyprint_opened": "Đã mở trong EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, trong trình duyệt)", + "ui.easyprint_uploading": "Đang tải lên Printables…", "ui.edit": "Chỉnh sửa", "ui.editJointLimits": "Chỉnh sửa giới hạn khớp nối", "ui.edit_section_analysis": "Chỉnh sửa phân tích mặt cắt", @@ -1860,9 +1866,7 @@ "ui.right": "Phải (Hình chiếu cạnh)", "ui.save": "Lưu", "ui.save_as": "Lưu thành tệp mới", - "ui.save_mesh_no_slicer": "Không tìm thấy phần mềm cắt lớp (slicer): hãy chọn Tùy chỉnh… và chỉ định chương trình cắt lớp, hoặc tắt tùy chọn Gửi đến slicer", "ui.save_mesh_pick_bodies": "Chọn các thân khối cần lưu", - "ui.save_mesh_temp_failed": "Không thể tạo thư mục {folder}: {error}", "ui.saved_to": "Đã lưu {path}", "ui.sbox_pin": "Ghim lên đầu hộp tìm kiếm phím S", "ui.sbox_unpin": "Bỏ ghim", @@ -1877,7 +1881,6 @@ "ui.selection_shift_add_only": "Shift+nhấp chỉ thêm, không bỏ chọn", "ui.selection_shift_add_only_tip": "Bật: Shift thêm mục, Ctrl/Cmd bật/tắt. Tắt (mặc định): cả Shift và Ctrl/Cmd đều bật/tắt.", "ui.send": "Gửi", - "ui.send_to_slicer": "Gửi sang phần mềm cắt lát (Slicer)", "ui.sent_to_slicer": "Đã gửi sang {slicer}", "ui.sheet_gap": "Khe hở tấm", "ui.shell": "Tạo vỏ mỏng (Shell)", @@ -1969,6 +1972,7 @@ "ui.untitled": "Chưa đặt tên", "ui.up_axis_note": "Trục nào hướng lên trên trong các góc nhìn (góc nhìn theo trục, Chuẩn, Nhìn thẳng). Các mô hình thiết kế không bị thay đổi.", "ui.updateToCurrentView": "Cập nhật theo góc nhìn hiện tại", + "ui.upload": "Tải lên", "ui.view_centre": "Tâm góc nhìn", "ui.visual_shaded_hidden_edges": "Tô bóng kèm nét khuất", "ui.visual_shaded_with_edges": "Tô bóng kèm hiển thị cạnh", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index c8a977edd..d58106a6e 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -533,6 +533,7 @@ "cmd.file_export": "匯出", "cmd.file_insert_mesh": "插入網格", "cmd.file_insert_step": "插入 STEP", + "cmd.file_open_in_easyprint": "用 EasyPrint 開啟", "cmd.file_save_mesh": "另存為網格", "cmd.file_slicers": "已安裝的切片軟體", "cmd.frame_member": "框架構件", @@ -1269,7 +1270,7 @@ "ui.agent_chat_pop_out": "在獨立視窗中開啟(可移到另一個螢幕)", "ui.agent_chat_previous_picture": "上一張圖片", "ui.agent_chat_privacy": "除了您以自己的帳號執行的代理之外,不會向任何地方傳送任何內容。", - "ui.agent_chat_privacy_note": "SolidCraft 不向任何地方傳送任何內容:您執行的代理以您自己的帳號與它自己的服務通訊。SolidCraft 從不檢視或儲存任何金鑰或密碼。", + "ui.agent_chat_privacy_note": "聊天本身不向任何地方傳送任何內容:您執行的代理以您自己的帳號與它自己的服務通訊。SolidCraft 從不檢視或儲存任何金鑰或密碼。", "ui.agent_chat_queue": "加入佇列", "ui.agent_chat_queue_full": "等待中的訊息太多:請移除一則,或等待代理完成。", "ui.agent_chat_queued": "已加入佇列", @@ -1511,6 +1512,11 @@ "ui.draft": "拔模", "ui.drawing": "工程圖", "ui.drill_point": "鑽尖", + "ui.easyprint_consent": "EasyPrint 是 Printables 在瀏覽器中的切片軟體。為了在那裡開啟模型,SolidCraft 會將模型上傳到 Printables 的伺服器。連結 30 分鐘後失效,且您需要登入 Printables。要繼續嗎?", + "ui.easyprint_failed": "上傳到 EasyPrint 失敗:{error}", + "ui.easyprint_opened": "已在 EasyPrint 中開啟", + "ui.easyprint_row": "EasyPrint(Printables,在瀏覽器中)", + "ui.easyprint_uploading": "正在上傳到 Printables…", "ui.edit": "編輯", "ui.editJointLimits": "編輯接頭限制", "ui.edit_section_analysis": "編輯截面分析", @@ -1802,9 +1808,7 @@ "ui.right": "右視", "ui.save": "儲存", "ui.save_as": "另存為", - "ui.save_mesh_no_slicer": "未找到切片軟體:請選擇「自訂…」並指定切片軟體程式,或關閉「傳送到切片軟體」", "ui.save_mesh_pick_bodies": "請選擇要儲存的實體", - "ui.save_mesh_temp_failed": "無法建立 {folder}:{error}", "ui.saved_to": "已儲存:{path}", "ui.sbox_pin": "固定到 S 框頂部", "ui.sbox_unpin": "取消固定", @@ -1819,7 +1823,6 @@ "ui.selection_shift_add_only": "Shift+點擊僅新增、不取消選擇", "ui.selection_shift_add_only_tip": "開:Shift 新增,Ctrl/Cmd 切換。關(預設):Shift 與 Ctrl/Cmd 均可切換。", "ui.send": "傳送", - "ui.send_to_slicer": "傳送到切片軟體", "ui.sent_to_slicer": "已傳送到 {slicer}", "ui.sheet_gap": "間隙", "ui.shell": "薄殼", @@ -1911,6 +1914,7 @@ "ui.untitled": "未命名", "ui.up_axis_note": "檢視中朝上的軸(軸檢視、主檢視、注視)。設計本身不變。", "ui.updateToCurrentView": "更新為目前檢視", + "ui.upload": "上傳", "ui.view_centre": "檢視中心", "ui.visual_shaded_hidden_edges": "含隱藏邊的著色", "ui.visual_shaded_with_edges": "含邊線的著色", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 07f7eecee..16781b1b5 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -774,7 +774,9 @@ "cmd.file_export": "导出", "cmd.file_insert_mesh": "插入网格", "cmd.file_insert_step": "插入 STEP", + "cmd.file_open_in_easyprint": "用 EasyPrint 打开", "cmd.file_save_mesh": "另存为网格", + "cmd.file_send_to_slicer": "发送到切片软件", "cmd.file_slicers": "已安装的切片软件", "cmd.frame_member": "框架构件", "cmd.frame_profile_insert": "插入型材", @@ -2477,7 +2479,7 @@ "ui.agent_chat_pop_out": "在独立窗口中打开(可移到另一个屏幕)", "ui.agent_chat_previous_picture": "上一张图片", "ui.agent_chat_privacy": "除了你以自己的账户运行的智能体之外,不会向任何地方发送任何内容。", - "ui.agent_chat_privacy_note": "SolidCraft 不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。", + "ui.agent_chat_privacy_note": "聊天本身不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。", "ui.agent_chat_provider_models": "{count} 个模型", "ui.agent_chat_provider_other": "其他", "ui.agent_chat_provider_tip": "旁边的列表显示此提供商的模型。", @@ -2755,6 +2757,11 @@ "ui.draft": "拔模", "ui.drawing": "绘图", "ui.drill_point": "钻尖", + "ui.easyprint_consent": "EasyPrint 是 Printables 在浏览器中的切片软件。为了在那里打开模型,SolidCraft 会将模型上传到 Printables 的服务器。链接 30 分钟后失效,并且你需要登录 Printables。要继续吗?", + "ui.easyprint_failed": "上传到 EasyPrint 失败:{error}", + "ui.easyprint_opened": "已在 EasyPrint 中打开", + "ui.easyprint_row": "EasyPrint(Printables,在浏览器中)", + "ui.easyprint_uploading": "正在上传到 Printables…", "ui.edit": "编辑", "ui.editJointLimits": "编辑接头限制", "ui.edit_section_analysis": "编辑截面分析", @@ -3085,9 +3092,8 @@ "ui.right": "右视", "ui.save": "保存", "ui.save_as": "另存为", - "ui.save_mesh_no_slicer": "未找到切片软件:请选择“自定义…”并指定切片软件程序,或关闭“发送到切片软件”", + "ui.save_mesh_no_slicer_open": "未找到切片软件:请选择“自定义…”并指定切片软件程序", "ui.save_mesh_pick_bodies": "请选择要保存的实体", - "ui.save_mesh_temp_failed": "无法创建 {folder}:{error}", "ui.saved_to": "已保存:{path}", "ui.sbox_pin": "固定到 S 框顶部", "ui.sbox_unpin": "取消固定", @@ -3102,8 +3108,9 @@ "ui.selection_shift_add_only": "Shift+点击仅添加、不取消选择", "ui.selection_shift_add_only_tip": "开:Shift 添加,Ctrl/Cmd 切换。关(默认):Shift 与 Ctrl/Cmd 均可切换。", "ui.send": "发送", - "ui.send_to_slicer": "发送到切片软件", + "ui.send_to_slicer_unavailable": "“发送到切片软件”需要桌面应用:浏览器无法启动程序", "ui.sent_to_slicer": "已发送到 {slicer}", + "ui.sent_to_slicer_copy": "已作为 {file} 发送到 {slicer},因为第一个文件仍在其中打开", "ui.sheet_gap": "间隙", "ui.shell": "抽壳", "ui.shortcut_capture_add_key": "请再按一个普通键。按 Esc 取消。", @@ -3138,6 +3145,15 @@ "ui.slice": "切片", "ui.slicer": "切片软件", "ui.slicer_delete_tip": "{program}\n按 Delete 键从列表中移除", + "ui.slicer_lost": "{slicer} 已启动,但无法再次找到它来发送文件。文件已保存到 {path}:请从该位置打开。", + "ui.slicer_no_file": "{slicer} 已就绪,但没有可发送给它的文件。", + "ui.slicer_no_response": "{slicer} 未在规定时间内响应。文件已保存到 {path}:切片软件启动后请再次发送。", + "ui.slicer_resend_hint": "再次发送会替换切片软件中已打开的文件。", + "ui.slicer_single_instance": "在已运行的切片软件中打开文件", + "ui.slicer_single_instance_tip": "PrusaSlicer、SuperSlicer 和 Cura 会在已打开的窗口中加载文件,而不是再启动一个。其他切片软件按原样启动。PrusaSlicer 3.0 始终如此:其启动器无法以其他方式接收文件。", + "ui.slicer_starting": "正在启动 {slicer}…", + "ui.slicer_still_starting": "仍在等待 {slicer} 启动。没有发送其他内容。", + "ui.slicer_stl_fallback": "无法写入 3MF,因此发送的是 STL。", "ui.slot": "槽", "ui.smooth": "平滑", "ui.smooth_wheel_zoom": "平滑滚轮缩放", @@ -3205,6 +3221,7 @@ "ui.untitled": "无标题", "ui.up_axis_note": "视图中朝上的轴(轴视图、主视图、注视)。设计本身不变。", "ui.updateToCurrentView": "更新为当前视图", + "ui.upload": "上传", "ui.vertical_constraint": "垂直约束", "ui.view_centre": "视图中心", "ui.viewport_theme_follow": "跟随主题", diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c1728044c..739b90a8d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -3,9 +3,16 @@ #[path = "file_thumbnail.rs"] mod thumbnail; +#[path = "file_easyprint.rs"] +mod easyprint; + #[path = "file_import.rs"] pub(crate) mod import; +#[cfg(not(target_arch = "wasm32"))] +#[path = "file_send.rs"] +mod send; + use serde_json::{Value, json}; use solidcraft_doc::Document; use solidcraft_io::Format; @@ -54,10 +61,20 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("INSERT", "FILES") .icon("mesh_export") .noundo() - .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id, name or program path from file.slicers (open the saved file there); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"), + .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"), + CommandSpec::new("file.send_to_slicer", "Send to Slicer", send_to_slicer) + .enabled(starts_programs) + .at("INSERT", "FILES") + .icon("mesh_export") + .noundo() + .params("slicer: id or name from file.slicers, or a program the user added under Custom…; bodies?: [names] (default: the selected bodies); wait?: block|return|no (default block: a slicer that drops a file at a cold start is started alone and the call waits up to 10 s for it to be ready, then sends; return: start it and answer {starting}; no: send now); single_instance?: bool (default true: PrusaSlicer, SuperSlicer and Cura load the file in the window that is open); format?: 3mf|stl|3mf-tagged (default 3mf, in millimetres; STL if that can't be written) → saves the bodies in this user's slicer folder and opens the file in the slicer. The file name stays the same for the same design and bodies, so sending again replaces it (use the slicer's Reload from disk)"), + CommandSpec::new("file.open_in_easyprint", "Open with EasyPrint", easyprint::open_in_easyprint) + .icon("mesh_export") + .noundo() + .params("consent: bool (required: true only once the user has agreed to upload the model to Printables' servers; it stays there for 30 minutes and opening it needs a Printables sign-in); bodies?: [names] (default: the selected bodies); format?: 3mf|stl (default 3mf, in millimetres) → uploads the bodies to EasyPrint, Printables' slicer in the browser, and opens it in the browser. 100 MB at most. Works in the desktop app and the browser build; the CLI has no way to upload yet"), CommandSpec::new("file.slicers", "Installed Slicers", slicers).icon("export") .noundo() - .params("→ the slicers found on this machine: [{id, name, icon?}]; pass an id or name as file.save_mesh's `slicer`"), + .params("→ the slicers found on this machine: [{id, name, program, icon?}]; pass an id, a name or the program path as file.send_to_slicer's or file.save_mesh's `slicer`"), ]; fn new_doc(s: &mut Session, p: &Value) -> Result { @@ -681,28 +698,81 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { Some("3mf-tagged") => Format::ThreeMfTagged, Some(other) => return Err(bad(cmd, format!("unknown mesh format `{other}` (stl, 3mf, 3mf-tagged)"))), }; - let slicer = match str_(p, "slicer") { - None => None, - Some(spec) => Some( - crate::slicers::resolve(spec).ok_or_else(|| bad(cmd, format!("no slicer `{spec}` (see file.slicers, or give the path of a program)")))?, - ), - }; + // `slicer` sends the saved file to a program, through the same pipeline as `file.send_to_slicer` + // (a slicer that needs starting is waited for, `single_instance` applies). It is kept for scripts + // and may be deprecated later in favour of `file.send_to_slicer` or a Send to App workflow; that is + // a possibility, not a plan. let quality = mesh_quality(p, cmd)?; - let mut out = export_to(s, path, format, &string_list(p, "bodies"), quality)?; - if let (Some(slicer), Some(obj)) = (slicer, out.as_object_mut()) { - // The file is saved either way; a slicer that won't start is reported, not fatal. - match slicer.open(path) { - Ok(()) => obj.insert("slicer".into(), json!(slicer.name)), - Err(e) => obj.insert("slicer_error".into(), json!(e)), - }; + if let Some(spec) = str_(p, "slicer") { + #[cfg(target_arch = "wasm32")] + { + let _ = spec; + return Err(bad(cmd, "a slicer can't be started from the browser")); + } + #[cfg(not(target_arch = "wasm32"))] + return send::send( + s, + send::Send { + cmd, + kind: crate::slicers::TargetKind::Slicer, + spec, + bodies: string_list(p, "bodies"), + format, + quality, + dest: send::Dest::Path(path), + single_instance: bool_(p, "single_instance").unwrap_or(true), + wait: send::Wait::Block, + }, + ); + } + export_to(s, path, format, &string_list(p, "bodies"), quality) +} + +/// The browser build can't start a program. +fn starts_programs(_: &Session) -> std::result::Result<(), String> { + if cfg!(target_arch = "wasm32") { Err("a slicer can't be started from the browser".into()) } else { Ok(()) } +} + +/// Save the bodies to this user's slicer folder and start the slicer with the file. The file +/// name stays the same for the same design and bodies, so sending again replaces it. +fn send_to_slicer(s: &mut Session, p: &Value) -> Result { + let cmd = "file.send_to_slicer"; + #[cfg(target_arch = "wasm32")] + { + let _ = (s, p); + Err(bad(cmd, "a slicer can't be started from the browser")) + } + #[cfg(not(target_arch = "wasm32"))] + { + let format = match str_(p, "format").map(str::to_ascii_lowercase).as_deref() { + None | Some("3mf") => Format::ThreeMf, + Some("stl") => Format::StlBinary, + Some("3mf-tagged") => Format::ThreeMfTagged, + Some(other) => return Err(bad(cmd, format!("unknown mesh format `{other}` (stl, 3mf, 3mf-tagged)"))), + }; + let spec = str_(p, "slicer").ok_or_else(|| bad(cmd, "give `slicer` (see file.slicers)"))?; + let wait = send::Wait::parse(str_(p, "wait")).ok_or_else(|| bad(cmd, "`wait` is block, return or no"))?; + send::send( + s, + send::Send { + cmd, + kind: crate::slicers::TargetKind::Slicer, + spec, + bodies: string_list(p, "bodies"), + format, + quality: Default::default(), + dest: send::Dest::Folder, + single_instance: bool_(p, "single_instance").unwrap_or(true), + wait, + }, + ) } - Ok(out) } fn slicers(_: &mut Session, _: &Value) -> Result { let list: Vec = crate::slicers::detect() .iter() - .map(|d| json!({"id": d.id, "name": d.name, "icon": d.icon.as_ref().map(|i| i.path().to_string_lossy().into_owned())})) + .map(|d| json!({"id": d.id, "name": d.name, "program": d.command.first(), "icon": d.icon.as_ref().map(|i| i.path().to_string_lossy().into_owned())})) .collect(); Ok(json!({ "slicers": list })) } diff --git a/crates/engine/src/cmd/file_easyprint.rs b/crates/engine/src/cmd/file_easyprint.rs new file mode 100644 index 000000000..e899553b6 --- /dev/null +++ b/crates/engine/src/cmd/file_easyprint.rs @@ -0,0 +1,68 @@ +//! `file.open_in_easyprint`: export the bodies and hand the file to the host to upload to +//! EasyPrint (Printables' slicer in the browser). The model leaves the machine, so the command +//! refuses unless the caller says the user agreed (`consent`). The host does the HTTP and opens the +//! answer; see [`crate::easyprint`]. + +use serde_json::{Value, json}; +use solidcraft_io::Format; + +use crate::easyprint::{self, MAX_BYTES}; +use crate::params::{bad, bool_, str_, string_list}; +use crate::{Result, Session}; + +/// The bodies to send as the bytes of a mesh file. +pub(super) struct Exported { + pub bytes: Vec, + /// `stl` or `3mf`. + pub ext: &'static str, + /// A 3MF was asked for and couldn't be written, so this is an STL. + pub fell_back: bool, + /// The bodies that went in: the ones named, else the selected ones. + pub bodies: Vec, +} + +/// Export the bodies (the selected ones when none are named). A 3MF that can't be written is +/// written as an STL, and `fell_back` says so. +pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Format) -> Result { + let mut bodies = named.to_vec(); + if bodies.is_empty() { + bodies = s.selection.iter().filter_map(|x| if let crate::Sel::Body { name } = x { Some(name.clone()) } else { None }).collect(); + } + if bodies.is_empty() { + return Err(bad(cmd, "select the bodies to send, or give `bodies`")); + } + let doc = s.doc.painted(&s.world_state()); + let write = |format| solidcraft_io::export_with_metadata(&doc, &bodies, format, &s.doc.name, &s.doc.metadata); + let mut fell_back = false; + let (bytes, ext) = match (format, write(format)) { + (_, Ok(b)) => (b, if format == Format::StlBinary { "stl" } else { "3mf" }), + (Format::ThreeMf, Err(_)) => { + fell_back = true; + (write(Format::StlBinary)?, "stl") + } + (_, Err(e)) => return Err(e.into()), + }; + Ok(Exported { bytes, ext, fell_back, bodies }) +} + +pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result { + let cmd = "file.open_in_easyprint"; + let format = match str_(p, "format").map(str::to_ascii_lowercase).as_deref() { + None | Some("3mf") => Format::ThreeMf, + Some("stl") => Format::StlBinary, + Some(other) => return Err(bad(cmd, format!("unknown mesh format `{other}` (3mf, stl)"))), + }; + let upload = s.easyprint_upload.clone().ok_or_else(|| bad(cmd, "not supported yet: this app has no way to reach EasyPrint"))?; + if !bool_(p, "consent").unwrap_or(false) { + return Err(bad(cmd, "this uploads the model to Printables' servers: ask the user, then pass `consent: true`")); + } + let Exported { bytes, ext, fell_back, .. } = export_bodies(s, cmd, &string_list(p, "bodies"), format)?; + if bytes.len() > MAX_BYTES { + let mb = bytes.len().div_ceil(1_000_000); + return Err(bad(cmd, format!("the model is {mb} MB and EasyPrint takes {} MB at most: send fewer bodies", MAX_BYTES / 1_000_000))); + } + let name = easyprint::file_name(&s.doc.name, ext); + let size = bytes.len(); + upload(&name, bytes).map_err(|e| bad(cmd, e))?; + Ok(json!({"file_name": name, "bytes": size, "format": ext, "stl_fallback": fell_back, "uploading": true})) +} diff --git a/crates/engine/src/cmd/file_send.rs b/crates/engine/src/cmd/file_send.rs new file mode 100644 index 000000000..6f70b71cb --- /dev/null +++ b/crates/engine/src/cmd/file_send.rs @@ -0,0 +1,225 @@ +//! Sending a mesh to a program: the one pipeline behind `file.send_to_slicer` and the `slicer` +//! parameter of `file.save_mesh`. Write the file, find the target, start it and wait for it if its +//! rule says so, hand the file over, report. The two commands differ only in where the file goes: +//! `file.send_to_slicer` writes it into this user's slicer folder under a stable name, so sending +//! again replaces it; `file.save_mesh` writes it where the caller said. +//! +//! It takes a [`TargetKind`], and slicers are the only kind there is; a later Send to App would add +//! one (see `slicers::TargetKind`) and send through this same function. + +use serde_json::{Value, json}; +use solidcraft_io::Format; + +use super::easyprint::{Exported, export_bodies}; +use super::export_to; +use crate::params::bad; +use crate::slicers::{self, Slicer, TargetKind}; +use crate::{EngineError, Result, Session}; + +/// What to do when the target has to be started first. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Wait { + /// Start it, wait up to ten seconds for it to be ready, then send. + Block, + /// Start it and answer `starting`; the caller waits and sends. + Return, + /// Send now, started or not. + No, +} + +impl Wait { + pub(super) fn parse(s: Option<&str>) -> Option { + match s { + None | Some("block") => Some(Wait::Block), + Some("return") => Some(Wait::Return), + Some("no") => Some(Wait::No), + Some(_) => None, + } + } +} + +/// Where the file is written. +pub(super) enum Dest<'a> { + /// This user's slicer folder, under a name that stays the same for the same design and bodies. + Folder, + /// The path the caller gave. + Path(&'a str), +} + +pub(super) struct Send<'a> { + /// The command, for its error messages. + pub cmd: &'static str, + pub kind: TargetKind, + /// The target as the caller named it: an id, a name, or a program path. + pub spec: &'a str, + pub bodies: Vec, + pub format: Format, + /// Only for [`Dest::Path`]; the slicer folder's file is always standard. + pub quality: solidcraft_io::MeshQuality, + pub dest: Dest<'a>, + pub single_instance: bool, + pub wait: Wait, +} + +fn format_name(f: Format) -> &'static str { + match f { + Format::StlBinary | Format::StlAscii => "stl", + Format::ThreeMfTagged => "3mf-tagged", + _ => "3mf", + } +} + +/// Send the bodies to the target named by `r.spec`. +pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { + // The target is found before anything is written, so a name that matches nothing writes nothing. + let target = slicers::resolve_for(r.kind, r.spec).ok_or_else(|| { + bad(r.cmd, format!("no slicer `{}` (see file.slicers; a program works only once the user has added it under Custom…)", r.spec)) + })?; + if !target.target().accepts(format_name(r.format)) { + return Err(bad(r.cmd, format!("{} does not take {}", target.name, format_name(r.format)))); + } + let mut out = match r.dest { + Dest::Path(path) => export_to(s, path, r.format, &r.bodies, r.quality)?, + Dest::Folder => write_in_folder(s, &r)?, + }; + let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + deliver(&target, &path, r.single_instance, r.wait, &mut out); + Ok(out) +} + +/// Write the bodies into the slicer folder. +fn write_in_folder(s: &mut Session, r: &Send<'_>) -> Result { + use crate::slicer_files; + let Exported { bytes, ext, fell_back, bodies } = export_bodies(s, r.cmd, &r.bodies, r.format)?; + let dir = slicer_files::dir().ok_or_else(|| bad(r.cmd, "no per-user folder on this system"))?; + let stem = slicer_files::stem(&s.doc.name, s.path.as_deref(), s.uid, &bodies); + let (file, numbered) = slicer_files::write(&dir, &stem, ext, &bytes).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?; + Ok(json!({"path": file.to_string_lossy(), "bytes": bytes.len(), "format": ext, "numbered": numbered, "stl_fallback": fell_back})) +} + +/// Hand the file at `path` to `target`, starting it first if it has to be, and say what happened in +/// `out`: `slicer` when it went, `slicer_error` when the program would not start, `starting` (with +/// [`Wait::Return`]) or `slicer_timeout` when the target had to be started. +pub(super) fn deliver(target: &Slicer, path: &str, single_instance: bool, wait: Wait, out: &mut Value) { + deliver_via(target, path, single_instance, wait, &slicers::busctl_program(), slicers::READY_LIMIT, slicers::READY_POLL, out); +} + +#[allow(clippy::too_many_arguments)] +fn deliver_via( + target: &Slicer, + path: &str, + mut single_instance: bool, + wait: Wait, + busctl: &str, + limit: std::time::Duration, + poll: std::time::Duration, + out: &mut Value, +) { + let Some(obj) = out.as_object_mut() else { return }; + // A target that drops a file given at a cold start is started alone, and sent the file once it is ready. + if wait != Wait::No && target.waits_for_ready().is_some() && target.ready_via(busctl, slicers::PROBE_LIMIT) == Some(false) { + if let Err(e) = target.start(single_instance) { + obj.insert("slicer_error".into(), json!(e)); + return; + } + if wait == Wait::Return { + obj.insert("starting".into(), json!(target.name)); + return; + } + if !slicers::wait_for_ready_via(target, busctl, limit, poll) { + obj.insert("slicer_timeout".into(), json!(target.name)); + return; + } + // After a start the file has to reach the instance that is now running, so the flag goes + // on whatever `single_instance` says. + single_instance = true; + } + // The file is saved either way; a program that won't start is reported, not fatal. + match target.open(path, single_instance) { + Ok(()) => obj.insert("slicer".into(), json!(target.name)), + Err(e) => obj.insert("slicer_error".into(), json!(e)), + }; +} + +#[cfg(test)] +#[cfg(unix)] +mod tests { + use super::*; + use crate::slicers::test_support::fake_program; + use std::time::Duration; + + /// A "PrusaSlicer 3" whose launcher logs what it is started with, and a `busctl` that says the + /// slicer is not up for the first `cold` looks and is up after that. + fn setup(tag: &str, cold: u32) -> (std::path::PathBuf, Slicer, String) { + let root = std::env::temp_dir().join(format!("solidcraft-send-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let launcher_dir = root.join("slic3r-app-launcher"); + std::fs::create_dir_all(&launcher_dir).unwrap(); + let log = root.join("log"); + let launcher = fake_program(&launcher_dir, "PrusaSlicer", &format!("echo \"$@\" >> {}", log.display())); + let count = root.join("count"); + let busctl = fake_program( + &root, + "busctl", + &format!( + "n=$(cat {c} 2>/dev/null || echo 0); echo $((n+1)) > {c}; echo ':1.5 1 x'; [ $n -ge {cold} ] && echo 'com.prusa3d.prusaslicer.BroadcastListener.ab 2 y'; exit 0", + c = count.display() + ), + ); + let slicer = Slicer { id: "custom".into(), name: "PrusaSlicer".into(), command: vec![launcher], icon: None, prusa_major: None }; + (root, slicer, busctl) + } + + fn lines(root: &std::path::Path) -> Vec { + for _ in 0..100 { + if root.join("log").exists() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + std::thread::sleep(Duration::from_millis(100)); + std::fs::read_to_string(root.join("log")).map(|t| t.lines().map(String::from).collect()).unwrap_or_default() + } + + #[test] + fn a_cold_launcher_is_started_alone_waited_for_and_then_sent_the_file() { + let (root, slicer, busctl) = setup("cold", 2); + let mut out = json!({"path": "/t/part.3mf"}); + deliver_via(&slicer, "/t/part.3mf", false, Wait::Block, &busctl, Duration::from_secs(10), Duration::from_millis(20), &mut out); + assert_eq!(out["slicer"], "PrusaSlicer", "{out}"); + let log = lines(&root); + // Started with no file, then sent the file, both with the single-instance flag the preference could not take away. + assert_eq!(log, ["--single-instance", "--single-instance /t/part.3mf"]); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn a_launcher_that_is_up_is_sent_the_file_at_once_and_wait_no_does_not_look() { + let (root, slicer, busctl) = setup("warm", 0); + let mut out = json!({"path": "/t/part.3mf"}); + deliver_via(&slicer, "/t/part.3mf", true, Wait::Block, &busctl, Duration::from_secs(10), Duration::from_millis(20), &mut out); + assert_eq!(lines(&root), ["--single-instance /t/part.3mf"]); + let (root2, slicer2, busctl2) = setup("no", 99); + let mut out = json!({"path": "/t/part.3mf"}); + deliver_via(&slicer2, "/t/part.3mf", true, Wait::No, &busctl2, Duration::from_secs(10), Duration::from_millis(20), &mut out); + assert_eq!(lines(&root2), ["--single-instance /t/part.3mf"], "sent without a start"); + std::fs::remove_dir_all(root).unwrap(); + std::fs::remove_dir_all(root2).unwrap(); + } + + #[test] + fn return_starts_it_and_answers_and_a_launcher_that_never_comes_up_times_out_unsent() { + let (root, slicer, busctl) = setup("return", 99); + let mut out = json!({"path": "/t/part.3mf"}); + deliver_via(&slicer, "/t/part.3mf", true, Wait::Return, &busctl, Duration::from_secs(10), Duration::from_millis(20), &mut out); + assert_eq!(out["starting"], "PrusaSlicer"); + assert_eq!(lines(&root), ["--single-instance"], "started, no file"); + let mut out = json!({"path": "/t/part.3mf"}); + deliver_via(&slicer, "/t/part.3mf", true, Wait::Block, &busctl, Duration::from_millis(200), Duration::from_millis(20), &mut out); + assert_eq!(out["slicer_timeout"], "PrusaSlicer"); + assert!(out.get("slicer").is_none()); + let log = lines(&root); + assert!(log.iter().all(|l| !l.contains("part.3mf")), "{log:?}: the file was not sent"); + std::fs::remove_dir_all(root).unwrap(); + } +} diff --git a/crates/engine/src/easyprint.rs b/crates/engine/src/easyprint.rs new file mode 100644 index 000000000..57b627d92 --- /dev/null +++ b/crates/engine/src/easyprint.rs @@ -0,0 +1,116 @@ +//! What talking to EasyPrint (Printables' slicer in the browser) needs that doesn't touch a +//! network: the upload form, and the reading of its answer. The hosts do the HTTP themselves (the +//! desktop app with `ureq`, the browser build with `fetch`) and call these. `file.open_in_easyprint` +//! hands them the file. + +use serde_json::Value; + +/// Where a model is uploaded: `POST`, multipart, field `file`, `Accept: application/json`. +pub const IMPORT_URL: &str = "https://slicer.printables.com/import"; +/// The most EasyPrint takes in one upload (100 MB); a bigger file is refused before it is sent. +pub const MAX_BYTES: usize = 100_000_000; + +/// The file name to upload as: the design's name made safe, with the extension. +pub fn file_name(design: &str, ext: &str) -> String { + let stem: String = design.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_') { c } else { '_' }).take(80).collect(); + let stem = stem.trim(); + format!("{}.{ext}", if stem.is_empty() { "model" } else { stem }) +} + +/// The upload form: its `Content-Type` and the body, a `file` part holding `bytes` and a +/// `file_name` field. +pub fn multipart(file_name: &str, bytes: &[u8]) -> (String, Vec) { + let mut boundary = String::from("----solidcraft-easyprint-6b1f0d"); + while bytes.windows(boundary.len()).any(|w| w == boundary.as_bytes()) { + boundary.push('x'); + } + // A quote or a line break in the name would end the header early. + let name: String = file_name.chars().filter(|c| !matches!(c, '"' | '\r' | '\n' | '\\')).collect(); + let mut body = Vec::with_capacity(bytes.len() + 512); + body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"file_name\"\r\n\r\n{name}\r\n").as_bytes()); + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{name}\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + (format!("multipart/form-data; boundary={boundary}"), body) +} + +/// The address to open from EasyPrint's answer to an upload, or why there is none. +pub fn parse_import_response(status: u16, body: &[u8]) -> Result { + let json: Option = serde_json::from_slice(body).ok(); + if !(200..300).contains(&status) { + let code = json.as_ref().and_then(|j| j.get("error")).and_then(Value::as_str); + return Err(match code { + Some("file-too-large") => "EasyPrint says the file is too large (100 MB at most)".into(), + Some("invalid-extension") => "EasyPrint doesn't take this kind of file".into(), + Some("missing-file") => "EasyPrint got no file".into(), + Some(other) => format!("EasyPrint refused the upload ({})", other.chars().take(60).collect::()), + None => format!("EasyPrint answered HTTP {status}"), + }); + } + let url = json.as_ref().and_then(|j| j.get("easyprint_url")).and_then(Value::as_str).ok_or("EasyPrint's answer had no address to open")?; + // Only a Printables address is opened in the browser, whatever the server says. + let host = url.strip_prefix("https://").map(|rest| rest.split(['/', '?', '#']).next().unwrap_or_default()); + match host { + Some(h) if !h.contains(['@', ':']) && (h == "printables.com" || h.ends_with(".printables.com")) => Ok(url.to_string()), + _ => Err("EasyPrint's answer pointed somewhere other than Printables, so it was not opened".into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const OK: &str = + r#"{"easyprint_url":"https://www.printables.com/slice?file_url=x","file_url":"https://slicer.printables.com/a","file_name":"t.stl"}"#; + + #[test] + fn a_good_answer_gives_its_address() { + assert_eq!(parse_import_response(200, OK.as_bytes()).unwrap(), "https://www.printables.com/slice?file_url=x"); + } + + #[test] + fn errors_malformed_and_foreign_answers_give_no_address() { + let e = parse_import_response(413, br#"{"error":"file-too-large"}"#).unwrap_err(); + assert!(e.contains("too large"), "{e}"); + assert!(parse_import_response(500, b"").unwrap_err().contains("HTTP 500")); + assert!(parse_import_response(200, b"not json").is_err()); + assert!(parse_import_response(200, b"{}").is_err()); + assert!(parse_import_response(200, br#"{"easyprint_url":7}"#).is_err()); + for url in [ + "http://www.printables.com/x", + "https://evil.example/x", + "https://printables.com.evil.example/x", + "https://www.printables.com@evil.example/x", + "javascript:alert(1)", + ] { + let body = format!(r#"{{"easyprint_url":"{url}"}}"#); + assert!(parse_import_response(200, body.as_bytes()).is_err(), "{url}"); + } + } + + #[test] + fn the_form_holds_the_file_untouched_and_a_safe_name() { + let bytes: Vec = (0..=255).collect(); + let (content_type, body) = multipart("a\"b\r\nc.stl", &bytes); + let boundary = content_type.strip_prefix("multipart/form-data; boundary=").unwrap(); + let text = String::from_utf8_lossy(&body); + assert!(text.contains("filename=\"abc.stl\""), "{text}"); + assert!(body.windows(bytes.len()).any(|w| w == bytes.as_slice())); + assert!(text.ends_with(&format!("--{boundary}--\r\n"))); + // A file that happens to hold the usual boundary gets another one. + let (ct, _) = multipart("m.stl", b"x----solidcraft-easyprint-6b1f0dx"); + assert!(!ct.ends_with("6b1f0d")); + } + + #[test] + fn names_are_made_safe() { + assert_eq!(file_name("Bracket v2", "3mf"), "Bracket v2.3mf"); + assert_eq!(file_name("../../etc/x", "stl"), "______etc_x.stl"); + assert_eq!(file_name(" ", "stl"), "model.stl"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7cf4d4898..31d4a0b00 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ pub mod control_auth; pub mod control_pending; pub mod cosmetic_threads; pub mod crash; +pub mod easyprint; pub mod frames; pub mod fuzz; pub mod licences; @@ -26,6 +27,8 @@ pub mod recovery; pub mod render_jobs; pub mod sample; pub mod schema; +#[cfg(not(target_arch = "wasm32"))] +pub mod slicer_files; mod slicer_icon; pub mod slicers; pub mod snap; @@ -273,6 +276,9 @@ impl WorldCache { } } +/// Source of [`Session::uid`]. +static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + /// Commands evaluated in isolation, ready for an atomic handoff to their source session. pub struct ComputedCommands { source: Session, @@ -309,6 +315,10 @@ impl ComputedCommands { } /// An editing session on one design. +/// Starts an upload of a file (its name, its bytes) to EasyPrint and returns at once; the host +/// reports how it went and opens the answer itself. `Err`: it couldn't start. +pub type EasyPrintUpload = Arc) -> std::result::Result<(), String> + Send + Sync>; + pub struct Session { pub doc: Arc, pub model: Model, @@ -322,6 +332,10 @@ pub struct Session { pub feature_edit_sketch: Option, pub selection: Vec, pub path: Option, + /// Tells this document from every other one opened or started in this process: new for each + /// `Session::new` (so for each New, Open and Recover), the same for the life of the document. + /// Not saved. + pub uid: u64, /// `path`'s size and modification time when it was opened or last saved: a Save to it /// finding them changed would replace another program's or computer's work (#5467). pub disk: Option, @@ -346,6 +360,9 @@ pub struct Session { /// How calls that break a command's parameter contract are treated (off by default). It /// belongs to the session, not the design, so it survives opening and starting designs. pub param_check: schema::ParamCheck, + /// How the host uploads a model to EasyPrint (`file.open_in_easyprint`); `None`: it can't. It + /// belongs to the session like `param_check`, so it survives opening and starting designs. + pub easyprint_upload: Option, /// After a live frame: its sketch, the document it left and the revision. Its links were /// brought up to date by that frame, so the gesture's next frame needn't project them again /// while nothing else has run (#3222). @@ -532,6 +549,7 @@ impl Session { feature_edit_sketch: None, selection: Vec::new(), path: None, + uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), disk: None, read_only: false, open_preview: None, @@ -541,6 +559,7 @@ impl Session { followed: None, auto_project: true, param_check: schema::ParamCheck::Off, + easyprint_upload: None, live_links: None, active_component: 0, active_occurrence_path: None, @@ -584,6 +603,7 @@ impl Session { pub fn replace_design(&mut self, fresh: Session) { let auto_project = self.auto_project; let param_check = self.param_check; + let easyprint_upload = self.easyprint_upload.take(); let render_viewport = self.render_viewport.clone(); let render_jobs = self.render_jobs.scratch(); let checkpoints = std::mem::take(&mut self.checkpoints); @@ -596,6 +616,7 @@ impl Session { self.crash_journal = crash_journal; self.auto_project = auto_project; self.param_check = param_check; + self.easyprint_upload = easyprint_upload; self.render_viewport = render_viewport; self.render_jobs = render_jobs; self.checkpoints = checkpoints; @@ -1270,6 +1291,7 @@ impl Session { feature_edit_sketch: self.feature_edit_sketch, selection: self.selection.clone(), path: None, + uid: self.uid, disk: self.disk, read_only: self.read_only, open_preview: None, @@ -1280,6 +1302,7 @@ impl Session { followed: None, auto_project: self.auto_project, param_check: self.param_check, + easyprint_upload: self.easyprint_upload.clone(), live_links: None, active_component: self.active_component, active_occurrence_path: self.active_occurrence_path.clone(), diff --git a/crates/engine/src/slicer_files.rs b/crates/engine/src/slicer_files.rs new file mode 100644 index 000000000..872c8e7ef --- /dev/null +++ b/crates/engine/src/slicer_files.rs @@ -0,0 +1,178 @@ +//! The files sent to a slicer: a private per-user folder, a name that stays the same for the same +//! design and bodies (so sending again replaces the file and the slicer's "Reload from disk" +//! picks it up), writes that never leave half a file behind, and a sweep of old files. + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +/// How long a sent file is kept. +pub const KEEP: Duration = Duration::from_secs(7 * 24 * 3600); +/// Most numbered copies (`name-2.3mf`, …) tried when the file is locked. +const MAX_COPIES: u32 = 9; + +/// The per-user folder: `%LOCALAPPDATA%\SolidCraft\slicer`, `~/Library/Caches/SolidCraft/slicer` +/// or `$XDG_CACHE_HOME/solidcraft/slicer` (`~/.cache/solidcraft/slicer`). +pub fn dir() -> Option { + // Tests never touch the user's real folder. + if cfg!(test) { + return Some(solidcraft_io::vfs::temp_dir().join(format!("solidcraft-test-slicer-{}", std::process::id()))); + } + let env = |k: &str| std::env::var_os(k).filter(|d| !d.is_empty()).map(PathBuf::from); + let (root, name) = if cfg!(windows) { + (env("LOCALAPPDATA")?, "SolidCraft") + } else if cfg!(target_os = "macos") { + (env("HOME")?.join("Library/Caches"), "SolidCraft") + } else { + (env("XDG_CACHE_HOME").or_else(|| env("HOME").map(|h| h.join(".cache")))?, "solidcraft") + }; + Some(root.join(name).join("slicer")) +} + +/// Make `dir`, readable by its owner only (on Unix). +fn make_private(dir: &Path) -> io::Result<()> { + std::fs::create_dir_all(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) +} + +/// A file name (no extension) for `bodies` of a design: the design's name, then a hash of which +/// document it is and of the bodies, so two designs with the same name, or two selections of one +/// design, never share a file. A saved design is told apart by its path; one that was never saved +/// by this process and its `uid` (`Session::uid`), so two unsaved "Untitled" designs differ too. +/// At the first Save As the name changes to the path-based one: the slicer gets a new file once, +/// and the unsaved one is left to the seven-day sweep. +pub fn stem(design: &str, path: Option<&str>, uid: u64, bodies: &[String]) -> String { + let mut names: Vec<&str> = bodies.iter().map(String::as_str).collect(); + names.sort_unstable(); + // FNV-1a: the same on every release, unlike `DefaultHasher`. + let mut h: u64 = 0xcbf29ce484222325; + let unsaved = format!("unsaved:{}:{uid}", std::process::id()); + for part in std::iter::once(path.unwrap_or(&unsaved)).chain(names) { + for b in part.bytes().chain([0]) { + h = (h ^ u64::from(b)).wrapping_mul(0x100000001b3); + } + } + let name: String = design.chars().take(60).map(|c| if c.is_alphanumeric() || "-_ ".contains(c) { c } else { '_' }).collect(); + let name = name.trim(); + format!("{}-{:016x}", if name.is_empty() { "design" } else { name }, h) +} + +/// Write `bytes` as `.` in `dir`: to a temporary name first, then renamed over the +/// file, so the slicer never reads half a file. When the name can't be replaced (Windows keeps a +/// file the slicer has open locked) the next free `-2.`, … is used; the flag says so. +pub fn write(dir: &Path, stem: &str, ext: &str, bytes: &[u8]) -> io::Result<(PathBuf, bool)> { + make_private(dir)?; + let tmp = dir.join(format!(".{stem}.{ext}.{}.tmp", std::process::id())); + std::fs::write(&tmp, bytes)?; + let mut failure = None; + for n in 1..=MAX_COPIES { + let target = dir.join(if n == 1 { format!("{stem}.{ext}") } else { format!("{stem}-{n}.{ext}") }); + match std::fs::rename(&tmp, &target) { + Ok(()) => return Ok((target, n > 1)), + Err(e) => failure = Some(e), + } + } + let _ = std::fs::remove_file(&tmp); + Err(failure.unwrap_or_else(|| io::Error::other("no free file name"))) +} + +/// Delete the files in `dir` last changed before `now - keep`; how many went. +pub fn sweep(dir: &Path, now: SystemTime, keep: Duration) -> usize { + let Ok(entries) = std::fs::read_dir(dir) else { return 0 }; + let mut gone = 0; + for e in entries.flatten().take(5_000) { + let old = e + .metadata() + .ok() + .filter(|m| m.is_file()) + .and_then(|m| m.modified().ok()) + .is_some_and(|t| now.duration_since(t).is_ok_and(|age| age > keep)); + if old && std::fs::remove_file(e.path()).is_ok() { + gone += 1; + } + } + gone +} + +/// Delete the sent files older than [`KEEP`]. Run at startup, never right after a send. +pub fn clean_old() { + if let Some(dir) = dir() { + sweep(&dir, SystemTime::now(), KEEP); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("solidcraft-slicer-files-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d + } + + #[test] + fn the_name_is_stable_per_design_and_bodies() { + let a = |names: &[&str]| stem("Bracket", Some("/d/bracket.solidcraft"), 1, &names.iter().map(|s| s.to_string()).collect::>()); + assert_eq!(a(&["Arm", "Base"]), a(&["Base", "Arm"])); + assert_ne!(a(&["Arm", "Base"]), a(&["Arm"])); + assert_ne!(a(&["Arm"]), stem("Bracket", Some("/other/bracket.solidcraft"), 1, &["Arm".to_string()])); + assert!(a(&["Arm"]).starts_with("Bracket-")); + assert_eq!(stem("a/b:c", None, 1, &[]).split('-').next(), Some("a_b_c")); + assert!(stem("", None, 1, &[]).starts_with("design-")); + } + + #[test] + fn unsaved_designs_with_the_same_name_get_different_files() { + let bodies = ["Arm".to_string()]; + let (a, b) = (stem("Untitled", None, 1, &bodies), stem("Untitled", None, 2, &bodies)); + assert_ne!(a, b); + assert_eq!(a, stem("Untitled", None, 1, &bodies), "one document keeps one file"); + assert_eq!(a.len(), "Untitled-".len() + 16); + } + + #[test] + fn a_second_send_replaces_the_file_and_leaves_no_temporary_one() { + let dir = scratch("replace"); + let (first, numbered) = write(&dir, "part", "3mf", b"one").unwrap(); + let (second, numbered_again) = write(&dir, "part", "3mf", b"two").unwrap(); + assert_eq!((first.clone(), numbered, numbered_again), (second, false, false)); + assert_eq!(std::fs::read(&first).unwrap(), b"two"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_name_that_can_not_be_replaced_gets_a_numbered_copy() { + let dir = scratch("locked"); + // A folder in the way stands in for a file the slicer holds open. + std::fs::create_dir_all(dir.join("part.3mf/inside")).unwrap(); + let (path, numbered) = write(&dir, "part", "3mf", b"data").unwrap(); + assert!(numbered); + assert_eq!(path.file_name().unwrap(), "part-2.3mf"); + assert_eq!(std::fs::read(&path).unwrap(), b"data"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn only_old_files_are_swept() { + let dir = scratch("sweep"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.3mf"), b"x").unwrap(); + let now = SystemTime::now(); + assert_eq!(sweep(&dir, now, KEEP), 0); + assert_eq!(sweep(&dir, now + KEEP + Duration::from_secs(60), KEEP), 1); + assert!(!dir.join("a.3mf").exists()); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/engine/src/slicers.rs b/crates/engine/src/slicers.rs index 40b305073..b456a2719 100644 --- a/crates/engine/src/slicers.rs +++ b/crates/engine/src/slicers.rs @@ -3,7 +3,8 @@ //! application). //! //! Detection reads desktop entries and Flatpak exports (Linux), `.app` bundles (macOS) and the -//! program folders (Windows), plus `PATH` and the usual AppImage folders. Nothing here runs a +//! program folders (Windows), plus `PATH` and the usual AppImage folders. On Linux a desktop entry +//! that claims 3MF or STL files is listed too, even when it is not a slicer we know by name. Nothing here runs a //! program except [`Slicer::open`]. use std::path::{Path, PathBuf}; @@ -14,6 +15,9 @@ use crate::slicer_icon; const MAX_ENTRIES: usize = 5_000; /// Largest desktop entry read. const MAX_DESKTOP_BYTES: u64 = 64 * 1024; +/// The file types (`MimeType=`) that make a desktop entry a program to send a mesh to: 3MF (and +/// the name Windows software gave it) and STL. +const MESH_TYPES: &[&str] = &["model/3mf", "application/vnd.ms-3mfdocument", "model/stl", "application/sla"]; /// A slicer the user can send a mesh to. #[derive(Clone, Debug, PartialEq, Eq)] @@ -24,6 +28,10 @@ pub struct Slicer { /// The program and its leading arguments; the file to open is appended. pub command: Vec, pub icon: Option, + /// For PrusaSlicer, the major version of this install (`3` for `3.0.0-alpha10`), read from its + /// appstream metadata when it was detected (see [`prusa_major`]); `None` when that can't be read, + /// and for every other program. Never worked out by running the program. + pub prusa_major: Option, } /// Where an application's icon is read from. @@ -54,33 +62,135 @@ impl IconSource { } } -struct Known { - id: &'static str, - name: &'static str, - /// Names the application goes by, letters and digits only, lower case; an entry matches when - /// its name starts with one of them. - keys: &'static [&'static str], - /// Program file names. - exes: &'static [&'static str], +/// What a mesh can be sent to. `Slicer` is the only kind there is. It is the extension point for a +/// later Send to App: a new kind would name programs that are not slicers (a viewer, a CAM tool, a +/// converter), each with its own accepted formats and way of taking a file, and would send through +/// the same pipeline as `file.send_to_slicer` (write the file, find the target, start it and wait if +/// it needs that, hand the file over, report). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TargetKind { + Slicer, } -const KNOWN: &[Known] = &[ - Known { id: "prusa", name: "PrusaSlicer", keys: &["prusaslicer"], exes: &["prusa-slicer", "PrusaSlicer", "prusa-slicer.exe"] }, - Known { id: "bambu", name: "Bambu Studio", keys: &["bambustudio"], exes: &["bambu-studio", "BambuStudio", "bambu-studio.exe"] }, - Known { id: "orca", name: "OrcaSlicer", keys: &["orcaslicer"], exes: &["orca-slicer", "OrcaSlicer", "orca-slicer.exe"] }, - Known { +/// How a target takes the file it is sent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileArg { + /// As an argument at the end of its command, or inside the `@@ … @@` pair of a Flatpak command. + Argument, +} + +/// A program a mesh can be sent to, and what is known about how to do it. One row per known program; +/// a program that is not in the table (a desktop entry that claims 3MF or STL, one the user picked) is +/// a slicer with [`Target::SLICER`]'s defaults. +pub struct Target { + pub id: &'static str, + /// The label shown to the user. + pub name: &'static str, + pub kind: TargetKind, + /// Names the application goes by, letters and digits only, lower case; an entry matches when + /// its name starts with one of them. + pub keys: &'static [&'static str], + /// Program file names, how it is found and started when it has no desktop entry. + pub exes: &'static [&'static str], + /// The mesh formats it takes, as `file.send_to_slicer` names them, and the one used when none is asked for. + pub formats: &'static [&'static str], + pub default_format: &'static str, + pub file: FileArg, + /// The flag that makes a running instance take the file instead of a new one starting, if it has one. + pub single_instance: Option<&'static str>, + /// The first major version whose `--single-instance-on-url` hands a file over; in an older one the + /// flag is swapped for `single_instance`. + pub on_url_swap_below: Option, + /// When it has to be started alone and waited for before it can be sent a file. + pub ready: Option, +} + +impl Target { + /// The defaults of a slicer: every mesh format, a file as an argument, no flag, no wait. + pub const SLICER: Target = Target { + id: "", + name: "", + kind: TargetKind::Slicer, + keys: &[], + exes: &[], + formats: &["3mf", "stl", "3mf-tagged"], + default_format: "3mf", + file: FileArg::Argument, + single_instance: None, + on_url_swap_below: None, + ready: None, + }; + + pub fn accepts(&self, format: &str) -> bool { + self.formats.contains(&format) + } + + /// Whether the version of an install matters to how it is sent to, and so is read when it is found. + fn reads_version(&self) -> bool { + self.on_url_swap_below.is_some() || self.ready.is_some() + } +} + +/// The known programs, in the order they are listed. +const TARGETS: &[Target] = &[ + Target { + id: "prusa", + name: "PrusaSlicer", + keys: &["prusaslicer"], + exes: &["prusa-slicer", "PrusaSlicer", "prusa-slicer.exe"], + single_instance: Some("--single-instance"), + on_url_swap_below: Some(3), + ready: Some(PRUSA_READY), + ..Target::SLICER + }, + Target { + id: "bambu", + name: "Bambu Studio", + keys: &["bambustudio"], + exes: &["bambu-studio", "BambuStudio", "bambu-studio.exe"], + ..Target::SLICER + }, + Target { id: "orca", name: "OrcaSlicer", keys: &["orcaslicer"], exes: &["orca-slicer", "OrcaSlicer", "orca-slicer.exe"], ..Target::SLICER }, + Target { id: "cura", name: "UltiMaker Cura", keys: &["ultimakercura", "curaultimaker", "cura"], exes: &["cura", "UltiMaker-Cura", "UltiMaker-Cura.exe", "Cura.exe"], + single_instance: Some("--single-instance"), + ..Target::SLICER }, - Known { id: "superslicer", name: "SuperSlicer", keys: &["superslicer"], exes: &["superslicer", "SuperSlicer", "superslicer.exe"] }, - Known { id: "creality", name: "Creality Print", keys: &["crealityprint"], exes: &["CrealityPrint", "creality-print", "CrealityPrint.exe"] }, - Known { id: "elegoo", name: "ElegooSlicer", keys: &["elegooslicer"], exes: &["elegoo-slicer", "ElegooSlicer", "ElegooSlicer.exe"] }, - Known { id: "anycubic", name: "AnycubicSlicerNext", keys: &["anycubicslicer"], exes: &["AnycubicSlicerNext", "AnycubicSlicerNext.exe"] }, - Known { id: "ideamaker", name: "ideaMaker", keys: &["ideamaker"], exes: &["ideamaker", "ideaMaker.exe"] }, - Known { id: "lychee", name: "Lychee Slicer", keys: &["lycheeslicer"], exes: &["lychee-slicer", "Lychee Slicer.exe"] }, - Known { id: "slic3r", name: "Slic3r", keys: &["slic3r"], exes: &["slic3r", "Slic3r", "slic3r.exe"] }, + Target { + id: "superslicer", + name: "SuperSlicer", + keys: &["superslicer"], + exes: &["superslicer", "SuperSlicer", "superslicer.exe"], + single_instance: Some("--single-instance"), + ..Target::SLICER + }, + Target { + id: "creality", + name: "Creality Print", + keys: &["crealityprint"], + exes: &["CrealityPrint", "creality-print", "CrealityPrint.exe"], + ..Target::SLICER + }, + Target { + id: "elegoo", + name: "ElegooSlicer", + keys: &["elegooslicer"], + exes: &["elegoo-slicer", "ElegooSlicer", "ElegooSlicer.exe"], + ..Target::SLICER + }, + Target { + id: "anycubic", + name: "AnycubicSlicerNext", + keys: &["anycubicslicer"], + exes: &["AnycubicSlicerNext", "AnycubicSlicerNext.exe"], + ..Target::SLICER + }, + Target { id: "ideamaker", name: "ideaMaker", keys: &["ideamaker"], exes: &["ideamaker", "ideaMaker.exe"], ..Target::SLICER }, + Target { id: "lychee", name: "Lychee Slicer", keys: &["lycheeslicer"], exes: &["lychee-slicer", "Lychee Slicer.exe"], ..Target::SLICER }, + Target { id: "slic3r", name: "Slic3r", keys: &["slic3r"], exes: &["slic3r", "Slic3r", "slic3r.exe"], ..Target::SLICER }, ]; /// Lower-case letters and digits only: how names are compared. @@ -89,13 +199,13 @@ fn normalize(s: &str) -> String { } /// The known slicer an application name (or file name) belongs to. -fn known_for(name: &str) -> Option<&'static Known> { +fn known_for(name: &str) -> Option<&'static Target> { let n = normalize(name); // Companion tools (G-code viewers, command-line builds) are not slicers to send a mesh to. if n.contains("viewer") || n.contains("console") || n.contains("gcode") || n.contains("uninstall") { return None; } - KNOWN.iter().find(|k| k.keys.iter().any(|key| n.starts_with(key))) + TARGETS.iter().find(|k| k.keys.iter().any(|key| n.starts_with(key))) } /// Folders and variables detection looks at, so it can be tested without the real machine. @@ -113,6 +223,9 @@ pub struct Env { pub app_dirs: Vec, /// Folders holding one folder per installed program (Windows). pub install_dirs: Vec, + /// Flatpak installations (`~/.local/share/flatpak`, `/var/lib/flatpak`), where an app's + /// metadata says its version. + pub flatpak_roots: Vec, } impl Env { @@ -150,6 +263,8 @@ impl Env { env.program_dirs.extend(home.iter().map(|h| h.join(dir))); } env.program_dirs.extend(["/opt", "/usr/local/bin"].map(PathBuf::from)); + env.flatpak_roots.extend(home.iter().map(|h| h.join(".local/share/flatpak"))); + env.flatpak_roots.push("/var/lib/flatpak".into()); } env } @@ -157,15 +272,48 @@ impl Env { /// The slicers installed on this machine, known ones in a fixed order. Empty in the browser. pub fn detect() -> Vec { + #[cfg(test)] + if let Some(made_up) = TEST_DETECTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() { + return made_up; + } if cfg!(target_arch = "wasm32") { Vec::new() } else { detect_in(&Env::current()) } } -/// [`detect`] over the folders in `env`. +/// Tests of the commands set the slicers `detect` finds, and the `busctl` that is asked, to ones they made up. +#[cfg(test)] +pub(crate) static TEST_DETECTED: std::sync::Mutex>> = std::sync::Mutex::new(None); +#[cfg(test)] +pub(crate) static TEST_BUSCTL: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// The program that is asked what is on the session bus: `busctl`. +pub(crate) fn busctl_program() -> String { + #[cfg(test)] + if let Some(made_up) = TEST_BUSCTL.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() { + return made_up; + } + "busctl".to_string() +} + +/// [`detect`] over the folders in `env`. Every install of a slicer is listed: when there are +/// several of one, each gets its own id (`prusa#`, the same on every run) and a +/// name that says which it is (`PrusaSlicer (system)`, `PrusaSlicer (Flatpak, beta)`). pub fn detect_in(env: &Env) -> Vec { - let mut found: Vec = Vec::new(); - let mut add = |s: Slicer| { - if !found.iter().any(|f| f.id == s.id) { - found.push(s); + // (slicer, which program it starts, where it was found) + let mut found: Vec<(Slicer, String, PathBuf)> = Vec::new(); + let mut add = |s: Slicer, origin: &Path| { + let key = install_key(env, &s.command); + // The same program found twice (a desktop entry and PATH) is one install, and which of the + // places it was found in speaks for it must not depend on which was read first: the one + // that sorts first does, so its file name, and so the id, is the same on every run. + if let Some(at) = found.iter().position(|(_, k, _)| *k == key) { + if origin < found[at].2.as_path() { + found[at] = (s, key, origin.to_path_buf()); + } + return; + } + // An unknown program that a second desktop entry names the same is the one too. + if !found.iter().any(|(f, ..)| f.id == s.id && known_by_id(&s.id).is_none()) { + found.push((s, key, origin.to_path_buf())); } }; desktop_entries(env, &mut add); @@ -173,9 +321,171 @@ pub fn detect_in(env: &Env) -> Vec { program_folders(env, &mut add); mac_apps(env, &mut add); windows_programs(env, &mut add); - let order = |s: &Slicer| KNOWN.iter().position(|k| k.id == s.id).unwrap_or(usize::MAX); - found.sort_by_key(order); - found + // Told apart by their program, so the result does not depend on the order they were found in. + found.sort_by(|a, b| a.1.cmp(&b.1)); + let mut out: Vec = Vec::new(); + let mut labels: Vec = Vec::new(); + for (s, _, origin) in &found { + let several = found.iter().filter(|(o, ..)| o.id == s.id).count() > 1; + let mut slicer = s.clone(); + if slicer.target().reads_version() { + slicer.prusa_major = prusa_major(env, &slicer.command, origin); + } + if several { + let mut slug = install_slug(origin); + // Two versions of one AppImage side by side in a folder would have the same id: their file + // names, which differ, tell them apart, and only while there is more than one. + let side_by_side = |(o, _, og): &&(Slicer, String, PathBuf)| o.id == s.id && is_appimage(og) && og.parent() == origin.parent(); + if is_appimage(origin) && found.iter().filter(side_by_side).count() > 1 { + slug = format!("{slug}-{}", normalize(&origin.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())); + } + let mut id = format!("{}#{slug}", s.id); + let mut n = 2; + while out.iter().any(|o| o.id == id) { + id = format!("{}#{slug}-{n}", s.id); + n += 1; + } + let mut name = format!("{} ({})", s.name, install_label(env, &s.command, origin)); + let mut n = 2; + while labels.contains(&name) { + name = format!("{} ({} {n})", s.name, install_label(env, &s.command, origin)); + n += 1; + } + (slicer.id, slicer.name) = (id, name); + } + labels.push(slicer.name.clone()); + out.push(slicer); + } + let order = |s: &Slicer| (TARGETS.iter().position(|k| k.id == s.base_id()).unwrap_or(usize::MAX), s.name.to_lowercase(), s.id.clone()); + out.sort_by_key(order); + out +} + +/// The major version of an install of PrusaSlicer, from the release at the top of its appstream +/// metadata: for a Flatpak, in the app's own files (the branch the command names, else the current +/// one); for any other install found through a desktop entry, in the `metainfo` or `appdata` folder +/// beside that entry's `applications`. Read from files, never by running the program. `None` when +/// there is no such file or it has no release, in which case the entry's own command decides (see +/// `Slicer::waits_for_ready` and `Slicer::base_args`). +fn prusa_major(env: &Env, command: &[String], origin: &Path) -> Option { + let xml = if command.first().is_some_and(|c| file_name(Path::new(c)) == "flatpak") { + flatpak_metainfo(env, command)? + } else { + let stem = origin.file_stem()?.to_string_lossy().into_owned(); + let data = origin.parent()?.parent()?; + [data.join(format!("metainfo/{stem}.metainfo.xml")), data.join(format!("appdata/{stem}.appdata.xml"))].into_iter().find(|p| p.is_file())? + }; + if std::fs::metadata(&xml).ok()?.len() > 1 << 20 { + return None; + } + release_major(&std::fs::read_to_string(xml).ok()?) +} + +/// The metadata file of the Flatpak a `flatpak run …` command starts. +fn flatpak_metainfo(env: &Env, command: &[String]) -> Option { + let mut rest = command.iter().skip(1).skip_while(|a| *a != "run").skip(1); + let app = rest.find(|a| !a.starts_with('-'))?; + let branch = command.iter().find_map(|a| a.strip_prefix("--branch=")); + if app.is_empty() || app.contains('/') || branch.is_some_and(|b| b.contains('/')) { + return None; + } + for root in &env.flatpak_roots { + let app_dir = root.join("app").join(app); + // The branch the command names, under each architecture; else the one `current` points at. + let deployments: Vec = match branch { + Some(b) => entries(&app_dir).into_iter().filter(|p| p.is_dir() && file_name(p) != "current").map(|arch| arch.join(b)).collect(), + None => vec![app_dir.join("current")], + }; + for d in deployments { + let files = d.join("active/files/share"); + for rel in [format!("metainfo/{app}.metainfo.xml"), format!("appdata/{app}.appdata.xml")] { + if files.join(&rel).is_file() { + return Some(files.join(rel)); + } + } + } + } + None +} + +/// The leading number of the first ``: `3` for `3.0.0-alpha10`. +fn release_major(xml: &str) -> Option { + let release = &xml[xml.find(" bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case("appimage")) +} + +/// What tells this install's id apart from another install of the same slicer: the name of the file +/// it was found through (the desktop entry, the program), or for an AppImage the folder it is in. An +/// AppImage's file name carries its version, which changes with every upgrade and would make the +/// remembered choice miss; its folder, and the fact that it is an AppImage, do not. +fn install_slug(origin: &Path) -> String { + match origin.parent().filter(|_| is_appimage(origin)) { + Some(folder) => { + // FNV-1a: the same on every release, unlike `DefaultHasher`. + let hash = folder.to_string_lossy().bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100000001b3)); + format!("appimage-{:08x}", hash as u32) + } + None => normalize(&origin.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()), + } +} + +fn known_by_id(id: &str) -> Option<&'static Target> { + TARGETS.iter().find(|k| k.id == id.split('#').next().unwrap_or(id)) +} + +/// The program that `command` starts, as one string: a Flatpak or `open` command by itself, any +/// other by where its program really is (found through `PATH`, symlinks followed). +fn install_key(env: &Env, command: &[String]) -> String { + let Some(first) = command.first() else { return String::new() }; + let program = Path::new(first); + // `flatpak run …` and `/usr/bin/flatpak run …` are one invocation when they start the same + // launcher: it is found as any program is, and its name stands in where it can't be. + if file_name(program) == "flatpak" { + let launcher = which(env, program).map(|at| s(&std::fs::canonicalize(&at).unwrap_or(at))).unwrap_or_else(|| "flatpak".into()); + return std::iter::once(launcher.as_str()).chain(command[1..].iter().map(String::as_str)).collect::>().join("\u{0}"); + } + if first == "open" { + return command.join("\u{0}"); + } + let at = which(env, program).unwrap_or_else(|| program.to_path_buf()); + s(&std::fs::canonicalize(&at).unwrap_or(at)) +} + +/// A program name or path as an absolute path, looking through `PATH`. +fn which(env: &Env, program: &Path) -> Option { + if program.is_absolute() { + return Some(program.to_path_buf()); + } + (program.components().count() == 1).then(|| env.path_dirs.iter().map(|d| d.join(program)).find(|p| is_executable(p))).flatten() +} + +/// What tells this install from another of the same slicer, worked out from its command and where +/// it was found, without running anything. +fn install_label(env: &Env, command: &[String], origin: &Path) -> String { + if command.first().is_some_and(|c| file_name(Path::new(c)) == "flatpak") { + let branch = command.iter().find_map(|a| a.strip_prefix("--branch=")).filter(|b| *b != "stable"); + return branch.map_or_else(|| "Flatpak".to_string(), |b| format!("Flatpak, {b}")); + } + // `open -a ` starts `open`, wherever that is; the application is what tells installs apart. + let program = command.first().filter(|c| *c != "open").and_then(|c| which(env, Path::new(c))); + let at = program.as_deref().unwrap_or(origin); + if at.extension().is_some_and(|e| e.eq_ignore_ascii_case("appimage")) { + return "AppImage".into(); + } + let Some(rel) = env.home.as_deref().and_then(|h| at.strip_prefix(h).ok()) else { return "system".into() }; + if rel.starts_with(".local") { + return "user".into(); + } + match rel.parent().filter(|p| !p.as_os_str().is_empty()) { + Some(dir) => format!("~/{}", dir.display()), + None => "~".into(), + } } fn entries(dir: &Path) -> Vec { @@ -202,8 +512,8 @@ fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } -fn known_slicer(k: &Known, command: Vec, icon: Option) -> Slicer { - Slicer { id: k.id.into(), name: k.name.into(), command, icon } +fn known_slicer(k: &Target, command: Vec, icon: Option) -> Slicer { + Slicer { id: k.id.into(), name: k.name.into(), command, icon, prusa_major: None } } // --- Linux --- @@ -263,7 +573,7 @@ pub fn parse_exec(exec: &str) -> Vec { args } -fn desktop_entries(env: &Env, add: &mut impl FnMut(Slicer)) { +fn desktop_entries(env: &Env, add: &mut impl FnMut(Slicer, &Path)) { for data in &env.data_dirs { for file in entries(&data.join("applications")) { if file.extension().is_none_or(|e| e != "desktop") || std::fs::metadata(&file).map(|m| m.len() > MAX_DESKTOP_BYTES).unwrap_or(true) { @@ -271,8 +581,17 @@ fn desktop_entries(env: &Env, add: &mut impl FnMut(Slicer)) { } let Ok(text) = std::fs::read_to_string(&file) else { continue }; let entry = parse_desktop(&text); - let Some(known) = entry.get("Name").and_then(|n| known_for(n)) else { continue }; - if entry.get("Type").is_some_and(|t| t != "Application") { + let Some(name) = entry.get("Name") else { continue }; + let flag = |key: &str| entry.get(key).is_some_and(|v| v.eq_ignore_ascii_case("true")); + if entry.get("Type").is_some_and(|t| t != "Application") || flag("NoDisplay") || flag("Hidden") { + continue; + } + let known = known_for(name); + // A program we don't know by name counts when it says it opens 3MF or STL files. + let claims_meshes = + entry.get("MimeType").is_some_and(|m| m.split(';').any(|t| MESH_TYPES.iter().any(|w| t.trim().eq_ignore_ascii_case(w)))); + let ours = normalize(name).starts_with("solidcraft"); + if known.is_none() && (!claims_meshes || ours || flag("Terminal")) { continue; } let command = entry.get("Exec").map(|e| parse_exec(e)).unwrap_or_default(); @@ -282,7 +601,10 @@ fn desktop_entries(env: &Env, add: &mut impl FnMut(Slicer)) { continue; } let icon = entry.get("Icon").and_then(|i| theme_icon(env, i)); - add(known_slicer(known, command, icon)); + match known { + Some(k) => add(known_slicer(k, command, icon), &file), + None => add(Slicer { id: format!("desktop-{}", normalize(name)), name: name.clone(), command, icon, prusa_major: None }, &file), + } } } } @@ -313,14 +635,14 @@ fn theme_icon(env: &Env, name: &str) -> Option { None } -fn path_programs(env: &Env, add: &mut impl FnMut(Slicer)) { - for k in KNOWN { +fn path_programs(env: &Env, add: &mut impl FnMut(Slicer, &Path)) { + for k in TARGETS { for dir in &env.path_dirs { for exe in k.exes { let p = dir.join(exe); if is_executable(&p) { let icon = k.exes.iter().chain([&k.id]).find_map(|n| theme_icon(env, n.trim_end_matches(".exe"))); - add(known_slicer(k, vec![s(&p)], icon)); + add(known_slicer(k, vec![s(&p)], icon), &p); } } } @@ -328,7 +650,7 @@ fn path_programs(env: &Env, add: &mut impl FnMut(Slicer)) { } /// AppImages and per-slicer folders in the usual places. -fn program_folders(env: &Env, add: &mut impl FnMut(Slicer)) { +fn program_folders(env: &Env, add: &mut impl FnMut(Slicer, &Path)) { for dir in &env.program_dirs { for p in entries(dir) { let name = file_name(&p); @@ -337,10 +659,10 @@ fn program_folders(env: &Env, add: &mut impl FnMut(Slicer)) { let inside = known.exes.iter().flat_map(|e| [p.join(e), p.join("bin").join(e)]).find(|c| is_executable(c)); if let Some(exe) = inside { let icon = theme_icon(env, known.id); - add(known_slicer(known, vec![s(&exe)], icon)); + add(known_slicer(known, vec![s(&exe)], icon), &exe); } } else if name.to_ascii_lowercase().ends_with(".appimage") && is_executable(&p) { - add(known_slicer(known, vec![s(&p)], None)); + add(known_slicer(known, vec![s(&p)], None), &p); } } } @@ -348,13 +670,13 @@ fn program_folders(env: &Env, add: &mut impl FnMut(Slicer)) { // --- macOS --- -fn mac_apps(env: &Env, add: &mut impl FnMut(Slicer)) { +fn mac_apps(env: &Env, add: &mut impl FnMut(Slicer, &Path)) { for dir in &env.app_dirs { for app in entries(dir) { let name = file_name(&app); let Some(stem) = name.strip_suffix(".app") else { continue }; let Some(known) = known_for(stem) else { continue }; - add(known_slicer(known, vec!["open".into(), "-a".into(), s(&app)], mac_icon(&app))); + add(known_slicer(known, vec!["open".into(), "-a".into(), s(&app)], mac_icon(&app)), &app); } } } @@ -369,13 +691,18 @@ fn mac_icon(app: &Path) -> Option { // --- Windows --- -fn windows_programs(env: &Env, add: &mut impl FnMut(Slicer)) { +fn windows_programs(env: &Env, add: &mut impl FnMut(Slicer, &Path)) { for root in &env.install_dirs { - for dir in entries(root).into_iter().filter(|p| p.is_dir()) { + let mut dirs: Vec = entries(root).into_iter().filter(|p| p.is_dir()).collect(); + // PrusaSlicer installs one level down, in `Prusa3D\PrusaSlicer`. + let nested: Vec = + dirs.iter().filter(|d| normalize(&file_name(d)) == "prusa3d").flat_map(|d| entries(d)).filter(|p| p.is_dir()).collect(); + dirs.extend(nested); + for dir in dirs { let Some(known) = known_for(&file_name(&dir)) else { continue }; let exe = known.exes.iter().filter(|e| e.ends_with(".exe")).flat_map(|e| [dir.join(e), dir.join("bin").join(e)]).find(|c| c.is_file()); if let Some(exe) = exe { - add(known_slicer(known, vec![s(&exe)], Some(IconSource::Exe(exe.clone())))); + add(known_slicer(known, vec![s(&exe)], Some(IconSource::Exe(exe.clone()))), &exe); } } } @@ -412,18 +739,64 @@ pub fn custom(path: &str) -> Option { let stem = p.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); (vec![path.to_string()], theme_icon(&Env::current(), &stem)) }; - Some(Slicer { id: "custom".into(), name, command, icon }) + Some(Slicer { id: "custom".into(), name, command, icon, prusa_major: None }) } -/// A slicer from a command parameter: the id or name of an installed one, else a program path. +/// The programs the user picked under Custom…, set by the application. Commands may start these +/// and the detected slicers, and nothing else. +static CHOSEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Tell the commands which programs the user has chosen (the application keeps them in its settings). +pub fn set_chosen_programs(paths: &[String]) { + *CHOSEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = paths.to_vec(); +} + +/// A slicer from a command parameter: the id or name of a detected one, the path of a detected +/// one's program, or a program the user chose (by its path or name). Any other program path is +/// refused: scripts and agents reach this through `file.save_mesh` and `file.send_to_slicer`, and +/// must not run arbitrary programs. pub fn resolve(spec: &str) -> Option { + resolve_for(TargetKind::Slicer, spec) +} + +/// [`resolve`] among the targets of one kind. +pub fn resolve_for(kind: TargetKind, spec: &str) -> Option { + let chosen = CHOSEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + resolve_in(detect_for(kind), &chosen, spec) +} + +/// The installed targets of one kind, in the order they are listed. Empty in the browser. +pub fn detect_for(kind: TargetKind) -> Vec { + detect().into_iter().filter(|s| s.target().kind == kind).collect() +} + +/// Whether `spec` names the program that `command` starts: the same text, or the same file. +fn same_program(command: &str, spec: &str) -> bool { + command == spec + || (Path::new(spec).is_absolute() + && std::fs::canonicalize(command).ok().is_some_and(|c| std::fs::canonicalize(spec).ok().is_some_and(|s| c == s))) +} + +fn resolve_in(detected: Vec, chosen: &[String], spec: &str) -> Option { let wanted = normalize(spec); + let named = |s: &Slicer| normalize(&s.name) == wanted; + // An exact id or name first; else the slicer without saying which install: the first one. + let plain = |d: &Slicer| normalize(d.base_id()) == wanted || known_by_id(d.base_id()).is_some_and(|k| normalize(k.name) == wanted); if !wanted.is_empty() - && let Some(found) = detect().into_iter().find(|d| normalize(&d.id) == wanted || normalize(&d.name) == wanted) + && let Some(i) = detected.iter().position(|d| normalize(&d.id) == wanted || named(d)).or_else(|| detected.iter().position(plain)) { - return Some(found); + return detected.into_iter().nth(i); } - custom(spec) + // The path of a detected slicer's program, as `file.slicers` lists it (an AppImage, a program + // on `PATH`): that slicer, with its own command and arguments. Only when it is the program of + // exactly one: a launcher several entries share (`/usr/bin/flatpak`) says nothing about which of + // them is meant, and is not taken for the first. It goes on to the user's own programs instead. + let by_path: Vec = (0..detected.len()).filter(|&i| detected[i].command.first().is_some_and(|c| same_program(c, spec))).collect(); + if let [only] = by_path.as_slice() { + return detected.into_iter().nth(*only); + } + let picked = chosen.iter().filter_map(|p| custom(p).map(|s| (p, s))); + picked.into_iter().find(|(p, s)| p.as_str() == spec || (!wanted.is_empty() && named(s))).map(|(_, s)| s) } /// `args` with the file added: at the end, or inside the `@@ … @@` pair of a Flatpak command, which @@ -440,31 +813,318 @@ fn with_file(args: &[String], path: &str) -> Vec { } impl Slicer { - /// Start the slicer with `path` loaded; does not wait for it to exit. - pub fn open(&self, path: &str) -> std::result::Result<(), String> { + /// The id without the `#` that tells installs of one slicer apart: `prusa` for + /// `prusa#comprusa3dprusaslicer`. + pub fn base_id(&self) -> &str { + self.id.split('#').next().unwrap_or(&self.id) + } + + /// The arguments after the program: the command's own, the single-instance flag when asked for + /// and this slicer has one, and the file. A desktop entry that already carries a + /// `--single-instance…` flag is never given a second one, and loses its own when + /// `single_instance` is off. PrusaSlicer 3.0's launcher has `--single-instance-on-url`, which + /// hands the file to a running instance, and keeps it. PrusaSlicer 2.9's Flatpak entry has the + /// same flag, but there it does not hand a file over (each send opened a new window); only + /// `--single-instance` does, so on a slicer that is not on the wait table it is swapped. + /// + /// A slicer on the wait table (the 3.0 launcher) gets the flag whatever `single_instance` says: + /// it can't hand a file to a running instance without it (a send with no flag left a launcher + /// process that never forwarded, and a start with a file and no flag loaded nothing). + #[cfg(not(target_arch = "wasm32"))] + fn args(&self, path: &str, single_instance: bool) -> Vec { + let single_instance = single_instance || self.waits_for_ready().is_some(); + with_file(&self.base_args(single_instance), path) + } + + /// [`Self::args`] without a file, for starting the slicer on its own: a Flatpak command's file + /// markers go too. A slicer that has to be started first (`Target::ready`) is always started + /// with the single-instance flag, whatever the preference says: a start that finds one already + /// running (a slow first look at the bus can start it twice) hands over to it and exits, where + /// without the flag it would open a second window. + #[cfg(not(target_arch = "wasm32"))] + fn start_args(&self, single_instance: bool) -> Vec { + let single_instance = single_instance || self.waits_for_ready().is_some(); + self.base_args(single_instance).into_iter().filter(|a| a != "@@" && a != "@@u").collect() + } + + /// The row of the target table this is, or the slicer defaults for a program that has none. + pub fn target(&self) -> &'static Target { + TARGETS.iter().find(|t| t.id == self.kind()).unwrap_or(&Target::SLICER) + } + + /// Which known slicer this is, by identity: its id without the install part, or for a program + /// the user picked, the one its name says (as for its icon). Empty for any other program. + fn kind(&self) -> &str { + if self.id == "custom" { known_for(&self.name).map_or("", |k| k.id) } else { self.base_id() } + } + + #[cfg(not(target_arch = "wasm32"))] + fn base_args(&self, single_instance: bool) -> Vec { + let mut args: Vec = self.command.iter().skip(1).cloned().collect(); + let has = |args: &[String]| args.iter().any(|a| a.starts_with("--single-instance")); + if !single_instance { + args.retain(|a| !a.starts_with("--single-instance")); + } else if self.url_flag_swaps() && args.iter().any(|a| a == "--single-instance-on-url") { + // PrusaSlicer 2 only (by its version, when that could be read): its `-on-url` does not hand + // a file over, and `--single-instance` does. Another program that happens to have the flag + // keeps its own meaning for it, and so does an entry whose version is unknown. + for a in args.iter_mut().filter(|a| *a == "--single-instance-on-url") { + *a = "--single-instance".into(); + } + } else if let Some(flag) = self.target().single_instance.filter(|_| self.command.first().is_some_and(|p| p != "open") && !has(&args)) { + // Before a Flatpak command's file markers, which close the application's own arguments. + let at = args.iter().position(|a| a == "@@" || a == "@@u").unwrap_or(args.len()); + args.insert(at, flag.into()); + } + args + } + + /// Start the slicer with `path` loaded; does not wait for it to exit. With `single_instance`, + /// a slicer that supports it loads the file in the window that is already open. + pub fn open(&self, path: &str, single_instance: bool) -> std::result::Result<(), String> { #[cfg(target_arch = "wasm32")] { - let _ = path; + let _ = (path, single_instance); Err(format!("{} can't be started from the browser", self.name)) } #[cfg(not(target_arch = "wasm32"))] { - use std::process::{Command, Stdio}; - let (program, args) = self.command.split_first().ok_or_else(|| format!("{} has no program to start", self.name))?; - Command::new(program) - .args(with_file(args, path)) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .map(drop) - .map_err(|e| format!("couldn't start {} ({e}); the file is saved at {path}", self.name)) + self.spawn(self.args(path, single_instance)).map_err(|e| format!("couldn't start {} ({e}); the file is saved at {path}", self.name)) } } + + #[cfg(not(target_arch = "wasm32"))] + fn spawn(&self, args: Vec) -> std::io::Result<()> { + use std::process::{Command, Stdio}; + let program = self.command.first().ok_or_else(|| std::io::Error::other("no program to start"))?; + Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().map(drop) + } + + /// Start the slicer on its own, with no file. Does not wait for it to exit or to be ready. + pub fn start(&self, single_instance: bool) -> std::result::Result<(), String> { + #[cfg(target_arch = "wasm32")] + { + let _ = single_instance; + Err(format!("{} can't be started from the browser", self.name)) + } + #[cfg(not(target_arch = "wasm32"))] + { + self.spawn(self.start_args(single_instance)).map_err(|e| format!("couldn't start {} ({e})", self.name)) + } + } + + /// Whether this slicer drops a file given at a cold start and so has to be started first and + /// sent the file once it can take one (see `Target::ready`). That is PrusaSlicer 3 or newer + /// (`prusa_major`), which starts through its launcher; PrusaSlicer 2 loads the file at launch, + /// whatever its command is. Where the version could not be read, and for a program that is not + /// in the table with such a rule, the launcher's name in the command decides. + pub fn waits_for_ready(&self) -> Option<&'static WaitRule> { + let by_name = || TARGETS.iter().filter_map(|t| t.ready.as_ref()).find(|r| self.command.iter().any(|a| a.contains(r.command_has))); + match (self.target().ready.as_ref(), self.prusa_major) { + (Some(rule), Some(m)) if m < rule.min_major => None, + (Some(rule), Some(_)) => Some(rule), + _ => by_name(), + } + } + + /// Whether this is a PrusaSlicer old enough that its `--single-instance-on-url` does not hand a + /// file over, by the version read when it was detected. + fn url_flag_swaps(&self) -> bool { + self.target().on_url_swap_below.is_some_and(|below| self.prusa_major.is_some_and(|v| v < below)) + } + + /// Whether the slicer can take a file now: `Some(true)` or `Some(false)`, or `None` when that + /// can't be told (no `busctl`, or it failed), in which case nobody waits. A `busctl` that is + /// only slow is `Some(false)`: nothing says it is up yet. + pub fn is_ready(&self) -> Option { + self.is_ready_within(PROBE_LIMIT) + } + + /// [`Self::is_ready`], giving `busctl` at most `limit` to answer. + pub fn is_ready_within(&self, limit: std::time::Duration) -> Option { + self.ready_via(&busctl_program(), limit) + } + + pub(crate) fn ready_via(&self, busctl: &str, limit: std::time::Duration) -> Option { + let rule = self.waits_for_ready()?; + match bus_list(busctl, limit) { + Bus::Names(list) => Some(has_bus_name(&list, rule.bus_prefix)), + Bus::Slow => Some(false), + Bus::Unknown => None, + } + } +} + +/// A rule for a program that ignores a file given at a cold start: how it is found by its command, +/// and the sign that it is up and can take one. +pub struct WaitRule { + /// Part of an argument of the command. + pub command_has: &'static str, + /// A name on the session bus that exists while the slicer is ready. Its end changes with the + /// install, so only its start is matched. + pub bus_prefix: &'static str, + /// The first major version that needs this (older ones load the file at launch). + pub min_major: u32, +} + +/// PrusaSlicer 3.0's launcher ignores the file on a cold start whatever the flag, and loads it +/// over D-Bus when an instance is running. PrusaSlicer 2.9 and OrcaSlicer load it at launch, so +/// they have no such rule. +pub const PRUSA_READY: WaitRule = + WaitRule { command_has: "slic3r-app-launcher", bus_prefix: "com.prusa3d.prusaslicer.BroadcastListener.", min_major: 3 }; + +/// Longest wait for a started slicer to be ready, and how often it is looked at. +pub const READY_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); +pub const READY_POLL: std::time::Duration = std::time::Duration::from_millis(200); + +/// The longest one look at the session bus may take. +pub const PROBE_LIMIT: std::time::Duration = std::time::Duration::from_secs(2); + +/// What one look at the session bus came to. +#[derive(Debug, PartialEq, Eq)] +enum Bus { + /// The names, one line each. + Names(String), + /// `busctl` did not answer in time: nothing is known yet, which is not the same as "not up". + Slow, + /// `busctl` is missing, failed, or this is not a system that has it: it can't be told. + Unknown, +} + +/// The session bus's names, as `busctl --user --no-legend --no-pager list` (`program` is +/// `busctl`) prints them, or why they could not be had. +fn bus_list(program: &str, limit: std::time::Duration) -> Bus { + #[cfg(any(target_arch = "wasm32", not(unix)))] + { + let _ = (program, limit); + Bus::Unknown + } + #[cfg(all(unix, not(target_arch = "wasm32")))] + { + use std::io::Read; + use std::process::Stdio; + let Ok(mut child) = std::process::Command::new(program) + .args(["--user", "--no-legend", "--no-pager", "list"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + else { + return Bus::Unknown; + }; + let end = std::time::Instant::now() + limit; + let left = || end.saturating_duration_since(std::time::Instant::now()); + // Read on another thread so a long list can't fill the pipe while this one waits, and hand + // the text back over a channel so that waiting for it has the same deadline: a process + // the program left running may keep the pipe open long after the program is gone. + // The reader is left to end when the pipe closes, not waited for. A busctl that answered but + // left a process holding its stdout reads as Slow, and each poll of such a bus can leave one + // blocked reader behind until that process lets go. + let Some(mut stdout) = child.stdout.take() else { return Bus::Unknown }; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut text = String::new(); + let _ = tx.send(stdout.read_to_string(&mut text).ok().map(|_| text)); + }); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if !left().is_zero() => std::thread::sleep(std::time::Duration::from_millis(10).min(left())), + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Bus::Slow; + } + Err(_) => return Bus::Unknown, + } + }; + // A reader that is still waiting when this gives up ends when the pipe closes. + match rx.recv_timeout(left()) { + Ok(Some(text)) if status.success() => Bus::Names(text), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Bus::Slow, + _ => Bus::Unknown, + } + } +} + +/// The first column of each line: the bus names. +fn bus_names(list: &str) -> impl Iterator { + list.lines().filter_map(|l| l.split_whitespace().next()) +} + +/// Whether the list has a name that starts with `prefix`. +fn has_bus_name(list: &str, prefix: &str) -> bool { + bus_names(list).any(|n| n.starts_with(prefix)) +} + +/// Look every `poll` until `ready` says so; false when `limit` runs out first. `ready` is asked at +/// once, so a slicer that is already up costs no sleep, and is given the time that is left, so a +/// probe that can block (`busctl`) can be cut short. +/// +/// No probe is started after the limit has passed. A probe that is already running when it passes +/// may finish, and a yes from it is accepted on purpose: the file should still go. So the wait takes +/// `limit` plus at most that last probe's own time. The production probe is given the time left, +/// which is a polling and read budget, not a wall-clock promise: its clock starts after the process +/// is spawned, and killing and reaping it, and scheduling, take time of their own. +pub fn wait_until(mut ready: impl FnMut(std::time::Duration) -> bool, limit: std::time::Duration, poll: std::time::Duration) -> bool { + let end = std::time::Instant::now() + limit; + let mut first = true; + loop { + let left = end.saturating_duration_since(std::time::Instant::now()); + if !first && left.is_zero() { + return false; + } + first = false; + if ready(left) { + return true; + } + std::thread::sleep(poll.min(end.saturating_duration_since(std::time::Instant::now()))); + } +} + +/// Wait for `slicer` to be ready to take a file. True when it is, or when that can't be told; false +/// when the limit passes first, a slow `busctl` included. +pub fn wait_for_ready(slicer: &Slicer) -> bool { + wait_for_ready_via(slicer, &busctl_program(), READY_LIMIT, READY_POLL) +} + +pub(crate) fn wait_for_ready_via(slicer: &Slicer, busctl: &str, limit: std::time::Duration, poll: std::time::Duration) -> bool { + // On purpose: if busctl is missing, or fails partway through, stop waiting and send; a file sent + // too early is dropped quietly and costs one re-send. A busctl that is only slow is not that: + // it keeps the wait going to the limit. + wait_until(|left| slicer.ready_via(busctl, left.min(PROBE_LIMIT)) != Some(false), limit, poll) +} + +/// What tests of this module and of the send pipeline share. +#[cfg(test)] +#[cfg(unix)] +pub(crate) mod test_support { + use std::path::Path; + + /// A small shell script that can be run. One that was only just written can fail to start (text + /// file busy) while another test forks, which would read as a `busctl` that is missing; so it is + /// started once here, patiently, with a flag the script answers at once, before a test relies + /// on it. + pub(crate) fn fake_program(root: &Path, name: &str, body: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let p = root.join(name); + std::fs::write(&p, format!("#!/bin/sh\n[ \"$1\" = --warm-up ] && exit 0\n{body}\n")).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + for _ in 0..200 { + use std::process::Stdio; + match std::process::Command::new(&p).arg("--warm-up").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status() { + Err(e) if e.raw_os_error() == Some(26) => std::thread::sleep(std::time::Duration::from_millis(20)), + _ => break, + } + } + p.to_string_lossy().into_owned() + } } #[cfg(test)] mod tests { + #[cfg(unix)] + use super::test_support::fake_program; use super::*; fn scratch(tag: &str) -> PathBuf { @@ -525,6 +1185,78 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn programs_that_claim_3mf_or_stl_are_candidates_too() { + let root = scratch("mime"); + let data = root.join("share"); + std::fs::create_dir_all(data.join("applications")).unwrap(); + let entry = |file: &str, body: &str| { + std::fs::write(data.join("applications").join(file), format!("[Desktop Entry]\nType=Application\n{body}\n")).unwrap() + }; + entry("fancy.desktop", "Name=Fancy Slicer\nExec=fancy %f\nMimeType=text/plain;MODEL/3MF;"); + entry("viewer.desktop", "Name=Mesh Viewer\nExec=meshview --open %F\nMimeType=image/png;application/sla;"); + // Known by name: the table still gives the name and id, and the file type is not needed. + entry("prusa.desktop", "Name=PrusaSlicer\nExec=prusa-slicer %F"); + entry("hidden.desktop", "Name=Hidden Slicer\nExec=h\nMimeType=model/stl;\nNoDisplay=true"); + entry("gone.desktop", "Name=Gone Slicer\nExec=g\nMimeType=model/stl;\nHidden=true"); + entry("terminal.desktop", "Name=Console Mesher\nExec=cm\nMimeType=model/stl;\nTerminal=true"); + entry("noclaim.desktop", "Name=Text Editor\nExec=edit %f\nMimeType=text/plain;application/vnd.ms-3mfdocumentation;"); + entry("hiddenprusa.desktop", "Name=PrusaSlicer Beta\nExec=prusa-beta\nNoDisplay=true"); + entry("ours.desktop", "Name=SolidCraft\nExec=solidcraft %f\nMimeType=model/3mf;model/stl;"); + entry("alias.desktop", "Name=Windows Mesher\nExec=wm\nMimeType=application/vnd.ms-3mfdocument;"); + let found = detect_in(&Env { data_dirs: vec![data], ..Env::default() }); + let listed: Vec<(&str, &str)> = found.iter().map(|f| (f.id.as_str(), f.name.as_str())).collect(); + assert_eq!( + listed, + [ + ("prusa", "PrusaSlicer"), + ("desktop-fancyslicer", "Fancy Slicer"), + ("desktop-meshviewer", "Mesh Viewer"), + ("desktop-windowsmesher", "Windows Mesher") + ] + ); + assert_eq!(found[1].command, ["fancy"]); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn a_program_path_that_several_entries_share_is_refused_and_a_single_one_runs_its_whole_command() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("shared-path"); + let flatpak = root.join("bin/flatpak"); + std::fs::create_dir_all(flatpak.parent().unwrap()).unwrap(); + std::fs::write(&flatpak, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&flatpak, std::fs::Permissions::from_mode(0o755)).unwrap(); + let share = root.join("share"); + std::fs::create_dir_all(share.join("applications")).unwrap(); + for (file, name, branch) in [("a.desktop", "PrusaSlicer", "stable"), ("b.desktop", "OrcaSlicer", "master")] { + let exec = format!("{} run --branch={branch} com.example.{name} @@u %U @@", flatpak.display()); + std::fs::write(share.join("applications").join(file), format!("[Desktop Entry]\nType=Application\nName={name}\nExec={exec}\n")).unwrap(); + } + // And an AppImage that is the program of one entry only. + let apps = root.join("Apps"); + let image = apps.join("SuperSlicer.AppImage"); + std::fs::create_dir_all(&apps).unwrap(); + std::fs::write(&image, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&image, std::fs::Permissions::from_mode(0o755)).unwrap(); + let found = detect_in(&Env { data_dirs: vec![share], program_dirs: vec![apps], ..Env::default() }); + assert_eq!(found.len(), 3, "{found:?}"); + // Two detected Flatpak entries start the same launcher: the path alone does not say which. + assert_eq!(resolve_in(found.clone(), &[], flatpak.to_str().unwrap()), None); + // Each is still reachable by its own id or name, with its full command. + let by_id = resolve_in(found.clone(), &[], "orca").unwrap(); + assert_eq!(by_id.command.first().map(String::as_str), flatpak.to_str()); + assert!(by_id.command.contains(&"--branch=master".to_string())); + // The one entry whose program the path is runs its whole command. + let by_path = resolve_in(found.clone(), &[], image.to_str().unwrap()).unwrap(); + assert_eq!(by_path.command, found.iter().find(|s| s.base_id() == "superslicer").unwrap().command); + // A path the user chose under Custom… is the user's own decision, whatever else shares it. + let chosen = [flatpak.to_str().unwrap().to_string()]; + assert_eq!(resolve_in(found, &chosen, flatpak.to_str().unwrap()).map(|s| s.id), Some("custom".into())); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn finds_mac_bundles_and_windows_folders() { let root = scratch("mac-win"); @@ -533,15 +1265,17 @@ mod tests { std::fs::write(apps.join("BambuStudio.app/Contents/Resources/BambuStudio.icns"), b"x").unwrap(); std::fs::create_dir_all(apps.join("Safari.app")).unwrap(); let prog = root.join("Program Files"); - std::fs::create_dir_all(prog.join("Prusa3D")).unwrap(); + std::fs::create_dir_all(prog.join("Prusa3D/PrusaSlicer")).unwrap(); + std::fs::write(prog.join("Prusa3D/PrusaSlicer/prusa-slicer.exe"), b"x").unwrap(); std::fs::create_dir_all(prog.join("OrcaSlicer")).unwrap(); std::fs::write(prog.join("OrcaSlicer/orca-slicer.exe"), b"x").unwrap(); let found = detect_in(&Env { app_dirs: vec![apps.clone()], install_dirs: vec![prog.clone()], ..Env::default() }); let ids: Vec<&str> = found.iter().map(|f| f.id.as_str()).collect(); - assert_eq!(ids, ["bambu", "orca"]); - assert_eq!(found[0].command, ["open", "-a", apps.join("BambuStudio.app").to_str().unwrap()]); - assert!(matches!(found[0].icon, Some(IconSource::Icns(_)))); - assert_eq!(found[1].icon, Some(IconSource::Exe(prog.join("OrcaSlicer/orca-slicer.exe")))); + assert_eq!(ids, ["prusa", "bambu", "orca"]); + assert_eq!(found[0].icon, Some(IconSource::Exe(prog.join("Prusa3D/PrusaSlicer/prusa-slicer.exe")))); + assert_eq!(found[1].command, ["open", "-a", apps.join("BambuStudio.app").to_str().unwrap()]); + assert!(matches!(found[1].icon, Some(IconSource::Icns(_)))); + assert_eq!(found[2].icon, Some(IconSource::Exe(prog.join("OrcaSlicer/orca-slicer.exe")))); std::fs::remove_dir_all(root).unwrap(); } @@ -573,4 +1307,654 @@ mod tests { assert!(custom(root.to_str().unwrap()).is_none()); std::fs::remove_dir_all(root).unwrap(); } + + #[test] + fn single_instance_is_asked_of_the_slicers_that_have_it() { + let slicer = |id: &str, name: &str, command: &[&str]| Slicer { + id: id.into(), + name: name.into(), + command: command.iter().map(|s| s.to_string()).collect(), + icon: None, + prusa_major: None, + }; + let args = |s: &Slicer, single| s.args("/t/a.3mf", single); + for (id, name) in [("prusa", "PrusaSlicer"), ("superslicer", "SuperSlicer"), ("cura", "UltiMaker Cura")] { + let s = slicer(id, name, &["/x/prog"]); + assert_eq!(args(&s, true), ["--single-instance", "/t/a.3mf"], "{id}"); + assert_eq!(args(&s, false), ["/t/a.3mf"], "{id}"); + } + // Bambu Studio is not given the flag, also when the user picked it as a custom program. + assert_eq!(args(&slicer("bambu", "Bambu Studio", &["/x/bambu-studio"]), true), ["/t/a.3mf"]); + assert_eq!(args(&slicer("custom", "Bambu Studio", &["/x/bambu-studio"]), true), ["/t/a.3mf"]); + // OrcaSlicer and the rest have no such flag; a macOS bundle is single-instance already. + assert_eq!(args(&slicer("orca", "OrcaSlicer", &["/x/orca"]), true), ["/t/a.3mf"]); + assert_eq!( + args(&slicer("prusa", "PrusaSlicer", &["open", "-a", "/Applications/PrusaSlicer.app"]), true), + ["-a", "/Applications/PrusaSlicer.app", "/t/a.3mf"] + ); + // A program the user picked is known by its name. + assert_eq!(args(&slicer("custom", "PrusaSlicer", &["/x/prusa-slicer"]), true), ["--single-instance", "/t/a.3mf"]); + assert_eq!(args(&slicer("custom", "Mycura", &["/x/mycura"]), true), ["/t/a.3mf"]); + // PrusaSlicer 3.0's launcher entry already has the flag (`%u` is dropped when the entry is read). + let launcher = slicer("prusa", "PrusaSlicer", &["slic3r-app-launcher", "--single-instance-on-url"]); + assert_eq!(args(&launcher, true), ["--single-instance-on-url", "/t/a.3mf"]); + // Its launcher can't hand a file over without the flag, so the preference does not remove it. + assert_eq!(args(&launcher, false), ["--single-instance-on-url", "/t/a.3mf"]); + // Flatpak: the flag goes among the application's arguments, before the file markers. + let flatpak = slicer("prusa", "PrusaSlicer", &["flatpak", "run", "com.prusa3d.PrusaSlicer", "@@u", "@@"]); + assert_eq!(args(&flatpak, true), ["run", "com.prusa3d.PrusaSlicer", "--single-instance", "@@", "/t/a.3mf", "@@"]); + } + + #[cfg(unix)] + #[test] + fn only_detected_slicers_and_chosen_programs_can_be_resolved() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("resolve"); + let program = root.join("mycura"); + std::fs::write(&program, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = program.to_str().unwrap(); + let prusa = Slicer { id: "prusa".into(), name: "PrusaSlicer".into(), command: vec!["prusa-slicer".into()], icon: None, prusa_major: None }; + let found = |spec: &str, chosen: &[String]| resolve_in(vec![prusa.clone()], chosen, spec).map(|s| s.id); + assert_eq!(found("prusa", &[]).as_deref(), Some("prusa")); + assert_eq!(found("Prusa Slicer", &[]).as_deref(), Some("prusa")); + // A real program that nobody chose is not a slicer, whatever path it is given by. + assert_eq!(found(path, &[]), None); + assert_eq!(found("/bin/sh", &[]), None); + assert_eq!(found("", &[]), None); + // One the user chose works by path and by name; a path that was not chosen still does not. + let chosen = [path.to_string()]; + assert_eq!(found(path, &chosen).as_deref(), Some("custom")); + assert_eq!(found("Mycura", &chosen).as_deref(), Some("custom")); + assert_eq!(found("/bin/sh", &chosen), None); + // Chosen, then uninstalled: gone. + std::fs::remove_file(&program).unwrap(); + assert_eq!(found(path, &chosen), None); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn each_install_of_a_slicer_is_listed_on_its_own() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("installs"); + let home = root.join("home"); + let (system, user) = (root.join("usr/share"), home.join(".local/share")); + for dir in [&system, &user] { + std::fs::create_dir_all(dir.join("applications")).unwrap(); + } + // The two entries of the real desktop: PrusaSlicer 2.9 from the system, 3.0 beta as a Flatpak. + std::fs::write( + system.join("applications/PrusaSlicer.desktop"), + "[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec=prusa-slicer %F\n", + ) + .unwrap(); + std::fs::write( + user.join("applications/com.prusa3d.PrusaSlicer.desktop"), + "[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec=flatpak run --branch=beta --arch=x86_64 --command=slic3r-app-launcher --file-forwarding com.prusa3d.PrusaSlicer --single-instance-on-url @@u %U @@\n", + ) + .unwrap(); + let bin = root.join("usr/bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("prusa-slicer"), b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("prusa-slicer"), std::fs::Permissions::from_mode(0o755)).unwrap(); + // The same program is also on PATH under its own name: still the one install. + let env = Env { home: Some(home), data_dirs: vec![user, system], path_dirs: vec![bin], ..Env::default() }; + let found = detect_in(&env); + let listed: Vec<(&str, &str)> = found.iter().map(|f| (f.id.as_str(), f.name.as_str())).collect(); + assert_eq!(listed, [("prusa#comprusa3dprusaslicer", "PrusaSlicer (Flatpak, beta)"), ("prusa#prusaslicer", "PrusaSlicer (system)")]); + // Both are still PrusaSlicer to everything that looks at the kind of slicer. + assert!(found.iter().all(|f| f.base_id() == "prusa")); + let flatpak = found[0].args("/t/a.3mf", true); + assert_eq!(flatpak.iter().filter(|a| a.starts_with("--single-instance")).collect::>(), ["--single-instance-on-url"]); + assert_eq!(found[1].args("/t/a.3mf", true), ["--single-instance", "/t/a.3mf"]); + // The same on every run, whatever order the folders are read in. + let again = detect_in(&Env { data_dirs: env.data_dirs.iter().rev().cloned().collect(), ..env.clone() }); + assert_eq!(found, again); + // `prusa` alone, as remembered or typed before there were two, is the first; a full id is that install. + let pick = |spec: &str| resolve_in(found.clone(), &[], spec).map(|s| s.id); + assert_eq!(pick("prusa").as_deref(), Some("prusa#comprusa3dprusaslicer")); + assert_eq!(pick("PrusaSlicer").as_deref(), Some("prusa#comprusa3dprusaslicer")); + assert_eq!(pick("prusa#prusaslicer").as_deref(), Some("prusa#prusaslicer")); + assert_eq!(pick("PrusaSlicer (system)").as_deref(), Some("prusa#prusaslicer")); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn the_launcher_needs_a_start_and_a_wait_and_other_slicers_do_not() { + let slicer = |command: &[&str]| Slicer { + id: "prusa".into(), + name: "PrusaSlicer".into(), + command: command.iter().map(|s| s.to_string()).collect(), + icon: None, + prusa_major: None, + }; + // The command lines of this machine's desktop entries. + let flatpak = slicer(&[ + "flatpak", + "run", + "--branch=beta", + "--arch=x86_64", + "--command=slic3r-app-launcher", + "--file-forwarding", + "com.prusa3d.PrusaSlicer", + "--single-instance-on-url", + "@@u", + "@@", + ]); + let launcher = slicer(&["slic3r-app-launcher", "--single-instance-on-url"]); + assert!(flatpak.waits_for_ready().is_some() && launcher.waits_for_ready().is_some()); + for command in [ + &["prusa-slicer"][..], + &["flatpak", "run", "com.prusa3d.PrusaSlicer", "@@u", "@@"], + &["/usr/bin/orca-slicer"], + &["open", "-a", "/Applications/PrusaSlicer.app"], + ] { + assert!(slicer(command).waits_for_ready().is_none(), "{command:?}"); + } + // Starting on its own: no file, and none of the Flatpak file markers. + assert_eq!( + flatpak.start_args(true), + [ + "run", + "--branch=beta", + "--arch=x86_64", + "--command=slic3r-app-launcher", + "--file-forwarding", + "com.prusa3d.PrusaSlicer", + "--single-instance-on-url" + ] + ); + // The preference does not take the flag off the launcher, on a start or a send (its entry's own + // is kept, and one is added where there is none). + assert_eq!(launcher.start_args(false), ["--single-instance-on-url"]); + let bare = slicer(&["slic3r-app-launcher"]); + assert_eq!(bare.start_args(false), ["--single-instance"]); + assert_eq!(bare.start_args(true), ["--single-instance"]); + assert_eq!(bare.args("/t/a.3mf", false), ["--single-instance", "/t/a.3mf"], "a normal send, preference off"); + assert_eq!(bare.args("/t/a.3mf", true), ["--single-instance", "/t/a.3mf"]); + // A slicer that does not need a start first is started as the preference says. + assert!(slicer(&["prusa-slicer"]).start_args(false).is_empty()); + } + + #[test] + fn the_bus_list_says_whether_the_slicer_is_up() { + let prefix = PRUSA_READY.bus_prefix; + let without = ":1.5 1234 systemd :1.5 user@1000.service 1 -\norg.freedesktop.Notifications 99 dunst :1.40 u 1 -\ncom.prusa3d.PrusaSlicer 7 x :1.9 s 1 -\n"; + let with = format!("{without}com.prusa3d.prusaslicer.BroadcastListener.3f9a1c 4321 xdg-dbus-proxy :1.77 u 1 -\n"); + assert!(!has_bus_name(without, prefix)); + assert!(has_bus_name(&with, prefix)); + assert!(!has_bus_name("", prefix)); + // The suffix changes with the install; only the start counts, and only at the start of a name. + assert!(!has_bus_name("x.com.prusa3d.prusaslicer.BroadcastListener.1 1 p :1.1 u 1 -", prefix)); + assert_eq!(bus_names(&with).count(), 4); + } + + #[test] + fn waiting_stops_at_once_when_ready_and_gives_up_at_the_limit() { + let tick = std::time::Duration::from_millis(5); + let mut asked = 0; + assert!(wait_until( + |_| { + asked += 1; + true + }, + std::time::Duration::from_secs(5), + std::time::Duration::from_secs(5) + )); + assert_eq!(asked, 1, "already up: no sleep"); + let mut asked = 0; + assert!(wait_until( + |_| { + asked += 1; + asked == 3 + }, + std::time::Duration::from_secs(5), + tick + )); + assert_eq!(asked, 3); + let started = std::time::Instant::now(); + assert!(!wait_until(|_| false, std::time::Duration::from_millis(40), tick)); + assert!(started.elapsed() >= std::time::Duration::from_millis(40) && started.elapsed() < std::time::Duration::from_secs(5)); + } + + #[test] + fn a_probe_that_says_yes_after_the_limit_is_accepted_and_the_wait_stays_bounded() { + let started = std::time::Instant::now(); + let mut asked = 0; + let ok = wait_until( + |_| { + asked += 1; + std::thread::sleep(std::time::Duration::from_millis(80)); + true + }, + std::time::Duration::from_millis(30), + std::time::Duration::from_millis(5), + ); + // The look began inside the limit, ran past it, and its yes is taken: the file still goes. + assert!(ok); + assert_eq!(asked, 1); + // Limit plus the probe's own time, nothing more. + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // A probe that began before the limit and says no, then is never followed by another. + let mut asked = 0; + let started = std::time::Instant::now(); + assert!(!wait_until( + |_| { + asked += 1; + std::thread::sleep(std::time::Duration::from_millis(80)); + false + }, + std::time::Duration::from_millis(30), + std::time::Duration::from_millis(5) + )); + assert_eq!(asked, 1, "no probe is started after the limit"); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + } + + #[test] + fn a_slow_probe_can_not_start_another_after_the_limit() { + // The first look takes longer than the whole limit and says no; the second would say yes, + // but the limit has passed, so it is never asked. + let mut asked = 0; + let ok = wait_until( + |_| { + asked += 1; + if asked == 1 { + std::thread::sleep(std::time::Duration::from_millis(60)); + } + asked > 1 + }, + std::time::Duration::from_millis(30), + std::time::Duration::from_millis(5), + ); + assert!(!ok); + assert_eq!(asked, 1); + // The probe is told how much time is left, and it shrinks. + let mut lefts = Vec::new(); + wait_until( + |left| { + lefts.push(left); + false + }, + std::time::Duration::from_millis(40), + std::time::Duration::from_millis(10), + ); + assert!(lefts[0] <= std::time::Duration::from_millis(40) && lefts.windows(2).all(|w| w[1] <= w[0]), "{lefts:?}"); + } + + #[cfg(unix)] + #[test] + fn a_busctl_that_hangs_is_cut_off_and_one_that_answers_is_read() { + let root = scratch("busctl"); + let fake = |name: &str, body: &str| fake_program(&root, name, body); + let hang = fake("hang", "exec sleep 30"); + let started = std::time::Instant::now(); + assert_eq!(bus_list(&hang, std::time::Duration::from_millis(100)), Bus::Slow); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "cut off, not waited for"); + let answers = fake("answers", "echo ':1.5 1 x'; echo 'com.prusa3d.prusaslicer.BroadcastListener.ab 2 y'"); + let Bus::Names(list) = bus_list(&answers, std::time::Duration::from_secs(5)) else { panic!("no names") }; + assert!(has_bus_name(&list, PRUSA_READY.bus_prefix)); + assert_eq!(bus_list(&fake("fails", "exit 1"), std::time::Duration::from_secs(5)), Bus::Unknown); + // It exits at once but leaves a process running that keeps its output open. + let lingers = fake("lingers", "echo ':1.5 1 x'; sleep 5 &\nexit 0"); + let started = std::time::Instant::now(); + assert_eq!(bus_list(&lingers, std::time::Duration::from_millis(200)), Bus::Slow); + assert!(started.elapsed() < std::time::Duration::from_secs(3), "{:?}", started.elapsed()); + assert_eq!(bus_list(&root.join("missing").to_string_lossy(), std::time::Duration::from_secs(1)), Bus::Unknown); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn mac_installs_are_labelled_by_their_application_not_by_open() { + let root = scratch("mac-labels"); + let home = root.join("home"); + let (system, user) = (root.join("Applications"), home.join("Applications")); + for dir in [&system, &user] { + std::fs::create_dir_all(dir.join("PrusaSlicer.app")).unwrap(); + } + let env = Env { home: Some(home), app_dirs: vec![system, user], ..Env::default() }; + let found = detect_in(&env); + let listed: Vec<(&str, &str)> = found.iter().map(|f| (f.id.as_str(), f.name.as_str())).collect(); + assert_eq!(listed.len(), 2); + assert!(listed.iter().any(|(_, n)| *n == "PrusaSlicer (system)"), "{listed:?}"); + assert!(listed.iter().any(|(_, n)| *n == "PrusaSlicer (~/Applications)"), "{listed:?}"); + assert_ne!(listed[0].0, listed[1].0, "own ids"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn two_names_for_one_program_give_the_same_ids_whichever_is_read_first() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("aliases"); + let home = root.join("home"); + let bin = root.join("usr/bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("prusa-slicer"), b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("prusa-slicer"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let entry = |dir: &Path, file: &str, exec: &str| { + std::fs::create_dir_all(dir.join("applications")).unwrap(); + std::fs::write(dir.join("applications").join(file), format!("[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec={exec}\n")) + .unwrap(); + }; + // Two desktop files, different names, one program; and a second, real install. + let (a, b, user) = (root.join("share-a"), root.join("share-b"), home.join(".local/share")); + entry(&a, "PrusaSlicer.desktop", "prusa-slicer %F"); + entry(&b, "prusa-alias.desktop", &format!("{} %U", bin.join("prusa-slicer").display())); + entry(&user, "com.prusa3d.PrusaSlicer.desktop", "flatpak run --branch=beta com.prusa3d.PrusaSlicer @@u %U @@"); + let env = |dirs: Vec| Env { home: Some(home.clone()), data_dirs: dirs, path_dirs: vec![bin.clone()], ..Env::default() }; + let forward = detect_in(&env(vec![a.clone(), b.clone(), user.clone()])); + let reversed = detect_in(&env(vec![user.clone(), b.clone(), a.clone()])); + assert_eq!(forward.len(), 2, "{forward:?}"); + assert_eq!(forward, reversed); + // The place that sorts first speaks for the program: its command, its file name in the id. + let system = forward.iter().find(|s| s.name.contains("system")).unwrap(); + assert_eq!(system.id, "prusa#prusaslicer"); + assert_eq!(system.command, ["prusa-slicer"]); + std::fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] + #[test] + fn the_same_flatpak_invocation_is_one_install_however_flatpak_is_spelled() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("flatpak-key"); + let launcher = |dir: &str| { + let p = root.join(dir).join("flatpak"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, dir.as_bytes()).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + p + }; + let (on_path, other) = (launcher("bin"), launcher("opt/tool-b")); + let (a, b) = (root.join("share-a"), root.join("share-b")); + let entry = |dir: &Path, file: &str, exec: &str| { + std::fs::create_dir_all(dir.join("applications")).unwrap(); + std::fs::write(dir.join("applications").join(file), format!("[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec={exec}\n")) + .unwrap(); + }; + let app = "--branch=beta com.prusa3d.PrusaSlicer @@u %U @@"; + let env = |dirs: Vec| Env { data_dirs: dirs, path_dirs: vec![root.join("bin")], ..Env::default() }; + entry(&a, "one.desktop", &format!("flatpak run {app}")); + entry(&b, "two.desktop", &format!("{} run {app}", on_path.display())); + // `flatpak` found on PATH and the same file by its path: one install. + let found = detect_in(&env(vec![a.clone(), b.clone()])); + assert_eq!(found.len(), 1, "{found:?}"); + // A different executable of the same name, with the same arguments: another install. + entry(&b, "three.desktop", &format!("{} run {app}", other.display())); + let found = detect_in(&env(vec![a.clone(), b.clone()])); + assert_eq!(found.len(), 2, "{found:?}"); + // A different branch is another install too. + entry(&b, "four.desktop", "flatpak run --branch=stable com.prusa3d.PrusaSlicer @@u %U @@"); + assert_eq!(detect_in(&env(vec![a, b])).len(), 3); + // Where `flatpak` can't be found, its name stands in. + let none = Env { data_dirs: vec![root.join("share-a")], ..Env::default() }; + assert_eq!(detect_in(&none).len(), 1); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn a_slow_busctl_is_not_up_yet_and_a_missing_or_failing_one_is_send_now() { + let root = scratch("busctl-wait"); + let fake = |name: &str, body: &str| fake_program(&root, name, body); + let launcher = + Slicer { id: "prusa".into(), name: "PrusaSlicer".into(), command: vec!["slic3r-app-launcher".into()], icon: None, prusa_major: None }; + let (limit, poll) = (std::time::Duration::from_millis(300), std::time::Duration::from_millis(20)); + // Hangs: not ready, the wait keeps going to its limit and then times out (does not send). + let hang = fake("hang", "exec sleep 30"); + assert_eq!(launcher.ready_via(&hang, std::time::Duration::from_millis(50)), Some(false)); + let started = std::time::Instant::now(); + assert!(!wait_for_ready_via(&launcher, &hang, limit, poll)); + assert!(started.elapsed() >= limit && started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // Missing: it can't be told, so no waiting. + let missing = root.join("missing").to_string_lossy().into_owned(); + assert_eq!(launcher.ready_via(&missing, limit), None); + let started = std::time::Instant::now(); + assert!(wait_for_ready_via(&launcher, &missing, limit, poll)); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // Answers "not up" once, then fails: the wait stops and sends. + let count = root.join("count"); + let flaky = fake( + "flaky", + &format!("n=$(cat {c} 2>/dev/null || echo 0); echo $((n+1)) > {c}; [ $n -ge 1 ] && exit 1; echo ':1.5 1 x'", c = count.display()), + ); + assert!(wait_for_ready_via(&launcher, &flaky, std::time::Duration::from_secs(5), poll)); + assert_eq!(std::fs::read_to_string(&count).unwrap().trim(), "2", "looked twice: not up, then failed"); + // And one that names the slicer is ready at once. + let up = fake("up", "echo 'com.prusa3d.prusaslicer.BroadcastListener.ab 1 x'"); + assert_eq!(launcher.ready_via(&up, limit), Some(true)); + std::fs::remove_dir_all(root).unwrap(); + } + /// What the flags and the wait come to for a PrusaSlicer install, by its version. + fn prusa(command: &str, major: Option) -> Slicer { + Slicer { + id: "prusa".into(), + name: "PrusaSlicer".into(), + command: command.split(' ').map(str::to_string).collect(), + icon: None, + prusa_major: major, + } + } + + // The command lines of this desktop's two Flatpak entries, with `%u` and `%U` dropped as `parse_exec` does. + const V2_ENTRY: &str = + "flatpak run --branch=stable --command=entrypoint --file-forwarding com.prusa3d.PrusaSlicer --single-instance-on-url @@u @@"; + const V3_ENTRY: &str = "flatpak run --branch=master --arch=x86_64 --command=slic3r-app-launcher --file-forwarding com.prusa3d.PrusaSlicer --single-instance-on-url @@u @@"; + + #[test] + fn prusa_2_swaps_the_flag_and_does_not_wait_and_prusa_3_keeps_it_and_waits() { + let with = |flag: &str| { + let mut v: Vec = + ["run", "--branch=stable", "--command=entrypoint", "--file-forwarding", "com.prusa3d.PrusaSlicer"].map(String::from).into(); + v.extend([flag, "@@", "/t/a.3mf", "@@"].map(String::from).into_iter().filter(|a| !a.is_empty())); + v + }; + // 2.9.6: `--single-instance` in its place, no wait, the file markers as before; nothing without the preference. + let v2 = prusa(V2_ENTRY, Some(2)); + assert!(v2.waits_for_ready().is_none()); + assert_eq!(v2.args("/t/a.3mf", true), with("--single-instance")); + assert_eq!(v2.args("/t/a.3mf", false), with("")); + // Also when its command happens to go through the launcher: the version decides. + assert!(prusa("slic3r-app-launcher --single-instance-on-url", Some(2)).waits_for_ready().is_none()); + // 3.0.0-alpha10: the launcher's own flag stays on every send and start, and it waits. + let v3 = prusa(V3_ENTRY, Some(3)); + assert!(v3.waits_for_ready().is_some()); + for single in [true, false] { + let sent = v3.args("/t/a.3mf", single); + assert!(sent.contains(&"--single-instance-on-url".to_string()) && !sent.contains(&"--single-instance".to_string()), "{sent:?}"); + assert!(v3.start_args(single).contains(&"--single-instance-on-url".to_string())); + } + // Newer than 3 waits too, and so does a 3 whose command is not the launcher. + assert!(prusa("prusa-slicer", Some(4)).waits_for_ready().is_some()); + assert!(prusa("prusa-slicer", Some(3)).waits_for_ready().is_some()); + } + + #[test] + fn an_unreadable_version_falls_back_to_the_command() { + // The launcher's name means 3: it waits and keeps its flag, as before versions were read. + let launcher = prusa("slic3r-app-launcher --single-instance-on-url", None); + assert!(launcher.waits_for_ready().is_some()); + assert_eq!(launcher.args("/t/a.3mf", true), ["--single-instance-on-url", "/t/a.3mf"]); + // Without it nothing is known: no wait, and the entry's flags are left as they are. + let unknown = prusa(V2_ENTRY, None); + assert!(unknown.waits_for_ready().is_none()); + let sent = unknown.args("/t/a.3mf", true); + assert!(sent.contains(&"--single-instance-on-url".to_string()) && !sent.contains(&"--single-instance".to_string()), "{sent:?}"); + assert!(!unknown.args("/t/a.3mf", false).iter().any(|a| a.starts_with("--single-instance"))); + } + + #[test] + fn a_program_that_is_not_prusaslicer_is_left_alone_whatever_a_version_says() { + let viewer = Slicer { + id: "desktop-meshviewer".into(), + name: "Mesh Viewer".into(), + command: vec!["mesh-viewer".into(), "--single-instance-on-url".into()], + icon: None, + prusa_major: Some(2), + }; + assert_eq!(viewer.args("/t/a.3mf", true), ["--single-instance-on-url", "/t/a.3mf"]); + assert_eq!(viewer.args("/t/a.3mf", false), ["/t/a.3mf"]); + assert!(viewer.waits_for_ready().is_none()); + // One the user picked and named PrusaSlicer is PrusaSlicer, and is told apart by its version like the rest. + let picked = |name: &str, major| Slicer { + id: "custom".into(), + name: name.into(), + command: vec!["/x/prog".into(), "--single-instance-on-url".into()], + icon: None, + prusa_major: major, + }; + assert_eq!(picked("PrusaSlicer", Some(2)).args("/t/a.3mf", true), ["--single-instance", "/t/a.3mf"]); + assert_eq!(picked("PrusaSlicer", None).args("/t/a.3mf", true), ["--single-instance-on-url", "/t/a.3mf"]); + assert_eq!(picked("Mesh Viewer", Some(2)).args("/t/a.3mf", true), ["--single-instance-on-url", "/t/a.3mf"]); + } + + #[test] + fn the_version_is_the_leading_number_of_the_top_release() { + let xml = |v: &str| { + format!( + "" + ) + }; + assert_eq!(release_major(&xml("3.0.0-alpha10")), Some(3)); + assert_eq!(release_major(&xml("2.9.6")), Some(2)); + assert_eq!(release_major(&xml("10.1")), Some(10)); + assert_eq!(release_major(&xml("beta")), None); + assert_eq!(release_major(""), None); + assert_eq!(release_major(""), None); + } + + #[test] + fn detection_reads_the_version_from_the_installs_metadata() { + let root = scratch("versions"); + let (home, share) = (root.join("home"), root.join("home/.local/share")); + let flatpak = home.join(".local/share/flatpak"); + let deploy = |branch: &str, version: &str| { + let dir = flatpak.join("app/com.prusa3d.PrusaSlicer/x86_64").join(branch).join("active/files/share/metainfo"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("com.prusa3d.PrusaSlicer.metainfo.xml"), + format!(""), + ) + .unwrap(); + }; + deploy("stable", "2.9.6"); + deploy("master", "3.0.0-alpha10"); + std::fs::create_dir_all(share.join("applications")).unwrap(); + let entry = |file: &str, exec: &str| { + std::fs::write(share.join("applications").join(file), format!("[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec={exec}\n")) + .unwrap(); + }; + entry("v2.desktop", V2_ENTRY); + entry("v3.desktop", V3_ENTRY); + // A branch that is not installed has no metadata to read. + entry("gone.desktop", &V3_ENTRY.replace("--branch=master", "--branch=beta")); + let env = Env { home: Some(home), data_dirs: vec![share.clone()], flatpak_roots: vec![flatpak], ..Env::default() }; + let found = detect_in(&env); + let by = |needle: &str| found.iter().find(|s| s.command.iter().any(|a| a == needle)).unwrap(); + assert_eq!(by("--branch=stable").prusa_major, Some(2)); + assert_eq!(by("--branch=master").prusa_major, Some(3)); + assert_eq!(by("--branch=beta").prusa_major, None); + // And what that decides: 2.9.6 swaps and does not wait; 3.0 keeps its flag and waits; the unread one goes by its launcher. + assert!( + by("--branch=stable").waits_for_ready().is_none() + && by("--branch=stable").args("/t/a.3mf", true).contains(&"--single-instance".to_string()) + ); + assert!(by("--branch=master").waits_for_ready().is_some()); + assert!(by("--branch=beta").waits_for_ready().is_some()); + // A system install: the metadata sits beside its desktop entry. + let usr = root.join("usr/share"); + std::fs::create_dir_all(usr.join("applications")).unwrap(); + std::fs::create_dir_all(usr.join("metainfo")).unwrap(); + std::fs::write(usr.join("applications/PrusaSlicer.desktop"), "[Desktop Entry]\nType=Application\nName=PrusaSlicer\nExec=prusa-slicer %F\n") + .unwrap(); + std::fs::write(usr.join("metainfo/PrusaSlicer.metainfo.xml"), "") + .unwrap(); + let found = detect_in(&Env { data_dirs: vec![usr], ..Env::default() }); + assert_eq!((found.len(), found[0].prusa_major), (1, Some(2))); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn the_path_of_a_listed_program_is_accepted_and_any_other_is_not() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("listed-path"); + let apps = root.join("Applications"); + std::fs::create_dir_all(&apps).unwrap(); + let image = apps.join("PrusaSlicer-2.9.AppImage"); + std::fs::write(&image, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&image, std::fs::Permissions::from_mode(0o755)).unwrap(); + let other = root.join("other"); + std::fs::write(&other, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&other, std::fs::Permissions::from_mode(0o755)).unwrap(); + let link = root.join("link-to-image"); + std::os::unix::fs::symlink(&image, &link).unwrap(); + let found = detect_in(&Env { program_dirs: vec![apps], ..Env::default() }); + let spec = |s: &std::path::Path| resolve_in(found.clone(), &[], s.to_str().unwrap()).map(|s| s.id); + // The AppImage as `file.slicers` lists it, and a link to the same file. + assert_eq!(found[0].command, [image.to_str().unwrap()]); + assert_eq!(spec(&image).as_deref(), Some("prusa")); + assert_eq!(spec(&link).as_deref(), Some("prusa")); + // A program nobody listed or chose is refused, executable or not. + assert_eq!(spec(&other), None); + assert_eq!(spec(std::path::Path::new("/bin/sh")), None); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn an_appimage_keeps_its_id_through_an_upgrade_and_has_its_own_per_folder() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("appimage-ids"); + let exe = |p: &std::path::Path| { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap(); + }; + // A second install of PrusaSlicer, so that each one is told apart by an id of its own. + let bin = root.join("bin"); + exe(&bin.join("prusa-slicer")); + let ids = |folder: &str, file: &str| { + let apps = root.join(folder); + exe(&apps.join(file)); + let found = detect_in(&Env { path_dirs: vec![bin.clone()], program_dirs: vec![apps.clone()], ..Env::default() }); + let image = found.iter().find(|s| s.command == [apps.join(file).to_string_lossy().into_owned()]).unwrap(); + std::fs::remove_file(apps.join(file)).unwrap(); + (image.id.clone(), found.iter().find(|s| s.id != image.id).map(|s| s.id.clone()).unwrap()) + }; + let (v29, path_install) = ids("Apps", "PrusaSlicer-2.9.0.AppImage"); + let (v210, _) = ids("Apps", "PrusaSlicer-2.10.1.AppImage"); + let (elsewhere, _) = ids("Other", "PrusaSlicer-2.9.0.AppImage"); + assert!(v29.starts_with("prusa#appimage-"), "{v29}"); + assert_eq!(v29, v210, "an upgrade in the same folder keeps the id"); + assert_ne!(v29, elsewhere, "another folder is another install"); + assert_eq!(path_install, "prusa#prusaslicer", "installs that are not AppImages are told apart as before"); + // Two versions side by side in one folder are two installs, told apart by their file names. + let apps = root.join("Apps"); + exe(&apps.join("PrusaSlicer-2.9.0.AppImage")); + exe(&apps.join("PrusaSlicer-2.10.1.AppImage")); + let both = detect_in(&Env { path_dirs: vec![bin.clone()], program_dirs: vec![apps.clone()], ..Env::default() }); + let mut images: Vec<&str> = both.iter().filter(|s| s.command[0].ends_with(".AppImage")).map(|s| s.id.as_str()).collect(); + images.sort_unstable(); + assert_eq!(images.len(), 2); + assert!(images.iter().all(|id| id.starts_with(&format!("{v29}-"))), "{images:?} from {v29}"); + assert_ne!(images[0], images[1]); + // Each resolves to its own file; the id from when there was only one names neither. + for id in &images { + let hit = resolve_in(both.clone(), &[], id).unwrap(); + assert_eq!(&hit.id, id); + } + assert_eq!(resolve_in(both.clone(), &[], &v29), None, "an id that is now two installs is not either of them"); + // After the old one is gone, the new one alone has the plain AppImage id again. + std::fs::remove_file(apps.join("PrusaSlicer-2.9.0.AppImage")).unwrap(); + let after = detect_in(&Env { path_dirs: vec![bin.clone()], program_dirs: vec![apps], ..Env::default() }); + assert!(after.iter().any(|s| s.id == v29 && s.command[0].ends_with("2.10.1.AppImage")), "{after:?}"); + // An id from before this (made of the file name) no longer names an install, here; the picker falls + // back to the first install of the same slicer for it (`SlicerMenu::key_for`), and the plain `prusa` still resolves. + let found = detect_in(&Env { path_dirs: vec![bin.clone()], ..Env::default() }); + assert_eq!(resolve_in(found.clone(), &[], "prusa#prusa29"), None); + assert!(resolve_in(found, &[], "prusa").is_some()); + std::fs::remove_dir_all(root).unwrap(); + } } diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs index f9f01a8e9..33a4bb841 100644 --- a/crates/engine/src/tests/mesh_convert.rs +++ b/crates/engine/src/tests/mesh_convert.rs @@ -184,9 +184,13 @@ fn stl_export_is_closed_where_faces_meet() { #[test] fn save_mesh_rejects_unknown_format_and_slicer_without_writing() { let mut s = imported_box(); - let path = std::env::temp_dir().join(format!("solvecraft-save-mesh-{}.stl", std::process::id())); + // Its own file name: `save_mesh_writes_stl_and_3mf` writes `solvecraft-save-mesh-.stl`, and + // sharing it made this one fail when the two ran together. + let path = std::env::temp_dir().join(format!("solvecraft-save-mesh-rejected-{}.stl", std::process::id())); let _ = std::fs::remove_file(&path); - for params in [json!({"path":path,"format":"nope"}), json!({"path":path,"slicer":"no such slicer anywhere"})] { + for params in + [json!({"path":path,"format":"nope"}), json!({"path":path,"slicer":"no such slicer anywhere"}), json!({"path":path,"slicer":"/bin/sh"})] + { assert!(s.execute("file.save_mesh", ¶ms).is_err()); assert!(!path.exists()); } @@ -217,6 +221,324 @@ fn installed_slicers_are_listed() { assert!(r["slicers"].is_array()); } +#[test] +fn send_to_slicer_needs_a_slicer_and_bodies() { + let mut s = imported_box(); + assert!(s.execute("file.send_to_slicer", &json!({"bodies":["Mesh"]})).is_err()); + assert!(s.execute("file.send_to_slicer", &json!({"slicer":"no such slicer anywhere","bodies":["Mesh"]})).is_err()); + // Nothing selected and nothing named. + assert!(s.execute("file.send_to_slicer", &json!({"slicer":"no such slicer anywhere"})).is_err()); +} + +/// The chosen-programs list is process-wide: tests that set it take turns. +static CHOSEN_PROGRAMS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// `file.save_mesh` with a `slicer` writes where the caller said and hands that file over, by the +/// same steps as `file.send_to_slicer`. +#[cfg(unix)] +#[test] +fn save_mesh_with_a_chosen_program_writes_the_file_where_asked_and_sends_it_there() { + use std::os::unix::fs::PermissionsExt; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = std::env::temp_dir().join(format!("solidcraft-save-mesh-send-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (script, seen, out) = (dir.join("fake-slicer"), dir.join("seen"), dir.join("part.stl")); + std::fs::write(&script, format!("#!/bin/sh\necho \"$@\" >> {}\n", seen.display())).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let spec = script.to_string_lossy().into_owned(); + crate::slicers::set_chosen_programs(std::slice::from_ref(&spec)); + let mut s = imported_box(); + let r = s.execute("file.save_mesh", &json!({"path": out, "slicer": spec, "single_instance": false})); + crate::slicers::set_chosen_programs(&[]); + let r = r.unwrap(); + assert_eq!(r["path"].as_str(), out.to_str()); + assert!(out.exists(), "written where it was asked"); + assert!(r.get("slicer").is_some() && r.get("slicer_error").is_none(), "{r}"); + for _ in 0..100 { + if seen.exists() && std::fs::metadata(&seen).unwrap().len() > 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + assert_eq!(std::fs::read_to_string(&seen).unwrap().trim(), out.to_str().unwrap()); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// Puts back what the tests of the send commands make up, even when one fails. +#[cfg(unix)] +struct MadeUp; + +#[cfg(unix)] +impl Drop for MadeUp { + fn drop(&mut self) { + *crate::slicers::TEST_DETECTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + *crate::slicers::TEST_BUSCTL.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + crate::slicers::set_chosen_programs(&[]); + } +} + +/// The entry point of the first reported failure: a path that `file.slicers` lists is accepted by +/// `file.save_mesh`, the file is written where asked, the result keeps its contract, and a path that +/// is not listed, or that several entries share, is refused without writing anything. +#[cfg(unix)] +#[test] +fn save_mesh_accepts_the_path_of_a_listed_appimage_and_refuses_the_others() { + use crate::slicers::{Slicer, TEST_DETECTED, test_support::fake_program}; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _reset = MadeUp; + let dir = std::env::temp_dir().join(format!("solidcraft-save-mesh-listed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let seen = dir.join("seen"); + let image = fake_program(&dir, "PrusaSlicer-2.9.AppImage", &format!("echo \"$@\" >> {}", seen.display())); + let other = fake_program(&dir, "other", "exit 0"); + let launcher = fake_program(&dir, "shared-launcher", "exit 0"); + let entry = |name: &str, command: Vec| Slicer { id: name.into(), name: name.into(), command, icon: None, prusa_major: None }; + *TEST_DETECTED.lock().unwrap() = Some(vec![ + entry("prusa", vec![image.clone()]), + entry("one", vec![launcher.clone(), "run".into(), "--branch=a".into()]), + entry("two", vec![launcher.clone(), "run".into(), "--branch=b".into()]), + ]); + let mut s = imported_box(); + let plain = dir.join("plain.stl"); + let plain_result = s.execute("file.save_mesh", &json!({"path": plain})).unwrap(); + // Listed: accepted, written where asked, the same export as without a slicer, then handed over. + let out = dir.join("part.stl"); + let r = s.execute("file.save_mesh", &json!({"path": out, "slicer": image, "single_instance": false})).unwrap(); + assert_eq!((&r["bytes"], &r["format"]), (&plain_result["bytes"], &plain_result["format"]), "the export's result is as before"); + assert_eq!(r["path"].as_str(), out.to_str()); + // The same STL; its 80-byte header carries the file's name, which differs. + assert_eq!(std::fs::read(&out).unwrap()[80..], std::fs::read(&plain).unwrap()[80..]); + assert!(r.get("slicer").is_some() && r.get("slicer_error").is_none(), "{r}"); + for _ in 0..100 { + if std::fs::metadata(&seen).map(|m| m.len() > 0).unwrap_or(false) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + assert!(std::fs::read_to_string(&seen).unwrap().trim().ends_with(out.to_str().unwrap())); + // Not listed, and shared by two entries: refused, and nothing is written. + for (spec, name) in [(other.as_str(), "other.stl"), (launcher.as_str(), "ambiguous.stl"), ("/bin/sh", "sh.stl")] { + let path = dir.join(name); + assert!(s.execute("file.save_mesh", &json!({"path": path, "slicer": spec})).is_err(), "{spec}"); + assert!(!path.exists(), "{spec}: nothing written"); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +/// The entry point of the second: a PrusaSlicer 3 that is not running is started on its own, waited +/// for, and only then sent the file `file.save_mesh` wrote. +#[cfg(unix)] +#[test] +fn save_mesh_with_a_cold_prusaslicer_3_waits_for_it_before_sending() { + use crate::slicers::{Slicer, TEST_BUSCTL, TEST_DETECTED, test_support::fake_program}; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _reset = MadeUp; + let dir = std::env::temp_dir().join(format!("solidcraft-save-mesh-cold-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let launcher_dir = dir.join("slic3r-app-launcher"); + std::fs::create_dir_all(&launcher_dir).unwrap(); + let log = dir.join("log"); + let launcher = fake_program(&launcher_dir, "PrusaSlicer", &format!("echo \"$@\" >> {}", log.display())); + let count = dir.join("count"); + // Not on the bus the first two looks, there after that. + let busctl = fake_program( + &dir, + "busctl", + &format!( + "n=$(cat {c} 2>/dev/null || echo 0); echo $((n+1)) > {c}; echo ':1.5 1 x'; [ $n -ge 2 ] && echo 'com.prusa3d.prusaslicer.BroadcastListener.ab 2 y'; exit 0", + c = count.display() + ), + ); + *TEST_BUSCTL.lock().unwrap() = Some(busctl); + *TEST_DETECTED.lock().unwrap() = + Some(vec![Slicer { id: "prusa".into(), name: "PrusaSlicer".into(), command: vec![launcher], icon: None, prusa_major: Some(3) }]); + let mut s = imported_box(); + let out = dir.join("part.stl"); + let r = s.execute("file.save_mesh", &json!({"path": out, "slicer": "prusa", "single_instance": false})).unwrap(); + assert!(out.exists()); + assert!(r.get("slicer").is_some() && r.get("slicer_timeout").is_none(), "{r}"); + std::thread::sleep(std::time::Duration::from_millis(300)); + let lines: Vec = std::fs::read_to_string(&log).unwrap().lines().map(String::from).collect(); + // Started with no file, then sent the file, both with the flag (the preference could not take it away). + assert_eq!(lines, ["--single-instance".to_string(), format!("--single-instance {}", out.display())]); + assert!(std::fs::read_to_string(&count).unwrap().trim().parse::().unwrap() >= 3, "it looked until it was up"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn unsaved_designs_of_one_name_send_to_different_files_and_one_design_to_one() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("solidcraft-open-in-slicer-uid-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("fake-slicer"); + std::fs::write(&script, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let spec = script.to_string_lossy().into_owned(); + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut a, mut b) = (imported_box(), imported_box()); + assert_eq!((a.path.is_none(), a.doc.name == b.doc.name), (true, true)); + // Chosen list is process-wide: set it for this test, clear it before leaving. + crate::slicers::set_chosen_programs(std::slice::from_ref(&spec)); + let send = |s: &mut Session| { + s.execute("file.send_to_slicer", &json!({"slicer": spec, "bodies": ["Mesh"]})).map(|r| r["path"].as_str().unwrap().to_string()) + }; + let (a1, a2, b1) = (send(&mut a), send(&mut a), send(&mut b)); + crate::slicers::set_chosen_programs(&[]); + let (a1, a2, b1) = (a1.unwrap(), a2.unwrap(), b1.unwrap()); + assert_eq!(a1, a2, "sending again from one document keeps one file"); + assert_ne!(a1, b1, "two unsaved documents with the same name and bodies get their own files"); + std::fs::remove_dir_all(std::path::Path::new(&a1).parent().unwrap()).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// The first Save As gives the design a path, and with it a new file name, once. Later sends keep +/// the name that comes from the saved path. +#[cfg(unix)] +#[test] +fn the_first_save_as_changes_the_file_name_once() { + use std::os::unix::fs::PermissionsExt; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let dir = std::env::temp_dir().join(format!("solidcraft-open-in-slicer-saveas-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("fake-slicer"); + std::fs::write(&script, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let spec = script.to_string_lossy().into_owned(); + let mut s = imported_box(); + crate::slicers::set_chosen_programs(std::slice::from_ref(&spec)); + let send = |s: &mut Session| { + s.execute("file.send_to_slicer", &json!({"slicer": spec, "bodies": ["Mesh"]})).map(|r| r["path"].as_str().unwrap().to_string()) + }; + let before = [send(&mut s), send(&mut s)]; + // What Save As does to the session: the design now has a path. + s.path = Some("/designs/box.solidcraft".into()); + let after = [send(&mut s), send(&mut s), send(&mut s)]; + crate::slicers::set_chosen_programs(&[]); + let (before, after) = (before.map(Result::unwrap), after.map(Result::unwrap)); + assert_eq!(before[0], before[1], "unsaved: one file"); + assert_ne!(before[0], after[0], "Save As: the name changes"); + assert!(after.iter().all(|p| *p == after[0]), "saved: the same name every time"); + std::fs::remove_dir_all(std::path::Path::new(&after[0]).parent().unwrap()).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn send_to_slicer_writes_3mf_and_starts_the_program_with_it() { + use std::os::unix::fs::PermissionsExt; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut s = imported_box(); + let dir = std::env::temp_dir().join(format!("solidcraft-open-in-slicer-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (script, seen) = (dir.join("fake-slicer"), dir.join("seen")); + std::fs::write(&script, format!("#!/bin/sh\necho \"$@\" > {}\n", seen.display())).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + run(&mut s, "select.set", json!({"items":[{"type":"body","name":"Mesh"}]})); + // A program nobody chose is refused; once it is among the user's chosen ones it starts. + assert!(s.execute("file.send_to_slicer", &json!({"slicer": script})).is_err()); + crate::slicers::set_chosen_programs(&[script.to_string_lossy().into_owned()]); + let r = s.execute("file.send_to_slicer", &json!({"slicer": script})); + // Never leave the chosen list set for other tests in this process. + if r.is_err() { + crate::slicers::set_chosen_programs(&[]); + } + let r = r.unwrap(); + assert_eq!(r["format"], "3mf"); + let file = r["path"].as_str().unwrap().to_string(); + assert!(std::fs::read(&file).unwrap().starts_with(b"PK")); + for _ in 0..100 { + if seen.exists() && std::fs::metadata(&seen).unwrap().len() > 0 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + assert_eq!(std::fs::read_to_string(&seen).unwrap().trim(), file); + // Sending the same bodies again replaces the file; the same name in the same private folder. + let again = s.execute("file.send_to_slicer", &json!({"slicer": script})).unwrap(); + assert_eq!((again["path"].as_str(), again["numbered"].as_bool()), (Some(file.as_str()), Some(false))); + let stl = s.execute("file.send_to_slicer", &json!({"slicer": script, "format": "stl"})).unwrap(); + assert!(stl["path"].as_str().unwrap().ends_with(".stl")); + assert_ne!(stl["path"], r["path"]); + crate::slicers::set_chosen_programs(&[]); + std::fs::remove_dir_all(std::path::Path::new(&file).parent().unwrap()).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} + +type Uploads = std::sync::Arc)>>>; + +/// A session whose "host" records what it is handed and answers `answer`. +fn easyprint_host(s: &mut Session, answer: std::result::Result<(), String>) -> Uploads { + let seen = Uploads::default(); + let log = seen.clone(); + s.easyprint_upload = Some(std::sync::Arc::new(move |name, bytes| { + log.lock().unwrap().push((name.to_string(), bytes)); + answer.clone() + })); + seen +} + +#[test] +fn open_in_easyprint_hands_the_host_a_3mf_or_an_stl_that_reads_back() { + let mut s = imported_box(); + let seen = easyprint_host(&mut s, Ok(())); + let r = s.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Mesh"]})).unwrap(); + assert_eq!(r["uploading"], true); + s.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Mesh"], "format": "stl"})).unwrap(); + let seen = seen.lock().unwrap(); + assert_eq!((seen[0].0.ends_with(".3mf"), seen[1].0.ends_with(".stl")), (true, true), "{:?}", seen.iter().map(|u| &u.0).collect::>()); + assert!(seen[0].1.starts_with(b"PK"), "a 3MF is a zip"); + // A binary STL: 80-byte header, a count, 50 bytes a triangle, and a box has 12. + assert_eq!(seen[1].1.len(), 84 + 50 * 12); +} + +#[test] +fn open_in_easyprint_without_consent_a_host_or_bodies_uploads_nothing() { + let mut s = imported_box(); + let e = s.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Mesh"]})).unwrap_err().to_string(); + assert!(e.contains("not supported yet"), "{e}"); + let seen = easyprint_host(&mut s, Ok(())); + assert!(s.execute("file.open_in_easyprint", &json!({"bodies": ["Mesh"]})).is_err()); + assert!(s.execute("file.open_in_easyprint", &json!({"consent": false, "bodies": ["Mesh"]})).is_err()); + assert!(s.execute("file.open_in_easyprint", &json!({"consent": true})).is_err(), "nothing selected, nothing named"); + assert!(s.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Mesh"], "format": "step"})).is_err()); + assert!(seen.lock().unwrap().is_empty()); +} + +#[test] +fn open_in_easyprint_reports_a_host_that_cannot_start_and_a_model_over_the_limit() { + let mut s = imported_box(); + let seen = easyprint_host(&mut s, Err("no network".into())); + let e = s.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Mesh"]})).unwrap_err().to_string(); + assert!(e.contains("no network"), "{e}"); + // An STL is 50 bytes a triangle: 2.1 million of them are over 100 MB. + let mut doc = Document::default(); + doc.add_feature( + FeatureKind::MeshImport { + file: "big.stl".into(), + meshes: vec![MeshData { + name: "Big".into(), + positions: vec![0., 0., 0., 1., 0., 0., 0., 1., 0.].into(), + triangles: [0u32, 1, 2].repeat(2_100_000).into(), + color: None, + }], + }, + Some("Imported mesh"), + ) + .unwrap(); + let mut big = Session::new(doc); + let seen_big = easyprint_host(&mut big, Ok(())); + let e = big.execute("file.open_in_easyprint", &json!({"consent": true, "bodies": ["Big"], "format": "stl"})).unwrap_err().to_string(); + assert!(e.contains("100 MB at most"), "{e}"); + assert!(seen_big.lock().unwrap().is_empty()); + assert_eq!(seen.lock().unwrap().len(), 1); +} + fn insert_box_mesh(s: &mut Session, suffix: &str) -> (String, u64) { let mut source = imported_box(); let path = std::env::temp_dir().join(format!("solidcraft-convert-component-{}-{suffix}.stl", std::process::id())); diff --git a/crates/ui-egui/src/agent_chat/gate.rs b/crates/ui-egui/src/agent_chat/gate.rs index 0674e49b6..633d190b2 100644 --- a/crates/ui-egui/src/agent_chat/gate.rs +++ b/crates/ui-egui/src/agent_chat/gate.rs @@ -123,11 +123,22 @@ pub fn command(id: &str, params: &Value, undo_left: usize) -> Verdict { } // Files, and commands that replace or reload the whole design. let file_command = id.starts_with("file.") || id.starts_with("doc.") || matches!(id, "render.export" | "render.start"); + // The question says which program a send to a slicer would start. + let with_slicer = + |question: String| match params.get("slicer").and_then(Value::as_str).filter(|_| id.ends_with("save_mesh") || id.ends_with("send_to_slicer")) + { + Some(slicer) => format!("{question}, send to {}", slicer.chars().take(200).collect::()), + None => question, + }; + // The model leaves the machine: the user is asked, whatever the agent says about consent. + if id == "file.open_in_easyprint" { + return Verdict::Ask(format!("{id}, upload the model to Printables' servers (EasyPrint)")); + } if let Some(p) = names_a_file(id, params) { - return Verdict::Ask(format!("{id}: {p}")); + return Verdict::Ask(with_slicer(format!("{id}: {p}"))); } if file_command && !reads_only(id) { - return Verdict::Ask(id.to_string()); + return Verdict::Ask(with_slicer(id.to_string())); } // Undo past this turn's first change takes back the user's own work. if id == "edit.undo" && undo_left == 0 { @@ -253,6 +264,21 @@ mod tests { assert!(matches!(request("engine.batch", &batch, 0), Verdict::Ask(a) if a.contains("/etc/x"))); } + /// Saving a mesh or opening it in a slicer asks, and the question names the slicer. + #[test] + fn starting_a_slicer_asks_and_names_it() { + assert!( + matches!(exec("file.save_mesh", json!({"path": "a.stl", "slicer": "orca"})), Verdict::Ask(a) if a.contains("a.stl") && a.contains("send to orca")) + ); + assert!( + matches!(exec("file.send_to_slicer", json!({"slicer": "prusa", "bodies": ["Part"]})), Verdict::Ask(a) if a.ends_with("send to prusa")) + ); + assert!( + matches!(exec("file.open_in_easyprint", json!({"bodies": ["Part"], "consent": true})), Verdict::Ask(a) if a.contains("upload the model")) + ); + assert!(matches!(exec("file.send_to_slicer", json!({})), Verdict::Ask(_))); + } + /// `path`, `source` and friends are also geometry (curve ids, edges, occurrence ids): those /// are not files and must not stop a sweep or a pattern with a question. #[test] diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index f58e8f8d7..d2b06b86c 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -643,6 +643,7 @@ fn body_items(app: &SolveApp, bodies: &[String], browser: bool) -> Vec { act("ui.properties", "Properties", "measure").with(json!({ "bodies": names })), Item::sep(), act("ui.saveMesh", "Save As Mesh", "export").with(json!({ "bodies": names })), + act("ui.sendToSlicer", "Send to Slicer", "export").with(json!({ "bodies": names })).on(crate::dialogs_save_mesh::available(app)), act("ui.export", "Export…", "export").with(json!({ "bodies": names })), Item::sep(), act("ui.delete", "Delete", "delete").key("Del").with(json!({ "items": items })).on(!locked), @@ -798,7 +799,7 @@ fn occurrence_items(app: &SolveApp, path: &[u64]) -> Vec { item.id = "ui.isolateOccurrence".into(); item.params = Some(json!({"path": path})); } - "ui.export" | "ui.saveMesh" => item.params = Some(json!({"bodies": bodies})), + "ui.export" | "ui.saveMesh" | "ui.sendToSlicer" => item.params = Some(json!({"bodies": bodies})), "browser.expand_all" | "browser.collapse_all" => item.params = Some(json!({"path": path})), _ => {} } @@ -884,6 +885,11 @@ fn component_items(app: &SolveApp, id: u64) -> Vec { v.push(Item::sep()); v.push(act("ui.export", "Export…", "export").with(json!({ "bodies": names })).on(!bodies.is_empty())); v.push(act("ui.saveMesh", "Save As Mesh", "export").with(json!({ "bodies": names })).on(!bodies.is_empty())); + v.push( + act("ui.sendToSlicer", "Send to Slicer", "export") + .with(json!({ "bodies": names })) + .on(!bodies.is_empty() && crate::dialogs_save_mesh::available(app)), + ); v.push(Item::sep()); if id != 0 { v.push(cmd(app, "occurrence.copy", "Paste (Instance)").with(json!({ "component": id, "translate": [10, 10, 0] }))); @@ -1422,10 +1428,10 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { let _ = app.run("select.set", json!({ "items": items })); app.start("material.assign"); } - "ui.saveMesh" => { + "ui.saveMesh" | "ui.sendToSlicer" => { let items: Vec = bodies.iter().map(|b| json!({"type": "body", "name": b})).collect(); let _ = app.run("select.set", json!({ "items": items })); - app.start("file.save_mesh"); + app.start(if item.id == "ui.saveMesh" { "file.save_mesh" } else { "file.send_to_slicer" }); } "ui.exportDxf" => { if let Some(id) = id_of(&p, "sketch") { diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 17d08b7be..46ce1470c 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -15,7 +15,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> { }), Kind::Part(_) => Some("parts.insert"), Kind::PartSize(_) => Some("parts.resize"), - Kind::SaveMesh(_) => Some("file.save_mesh"), + Kind::SaveMesh(k) => Some(crate::dialogs_save_mesh::command_id(k)), Kind::ViewDxf { .. } => Some("file.export_view_dxf"), Kind::Sketch => Some("sketch.create"), Kind::SketchModify(k) => Some(crate::sketch_modify_ui::command(k)), diff --git a/crates/ui-egui/src/dialogs_save_mesh.rs b/crates/ui-egui/src/dialogs_save_mesh.rs index b53b33177..5599f994d 100644 --- a/crates/ui-egui/src/dialogs_save_mesh.rs +++ b/crates/ui-egui/src/dialogs_save_mesh.rs @@ -1,8 +1,10 @@ -//! The Save as mesh dialog (`file.save_mesh`): which bodies, the mesh format, and optionally a -//! slicer to open the saved file in. +//! The Save as mesh dialog (`file.save_mesh`): which bodies and the mesh format, then a file dialog. +//! Send to Slicer (`file.send_to_slicer`) shares the dialog without the format and with a slicer to +//! send the bodies to: it always asks, and pre-selects the slicer used last time. The list also has +//! a plain text row for EasyPrint (`file.open_in_easyprint`), which works in a browser too. //! //! Every place that saves a mesh opens this dialog: File › Export STL / Export 3MF, the Mesh tab, and the -//! Save As Mesh item of the body menus. The slicer list holds the programs the user added (kept +//! Save As Mesh item of the body menus. The slicer list (Send to Slicer only) holds the programs the user added (kept //! between runs, newest first), then the slicers found on this machine, then "Custom…", which asks //! for a program and adds it at the top; "Custom…" itself is never the selection. Pressing Delete //! over a program the user added removes it. @@ -23,6 +25,8 @@ use crate::theme::Tokens; /// The formats, as shown and as `file.save_mesh` names them. /// (label, `format` parameter, file extension). const FORMATS: [(&str, &str, &str); 3] = [("STL", "stl", "stl"), ("3MF", "3mf", "3mf"), ("3MF with face tags", "3mf-tagged", "3mf")]; +/// The list key of the EasyPrint row (no slicer has it: ids are words, programs are paths). +const EASYPRINT: &str = "easyprint"; /// How closely the mesh follows curved faces (#4747): the label and `file.save_mesh`'s `quality`. const QUALITIES: [(&str, &str); 3] = [("Standard", "standard"), ("Fine", "fine"), ("Finest", "finest")]; /// Edge of a slicer's icon in the list. @@ -34,9 +38,10 @@ const MAX_CUSTOM: usize = 24; #[derive(Clone, Debug, PartialEq)] pub struct SaveMesh { format: usize, - /// Index into [`QUALITIES`]. + /// Send to Slicer: only the bodies and the slicer are asked. + open: bool, + /// Index into [`QUALITIES`] (Save As Mesh; Send to Slicer has no quality row). quality: usize, - send: bool, /// The chosen slicer: an installed one's id, or the path of one the user added. slicer: String, /// The slicer list has not been read for this opening yet. @@ -81,6 +86,25 @@ impl SlicerMenu { self.custom = paths.iter().filter_map(|p| slicers::custom(p).map(|s| (p.clone(), s))).collect(); } + /// The list key for a remembered one: itself; or, for one remembered under another install + /// of the same slicer (`prusa` before it had several, `prusa#x` after an uninstall), the one + /// install of that slicer when there is exactly one; else none. + fn key_for(&self, key: &str) -> Option { + let entries = self.entries(); + if let Some(e) = entries.iter().find(|e| e.key == key) { + return Some(e.key.clone()); + } + // `prusa#x` remembered while there were two installs, and one left: the plain `prusa`. Only + // when it is exactly one: with several, nothing says which was meant, and another is not + // picked in its place (the choice then starts from the first, as when nothing was remembered). + let base = key.split('#').next().unwrap_or(key); + let mut same = entries.iter().filter(|e| !e.user && e.slicer.base_id() == base); + match (same.next(), same.next()) { + (Some(only), None) => Some(only.key.clone()), + _ => None, + } + } + fn entries(&self) -> Vec { let user = self.custom.iter().map(|(path, s)| Entry { key: path.clone(), slicer: s.clone(), user: true }); let found = self.detected.iter().map(|s| Entry { key: s.id.clone(), slicer: s.clone(), user: false }); @@ -88,18 +112,127 @@ impl SlicerMenu { } } -/// The dialog for `file.save_mesh`, with the choices of last time. +/// The dialog for `file.save_mesh` or `file.send_to_slicer`, with the choices of last time. pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { - if id != "file.save_mesh" { - return None; - } + let open = match id { + "file.save_mesh" => false, + "file.send_to_slicer" | "file.open_in_easyprint" => true, + _ => return None, + }; let p = &app.preferences; let format = FORMATS.iter().position(|f| f.1 == p.save_mesh_format).unwrap_or(0); + let slicer = match id { + "file.open_in_easyprint" => EASYPRINT.into(), + _ if open => p.send_slicer.clone(), + _ => String::new(), + }; let quality = QUALITIES.iter().position(|q| q.1 == p.save_mesh_quality).unwrap_or(0); - let kind = Kind::SaveMesh(SaveMesh { format, quality, send: p.save_mesh_send, slicer: p.save_mesh_slicer.clone(), stale: true }); + let kind = Kind::SaveMesh(SaveMesh { format, quality, open, slicer, stale: true }); Some((kind, vec![SelInput::new("Bodies", BODIES, true)])) } +/// Send to Slicer needs a way to start a program (a browser has none) or a way to reach EasyPrint. +pub fn available(app: &SolveApp) -> bool { + app.services.pick_program.is_some() || crate::easyprint_ui::available(app) +} + +/// A slicer that was started alone and is being waited for, off the UI thread, until it can take +/// the file (`Target::ready` in `slicers`). One at a time: a second send while it lasts does nothing. +pub struct SlicerWait { + done: std::sync::mpsc::Receiver, + /// The slicer that was started, found once. + slicer: slicers::Slicer, + /// What `file.send_to_slicer` answered when it wrote the file: the file that is sent, not + /// exported again, however the design has changed since. + result: Value, +} + +/// Look at `ready` on another thread until it says so or `limit` runs out; the answer arrives on the +/// channel. +fn spawn_wait( + ready: impl FnMut(std::time::Duration) -> bool + Send + 'static, + limit: std::time::Duration, + poll: std::time::Duration, +) -> std::sync::mpsc::Receiver { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(slicers::wait_until(ready, limit, poll)); + }); + rx +} + +/// Run `file.send_to_slicer` and report what happened. A slicer that has to be started first is +/// started and waited for in the background. +fn send_to_slicer(app: &mut SolveApp, params: Value) { + let _language = crate::i18n::scope(&app.preferences.language); + if let Some(wait) = &app.slicer_wait { + // Whatever was picked this time (another slicer, other bodies): nothing else is sent. + let line = crate::i18n::format("ui.slicer_still_starting", &[("slicer", &wait.slicer.name)]); + app.set_status(line, false); + return; + } + let mut params = params; + params["single_instance"] = json!(app.preferences.slicer_single_instance); + params["wait"] = json!("return"); + let Ok(result) = app.run("file.send_to_slicer", params.clone()) else { return }; + if result.get("starting").is_none() { + return report(app, &result); + } + begin_wait(app, params, &result); +} + +/// The command started the slicer on its own (`result.starting`): wait for it in the background. +fn begin_wait(app: &mut SolveApp, params: Value, result: &Value) { + let name = result.get("starting").and_then(Value::as_str).unwrap_or_default().to_string(); + let path = result.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + let spec = params["slicer"].as_str().unwrap_or_default().to_string(); + let Some(slicer) = slicers::resolve(&spec) else { + // Started, but it can't be found again to be sent the file: say so rather than go quiet. + app.set_status(crate::i18n::format("ui.slicer_lost", &[("slicer", &name), ("path", &path)]), true); + return; + }; + // Same reading as `slicers::wait_for_ready`: when `busctl` is missing or fails, send; when it is + // only slow, keep waiting. + let probe = slicer.clone(); + let done = + spawn_wait(move |left| probe.is_ready_within(left.min(slicers::PROBE_LIMIT)) != Some(false), slicers::READY_LIMIT, slicers::READY_POLL); + app.slicer_wait = Some(SlicerWait { done, slicer, result: result.clone() }); + app.set_status(crate::i18n::format("ui.slicer_starting", &[("slicer", &name)]), false); +} + +/// Per frame: when the slicer being waited for is ready, send the file; when the wait ran out, say so. +pub fn tick_wait(app: &mut SolveApp, ctx: &egui::Context) { + use std::sync::mpsc::TryRecvError; + let Some(wait) = app.slicer_wait.as_ref() else { return }; + let ready = match wait.done.try_recv() { + Err(TryRecvError::Empty) => return ctx.request_repaint_after(std::time::Duration::from_millis(200)), + Ok(ready) => ready, + Err(TryRecvError::Disconnected) => false, + }; + let Some(wait) = app.slicer_wait.take() else { return }; + let _language = crate::i18n::scope(&app.preferences.language); + let path = wait.result.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + if ready && path.is_empty() { + // Nothing was written to send (the answer had no path): say so, rather than open "". + app.set_status(crate::i18n::format("ui.slicer_no_file", &[("slicer", &wait.slicer.name)]), true); + } else if ready { + // The file is already written: open that one, rather than export the design again. + let mut result = wait.result; + if let Some(obj) = result.as_object_mut() { + obj.remove("starting"); + // After a start the file has to reach the instance that is now running, so the flag goes + // on whatever the preference says (the preference is for a slicer that was already up). + match wait.slicer.open(&path, true) { + Ok(()) => obj.insert("slicer".into(), json!(wait.slicer.name)), + Err(e) => obj.insert("slicer_error".into(), json!(e)), + }; + } + report(app, &result); + } else { + app.set_status(crate::i18n::format("ui.slicer_no_response", &[("slicer", &wait.slicer.name), ("path", &path)]), true); + } +} + /// Open the dialog with `format` (`stl`, `3mf` or `3mf-tagged`) chosen, whatever was used last: /// File › Export STL… and Export 3MF…. The user can still change it in the dialog. pub fn start_with_format(app: &mut SolveApp, format: &str) { @@ -141,6 +274,13 @@ fn decode(bytes: &[u8]) -> Option { Some(egui::ColorImage::from_rgba_unmultiplied([SIDE as usize, SIDE as usize], small.as_raw())) } +/// `text` on one line, ending in … when it is wider than `width`. +fn fitted(ui: &egui::Ui, text: &str, width: f32, color: Color32) -> std::sync::Arc { + let mut job = egui::text::LayoutJob::simple_singleline(text.to_string(), egui::FontId::proportional(Tokens::get().font_button), color); + job.wrap = egui::text::TextWrapping::truncate_at_width(width.max(0.0)); + ui.painter().layout_job(job) +} + /// An icon, or the first letter of the name on a tile when there is none. fn paint_icon(ui: &egui::Ui, rect: egui::Rect, tex: Option, name: &str) { match tex { @@ -164,28 +304,28 @@ fn paint_icon(ui: &egui::Ui, rect: egui::Rect, tex: Option, nam /// The rows after the Bodies input; true when Enter was pressed in a field. pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) -> bool { + if !k.open { + choice_row(ui, "Format", "sm_format", &mut k.format, &FORMATS.map(|f| f.0)); + choice_row(ui, "Quality", "sm_quality", &mut k.quality, &QUALITIES.map(|q| q.0)); + return false; + } if k.stale { // Look at the machine once per opening, then settle on a slicer that exists. k.stale = false; app.slicer_menu.picked = None; app.slicer_menu.refresh(&app.preferences.custom_slicers); let entries = app.slicer_menu.entries(); - if !entries.iter().any(|e| e.key == k.slicer) { - k.slicer = entries.first().map(|e| e.key.clone()).unwrap_or_default(); - } - k.send &= !entries.is_empty(); + let easyprint = crate::easyprint_ui::available(app); + k.slicer = if easyprint && k.slicer == EASYPRINT { + EASYPRINT.into() + } else { + app.slicer_menu + .key_for(&k.slicer) + .or_else(|| entries.first().map(|e| e.key.clone())) + .or_else(|| easyprint.then(|| EASYPRINT.to_string())) + .unwrap_or_default() + }; } - choice_row(ui, "Format", "sm_format", &mut k.format, &FORMATS.map(|f| f.0)); - choice_row(ui, "Quality", "sm_quality", &mut k.quality, &QUALITIES.map(|q| q.0)); - - // A browser has no installed programs to send a file to. - if app.services.pick_program.is_none() { - k.send = false; - return false; - } - form_row(ui, "Send to slicer", |ui| { - crate::ui_kit::checkbox(ui, "", &mut k.send); - }); form_row(ui, "Slicer", |ui| { if let Some(path) = app.slicer_menu.picked.take() { @@ -195,7 +335,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) -> bool { } } let choosing = app.file_picker_busy(); - ui.add_enabled_ui(k.send && !choosing, |ui| slicer_combo(app, ui, k)); + ui.add_enabled_ui(!choosing, |ui| slicer_combo(app, ui, k)); }); false } @@ -205,10 +345,20 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) { let ctx = ui.ctx().clone(); let current = entries.iter().find(|e| e.key == k.slicer); let pad = "\u{2003}\u{2003}"; - let text = current.map_or_else(|| crate::i18n::tr_label("No slicer found").to_string(), |e| format!("{pad}{}", e.slicer.name)); + let easyprint = crate::easyprint_ui::available(app); + let easyprint_label = crate::i18n::tr("ui.easyprint_row"); + let text = match current { + Some(e) => format!("{pad}{}", e.slicer.name), + None if easyprint && k.slicer == EASYPRINT => format!("{pad}{easyprint_label}"), + None => crate::i18n::tr_label("No slicer found").to_string(), + }; let mut pick_custom = false; let mut delete: Option = None; let mut chosen: Option = None; + let name = current.map(|e| e.slicer.name.clone()); + // A long name ends in … instead of wrapping onto a second line; the full one is in the tooltip. + let wrap = ui.style().wrap_mode; + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); let r = crate::ui_kit::dropdown_menu(ui, "sm_slicer", &text, |ui| { let frame = ctx.cumulative_frame_nr(); ctx.data_mut(|d| d.insert_temp(egui::Id::new("sc_slicer_popup"), frame)); @@ -221,29 +371,45 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) { ui.painter().rect_filled(rect, Tokens::get().radius_sm / 2, fill); } paint_icon(ui, egui::Rect::from_min_size(rect.left_center() + vec2(3.0, -ICON / 2.0), vec2(ICON, ICON)), tex, &e.slicer.name); - ui.painter().text( - rect.left_center() + vec2(ICON + 9.0, 0.0), - egui::Align2::LEFT_CENTER, - &e.slicer.name, - egui::FontId::proportional(crate::theme::Tokens::get().font_button), - Tokens::get().text, - ); + let text = fitted(ui, &e.slicer.name, rect.width() - (ICON + 9.0) - 6.0, Tokens::get().text); + let (elided, at) = (text.elided, rect.left_center() + vec2(ICON + 9.0, -text.size().y / 2.0)); + ui.painter().galley(at, text, Tokens::get().text); crate::scenario::publish_handle(&format!("dialog:Slicer:{}", e.slicer.name), rect.center()); if e.user { let hint = crate::i18n::format("ui.slicer_delete_tip", &[("program", e.slicer.command.first().map_or("", String::as_str))]); - resp.clone().on_hover_text(hint); + resp.clone().on_hover_text(if elided { format!("{}\n{hint}", e.slicer.name) } else { hint }); if resp.hovered() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete)) { delete = Some(e.key.clone()); } + } else if elided { + resp.clone().on_hover_text(&e.slicer.name); } if resp.clicked() { chosen = Some(e.key.clone()); ui.close(); } } - if !entries.is_empty() { + if easyprint { + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + if resp.hovered() || k.slicer == EASYPRINT { + let fill = if resp.hovered() { Tokens::get().hover } else { Tokens::get().selected_bg }; + ui.painter().rect_filled(rect, 2.0, fill); + } + let text = fitted(ui, easyprint_label, rect.width() - (ICON + 9.0) - 6.0, Tokens::get().text); + ui.painter().galley(rect.left_center() + vec2(ICON + 9.0, -text.size().y / 2.0), text, Tokens::get().text); + crate::scenario::publish_handle("dialog:Slicer:EasyPrint", rect.center()); + if resp.clicked() { + chosen = Some(EASYPRINT.to_string()); + ui.close(); + } + } + if !entries.is_empty() || easyprint { ui.separator(); } + // A browser has no program to add. + if app.services.pick_program.is_none() { + return; + } let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); if resp.hovered() { ui.painter().rect_filled(rect, Tokens::get().radius_sm / 2, Tokens::get().hover); @@ -261,6 +427,10 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) { ui.close(); } }); + ui.style_mut().wrap_mode = wrap; + if let Some(name) = name { + r.clone().on_hover_text(name); + } if let Some(e) = current { let tex = icon(&mut app.slicer_menu, &ctx, e); let rect = r.rect; @@ -296,12 +466,13 @@ fn add_custom(app: &mut SolveApp, path: &str) -> Result<(), String> { Ok(()) } -/// What the Save (or Send) button asks `file.save_mesh` to do, without the file name. +/// What the Save (or Send) button asks `file.save_mesh` or `file.send_to_slicer` to do; Save is +/// without the file name. pub fn commands(k: &SaveMesh, inputs: &[SelInput]) -> Result, String> { let format = FORMATS.get(k.format).map_or("stl", |f| f.1); let mut p = json!({ "format": format }); - // Standard is the command's own default, so it is left out. - if let Some((_, quality)) = QUALITIES.get(k.quality).filter(|_| k.quality > 0) { + // Standard is the command's own default, so it is left out. Sending has no quality row. + if let Some((_, quality)) = QUALITIES.get(k.quality).filter(|_| k.quality > 0 && !k.open) { p["quality"] = json!(quality); } let names = crate::selection::items(inputs, 0).body_names(); @@ -309,11 +480,16 @@ pub fn commands(k: &SaveMesh, inputs: &[SelInput]) -> Result bool { !crate::selection::items(inputs, 0).body_names().is_empty() } -/// The button's label: Save, or Send when the file goes to a slicer. -pub fn button(k: &SaveMesh) -> &'static str { - if k.send { "Send" } else { "Save" } +/// The command the dialog is for: its name is the dialog's title. +pub fn command_id(k: &SaveMesh) -> &'static str { + if k.open { "file.send_to_slicer" } else { "file.save_mesh" } } -/// Save: ask for a file name and write the file. Send: write it to a temporary file and start the +/// The button's label: Save, or Send when the file goes to a slicer. +pub fn button(k: &SaveMesh) -> &'static str { + if k.open { "Send" } else { "Save" } +} + +/// Save: ask for a file name and write the file. Send: write it to the slicer folder and start the /// slicer with it, with no file dialog. pub fn run(app: &mut SolveApp, k: &SaveMesh, inputs: &[SelInput]) -> Result<(), String> { let (_, params) = commands(k, inputs)?.into_iter().next().ok_or("nothing to save")?; + if k.open { + app.preferences.send_slicer = k.slicer.clone(); + if k.slicer == EASYPRINT { + crate::easyprint_ui::request(app, params); + } else { + send_to_slicer(app, params); + } + return Ok(()); + } let (format, ext) = FORMATS.get(k.format).map_or(("stl", "stl"), |f| (f.1, f.2)); let name = crate::selection::items(inputs, 0).body_names().first().cloned().unwrap_or_else(|| app.session.doc.name.clone()); - let p = &mut app.preferences; - p.save_mesh_format = format.into(); - p.save_mesh_quality = QUALITIES.get(k.quality).map_or("standard", |q| q.1).into(); - p.save_mesh_send = k.send; - if !k.slicer.is_empty() { - p.save_mesh_slicer = k.slicer.clone(); - } - if k.send { - let dir = std::env::temp_dir().join("solidcraft-slicer"); - std::fs::create_dir_all(&dir) - .map_err(|e| crate::i18n::format("ui.save_mesh_temp_failed", &[("folder", &dir.display().to_string()), ("error", &e.to_string())]))?; - let file: String = name.chars().map(|c| if c.is_alphanumeric() || "-_. ".contains(c) { c } else { '_' }).collect(); - save(app, params, &dir.join(format!("{file}.{ext}")).to_string_lossy()); - } else { - // The file dialog answers later; the dialog closes meanwhile, as for every export. - app.pick_save(&format!("{name}.{ext}"), &[ext], move |app, path| { - if let Some(path) = path { - save(app, params, &path); - } - }); - } + app.preferences.save_mesh_format = format.into(); + app.preferences.save_mesh_quality = QUALITIES.get(k.quality).map_or("standard", |q| q.1).into(); + // The file dialog answers later; the dialog closes meanwhile, as for every export. + app.pick_save(&format!("{name}.{ext}"), &[ext], move |app, path| { + if let Some(path) = path { + save(app, params, &path); + } + }); Ok(()) } @@ -364,11 +541,349 @@ fn save(app: &mut SolveApp, mut params: Value, path: &str) { let _language = crate::i18n::scope(&app.preferences.language); params["path"] = json!(path); let Ok(result) = app.run("file.save_mesh", params) else { return }; + report(app, &result); +} + +/// The status line after a save or a send. +fn report(app: &mut SolveApp, result: &Value) { + let path = result.get("path").and_then(Value::as_str).unwrap_or_default(); match result.get("slicer_error").and_then(Value::as_str) { Some(e) => app.set_status(e.to_string(), true), None => match result.get("slicer").and_then(Value::as_str) { - Some(s) => app.set_status(crate::i18n::format("ui.sent_to_slicer", &[("slicer", s)]), false), + Some(s) => { + let mut line = match (result.get("numbered").and_then(Value::as_bool), std::path::Path::new(path).file_name()) { + (Some(true), Some(file)) => crate::i18n::format("ui.sent_to_slicer_copy", &[("slicer", s), ("file", &file.to_string_lossy())]), + _ => crate::i18n::format("ui.sent_to_slicer", &[("slicer", s)]), + }; + // Said once: sending the same bodies again overwrites the file the slicer has open. + if result.get("numbered").is_some() && !std::mem::replace(&mut app.preferences.slicer_resend_hint_seen, true) { + line = format!("{line}. {}", crate::i18n::tr("ui.slicer_resend_hint")); + } + if result.get("stl_fallback").and_then(Value::as_bool) == Some(true) { + line = format!("{line}. {}", crate::i18n::tr("ui.slicer_stl_fallback")); + } + app.set_status(line, false); + } None => app.set_status(crate::i18n::format("ui.saved_to", &[("path", path)]), false), }, } } + +#[cfg(test)] +mod tests { + use super::*; + use solidcraft_engine::Sel; + + #[test] + fn without_a_program_dialog_send_to_slicer_is_unavailable_and_starts_nothing() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert!(app.services.pick_program.is_none()); + assert!(!available(&app)); + app.preferences.send_slicer = "prusa".into(); + app.start("file.send_to_slicer"); + assert!(app.dialog.is_none(), "no dialog to choose a slicer in"); + assert!(matches!(&app.status, Some((_, _, true)))); + app.services.pick_program = Some(Box::new(|| Box::pin(async { None }))); + assert!(available(&app)); + } + + /// An app with a box in it, `fake-slicer` (a script that writes its arguments to `seen`) among the + /// user's programs, and the parameters Send to Slicer would send. + #[cfg(unix)] + fn app_with_fake_slicer(tag: &str) -> (SolveApp, std::path::PathBuf, Value) { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("solidcraft-slicer-wait-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (script, seen) = (dir.join("fake-slicer"), dir.join("seen")); + std::fs::write(&script, format!("#!/bin/sh\necho \"$@\" >> {}\n", seen.display())).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"})).unwrap(); + app.preferences.custom_slicers = vec![script.to_string_lossy().into_owned()]; + let params = json!({"slicer": script, "bodies": ["Part"], "wait": "no"}); + (app, seen, params) + } + + #[cfg(unix)] + fn sent(seen: &std::path::Path) -> usize { + for _ in 0..100 { + if seen.exists() && std::fs::metadata(seen).map(|m| m.len() > 0).unwrap_or(false) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + std::fs::read_to_string(seen).map(|t| t.lines().count()).unwrap_or(0) + } + + #[cfg(unix)] + #[test] + fn the_menu_entries_always_ask_and_a_script_with_a_slicer_does_not() { + let (mut app, seen, mut params) = app_with_fake_slicer("ask"); + app.services.pick_program = Some(Box::new(|| Box::pin(async { None }))); + app.run("select.set", json!({"items": [{"type": "body", "name": "Part"}]})).unwrap(); + // Last time's slicer is remembered and bodies are selected: still the picker, with it pre-selected. + let key = params["slicer"].as_str().unwrap().to_string(); + app.preferences.send_slicer = key.clone(); + app.start("file.send_to_slicer"); + let Some(Kind::SaveMesh(k)) = app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("no picker opened") }; + assert!(k.open); + assert_eq!(k.slicer, key, "pre-selected"); + assert!(!seen.exists(), "nothing sent until the user confirms"); + // A script names the slicer: no dialog, the file goes. + app.dialog = None; + params["wait"] = json!("no"); + app.run("file.send_to_slicer", params).unwrap(); + assert!(app.dialog.is_none()); + assert_eq!(sent(&seen), 1); + let _ = std::fs::remove_dir_all(seen.parent().unwrap()); + solidcraft_engine::slicers::set_chosen_programs(&[]); + } + + #[cfg(unix)] + #[test] + fn a_started_slicer_is_waited_for_and_then_sent_the_file_once() { + let ctx = egui::Context::default(); + let (mut app, seen, params) = app_with_fake_slicer("ready"); + // Ready on the third look; a second click while it waits starts and sends nothing. + let mut looks = 0; + let done = spawn_wait( + move |_| { + looks += 1; + looks == 3 + }, + std::time::Duration::from_secs(5), + std::time::Duration::from_millis(5), + ); + let slicer = slicers::custom(params["slicer"].as_str().unwrap()).unwrap(); + app.slicer_wait = Some(SlicerWait { done, slicer, result: json!({"path": "/p"}) }); + send_to_slicer(&mut app, params); + assert!(app.slicer_wait.is_some(), "still the one wait"); + let status = app.status.clone().unwrap(); + assert!(!status.2 && status.0.contains("Still waiting") && status.0.contains("Nothing else was sent"), "{status:?}"); + assert!(status.0.contains(&app.slicer_wait.as_ref().unwrap().slicer.name), "names the slicer being waited for: {status:?}"); + assert!(!seen.exists(), "the second click sent nothing"); + for _ in 0..200 { + tick_wait(&mut app, &ctx); + if app.slicer_wait.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.slicer_wait.is_none()); + assert_eq!(sent(&seen), 1, "one send"); + assert!(app.status.as_ref().is_some_and(|(_, _, error)| !*error), "{:?}", app.status); + let _ = std::fs::remove_dir_all(seen.parent().unwrap()); + solidcraft_engine::slicers::set_chosen_programs(&[]); + } + + #[test] + fn a_started_slicer_that_can_not_be_found_again_is_reported() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let result = json!({"starting": "Ghost Slicer", "path": "/tmp/part.3mf"}); + begin_wait(&mut app, json!({"slicer": "no such slicer anywhere", "bodies": ["Part"]}), &result); + assert!(app.slicer_wait.is_none()); + let status = app.status.clone().unwrap(); + assert!(status.2 && status.0.contains("Ghost Slicer") && status.0.contains("/tmp/part.3mf"), "{status:?}"); + } + + #[cfg(unix)] + #[test] + fn the_file_that_was_written_is_sent_whatever_happens_to_the_design_meanwhile() { + let ctx = egui::Context::default(); + let (mut app, seen, params) = app_with_fake_slicer("same-file"); + let dir = seen.parent().unwrap().to_path_buf(); + let file = dir.join("part.3mf"); + std::fs::write(&file, b"as exported").unwrap(); + let slicer = slicers::custom(params["slicer"].as_str().unwrap()).unwrap(); + let done = spawn_wait(|_| true, std::time::Duration::from_secs(5), std::time::Duration::from_millis(5)); + let result = json!({"path": file, "numbered": false, "starting": slicer.name}); + app.slicer_wait = Some(SlicerWait { done, slicer, result }); + // The design changes while the slicer starts: a body is added and the first one removed. + app.run("solid.box", json!({"length": 5, "width": 5, "height": 5, "body_name": "Late", "operation": "new"})).unwrap(); + app.run("solid.remove", json!({"bodies": ["Part"]})).unwrap(); + let revision = app.session.revision; + for _ in 0..200 { + tick_wait(&mut app, &ctx); + if app.slicer_wait.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(sent(&seen), 1); + assert_eq!(std::fs::read_to_string(&seen).unwrap().trim(), file.to_string_lossy(), "the file already written"); + assert_eq!(std::fs::read(&file).unwrap(), b"as exported", "not written again"); + assert_eq!(app.session.revision, revision, "no command ran for the send"); + let mut names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["fake-slicer", "part.3mf", "seen"], "no second file"); + assert!(app.status.as_ref().is_some_and(|(m, _, error)| !*error && m.contains("Sent")), "{:?}", app.status); + let _ = std::fs::remove_dir_all(dir); + solidcraft_engine::slicers::set_chosen_programs(&[]); + } + + #[cfg(unix)] + #[test] + fn the_launcher_gets_the_flag_on_a_send_and_after_a_start_even_when_the_preference_is_off() { + use std::os::unix::fs::PermissionsExt; + let ctx = egui::Context::default(); + let dir = std::env::temp_dir().join(format!("solidcraft-slicer-flag-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + // The launcher is recognised by its command, and PrusaSlicer by its name. + let folder = dir.join("slic3r-app-launcher"); + std::fs::create_dir_all(&folder).unwrap(); + let (script, seen) = (folder.join("PrusaSlicer"), dir.join("seen")); + std::fs::write(&script, format!("#!/bin/sh\necho \"$@\" >> {}\n", seen.display())).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"})).unwrap(); + let spec = script.to_string_lossy().into_owned(); + app.preferences.custom_slicers = vec![spec.clone()]; + app.preferences.slicer_single_instance = false; + // A normal send with the preference off: this launcher still gets the flag, it can't hand a file over without. + app.run("file.send_to_slicer", json!({"slicer": spec, "bodies": ["Part"], "wait": "no", "single_instance": false})).unwrap(); + assert_eq!(sent(&seen), 1); + assert!(std::fs::read_to_string(&seen).unwrap().starts_with("--single-instance "), "{:?}", std::fs::read_to_string(&seen)); + // The send that follows a start: the flag, preference or not. + let slicer = slicers::custom(&spec).unwrap(); + assert!(slicer.waits_for_ready().is_some()); + let done = spawn_wait(|_| true, std::time::Duration::from_secs(5), std::time::Duration::from_millis(5)); + app.slicer_wait = Some(SlicerWait { done, slicer, result: json!({"path": "/tmp/part.3mf"}) }); + for _ in 0..200 { + tick_wait(&mut app, &ctx); + if app.slicer_wait.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + for _ in 0..100 { + if std::fs::read_to_string(&seen).map(|t| t.lines().count()).unwrap_or(0) >= 2 { + break; + } + std::thread::sleep(std::time::Duration::from_millis(30)); + } + assert_eq!(sent(&seen), 2); + let second = std::fs::read_to_string(&seen).unwrap().lines().nth(1).unwrap().to_string(); + assert_eq!(second, "--single-instance /tmp/part.3mf"); + let _ = std::fs::remove_dir_all(dir); + solidcraft_engine::slicers::set_chosen_programs(&[]); + } + + #[cfg(unix)] + #[test] + fn a_ready_slicer_with_no_file_to_send_is_reported_and_nothing_is_started() { + let ctx = egui::Context::default(); + let (mut app, seen, params) = app_with_fake_slicer("nofile"); + let slicer = slicers::custom(params["slicer"].as_str().unwrap()).unwrap(); + let done = spawn_wait(|_| true, std::time::Duration::from_secs(5), std::time::Duration::from_millis(5)); + app.slicer_wait = Some(SlicerWait { done, slicer, result: json!({"starting": "Fake"}) }); + for _ in 0..200 { + tick_wait(&mut app, &ctx); + if app.slicer_wait.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.slicer_wait.is_none()); + let status = app.status.clone().unwrap(); + assert!(status.2 && status.0.contains("no file"), "{status:?}"); + std::thread::sleep(std::time::Duration::from_millis(100)); + assert!(!seen.exists(), "the slicer was not started with an empty path"); + let _ = std::fs::remove_dir_all(seen.parent().unwrap()); + solidcraft_engine::slicers::set_chosen_programs(&[]); + } + + #[cfg(unix)] + #[test] + fn a_slicer_that_never_comes_up_is_reported_and_nothing_is_sent() { + let ctx = egui::Context::default(); + let (mut app, seen, params) = app_with_fake_slicer("late"); + let done = spawn_wait(|_| false, std::time::Duration::from_millis(30), std::time::Duration::from_millis(5)); + let slicer = slicers::custom(params["slicer"].as_str().unwrap()).unwrap(); + app.slicer_wait = Some(SlicerWait { done, slicer, result: json!({"path": "/tmp/part.3mf"}) }); + for _ in 0..400 { + tick_wait(&mut app, &ctx); + if app.slicer_wait.is_none() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.slicer_wait.is_none()); + let status = app.status.clone().unwrap(); + assert!(status.2 && status.0.contains("/tmp/part.3mf"), "{status:?}"); + assert!(!seen.exists()); + let _ = std::fs::remove_dir_all(seen.parent().unwrap()); + } + + #[test] + fn a_long_slicer_name_is_cut_with_an_ellipsis_to_fit_its_row() { + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let long = "PrusaSlicer (Flatpak, master, a rather long install label)"; + let galley = fitted(ui, long, 120.0, Color32::WHITE); + assert!(galley.elided, "does not fit, so it is cut"); + assert!(galley.size().x <= 120.0 + 0.5, "{}", galley.size().x); + assert_eq!(galley.rows.len(), 1, "one line"); + let short = fitted(ui, "OrcaSlicer", 120.0, Color32::WHITE); + assert!(!short.elided && short.size().x <= 120.0); + }); + output.textures_delta.clear(); + } + + #[test] + fn a_remembered_install_that_is_gone_falls_back_to_the_same_slicer() { + let prusa = |id: &str| slicers::Slicer { + id: id.into(), + name: "PrusaSlicer".into(), + command: vec!["prusa-slicer".into()], + icon: None, + prusa_major: None, + }; + let orca = + slicers::Slicer { id: "orca".into(), name: "OrcaSlicer".into(), command: vec!["orca-slicer".into()], icon: None, prusa_major: None }; + let menu = |detected: Vec| SlicerMenu { detected, ..Default::default() }; + // Two installs when it was remembered, one (now plain) left. + let lone = menu(vec![orca.clone(), prusa("prusa")]); + assert_eq!(lone.key_for("prusa#prusaslicer").as_deref(), Some("prusa")); + assert_eq!(lone.key_for("prusa").as_deref(), Some("prusa")); + // Remembered plain, now two: which of them was meant is not known, so none is taken; an exact key is itself. + let two = menu(vec![prusa("prusa#a"), prusa("prusa#b")]); + assert_eq!(two.key_for("prusa"), None); + assert_eq!(two.key_for("prusa#b").as_deref(), Some("prusa#b")); + // An AppImage remembered when it was alone, now two versions side by side: not remembered. + let side_by_side = menu(vec![prusa("prusa#appimage-1f-prusaslicer29"), prusa("prusa#appimage-1f-prusaslicer210")]); + assert_eq!(side_by_side.key_for("prusa#appimage-1f"), None); + // And after an upgrade, the id is the same and is found. + assert_eq!(menu(vec![prusa("prusa#appimage-1f")]).key_for("prusa#appimage-1f").as_deref(), Some("prusa#appimage-1f")); + // A different slicer is never picked for it. + assert_eq!(menu(vec![orca]).key_for("prusa#x"), None); + } + + #[test] + fn send_to_slicer_asks_for_bodies_and_a_slicer_but_not_a_format() { + let k = SaveMesh { format: 0, quality: 0, open: true, slicer: "prusa".into(), stale: false }; + let mut input = SelInput::new("Bodies", BODIES, true); + assert!(commands(&k, std::slice::from_ref(&input)).is_err()); + input.items = vec![Sel::Body { name: "Part".into() }]; + let cmds = commands(&k, std::slice::from_ref(&input)).unwrap(); + assert_eq!(cmds, [("file.send_to_slicer".to_string(), json!({"slicer": "prusa", "bodies": ["Part"], "format": "3mf"}))]); + // Save as mesh is a plain export in the chosen format: no slicer in it, whatever was set. + let save = SaveMesh { format: 2, open: false, slicer: "prusa".into(), ..k.clone() }; + let (id, p) = commands(&save, std::slice::from_ref(&input)).unwrap().remove(0); + assert_eq!((id.as_str(), p["format"].as_str(), p.get("slicer")), ("file.save_mesh", Some("3mf-tagged"), None)); + assert_eq!(button(&save), "Save"); + assert_eq!(button(&k), "Send"); + assert!(commands(&SaveMesh { slicer: String::new(), ..k }, &[input]).is_err()); + } + + #[test] + fn a_remembered_quality_goes_to_save_but_not_to_send() { + let mut input = SelInput::new("Bodies", BODIES, true); + input.items = vec![Sel::Body { name: "Part".into() }]; + let k = SaveMesh { format: 0, quality: 2, open: true, slicer: "prusa".into(), stale: false }; + let (_, sent) = commands(&k, std::slice::from_ref(&input)).unwrap().remove(0); + assert_eq!(sent.get("quality"), None, "sending has no quality row: the default applies"); + let (_, saved) = commands(&SaveMesh { open: false, ..k }, &[input]).unwrap().remove(0); + assert_eq!(saved["quality"], "finest"); + } +} diff --git a/crates/ui-egui/src/easyprint_ui.rs b/crates/ui-egui/src/easyprint_ui.rs new file mode 100644 index 000000000..5bd9bad80 --- /dev/null +++ b/crates/ui-egui/src/easyprint_ui.rs @@ -0,0 +1,236 @@ +//! Open with EasyPrint: the UI side of `file.open_in_easyprint`. The command exports the bodies +//! and gives them to the host (`Services::easyprint_upload`), which uploads them to Printables +//! and answers on a channel; this opens the answer in the browser, or says why not. The model +//! leaves the machine, so the first time asks the user (a preference remembers the answer). + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use serde_json::{Value, json}; + +use crate::SolveApp; +use crate::ui_kit; + +/// What the host answers: the address to open, or why the upload failed. +pub type Answer = Result; + +/// Starts the upload of a file (its name, its bytes) and answers on the channel later. +pub type Upload = Arc, Sender) + Send + Sync>; + +/// The upload in flight, and the question waiting for an answer. +pub struct State { + tx: Sender, + rx: Mutex>, + /// An upload has been started and not answered. One at a time. + busy: Arc, + /// The parameters of a send waiting for the user to agree to the upload. + ask: Option, + /// The last address opened (a step of a scenario runs several frames, so tests can't catch it). + #[cfg(test)] + opened: Option, +} + +impl Default for State { + fn default() -> Self { + let (tx, rx) = channel(); + Self { + tx, + rx: Mutex::new(rx), + busy: Arc::default(), + ask: None, + #[cfg(test)] + opened: None, + } + } +} + +/// Give the session the host's way to upload (call after the services are set). +pub fn install(app: &mut SolveApp) { + let Some(upload) = app.services.easyprint_upload.clone() else { return }; + let (tx, busy) = (app.easyprint.tx.clone(), app.easyprint.busy.clone()); + app.session.easyprint_upload = Some(Arc::new(move |name, bytes| { + if busy.swap(true, Ordering::SeqCst) { + return Err("the last model is still being uploaded to Printables".into()); + } + upload(name, bytes, tx.clone()); + Ok(()) + })); +} + +/// Whether this host can upload to EasyPrint. +pub fn available(app: &SolveApp) -> bool { + app.services.easyprint_upload.is_some() +} + +/// Send the bodies of `params` to EasyPrint: at once when the user has agreed before, else after +/// asking. +pub fn request(app: &mut SolveApp, params: Value) { + if app.preferences.easyprint_consent { + return go(app, params); + } + app.easyprint.ask = Some(params); +} + +fn go(app: &mut SolveApp, mut params: Value) { + let _language = crate::i18n::scope(&app.preferences.language); + params["consent"] = json!(true); + if app.run("file.open_in_easyprint", params).is_ok() { + app.set_status(crate::i18n::tr("ui.easyprint_uploading"), false); + } +} + +/// Per frame: open the answer of an upload, or report its failure. +pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { + let answer = app.easyprint.rx.lock().ok().and_then(|rx| rx.try_recv().ok()); + let Some(answer) = answer else { + if app.easyprint.busy.load(Ordering::SeqCst) { + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + } + return; + }; + app.easyprint.busy.store(false, Ordering::SeqCst); + let _language = crate::i18n::scope(&app.preferences.language); + match answer { + Ok(url) => { + #[cfg(test)] + { + app.easyprint.opened = Some(url.clone()); + } + ctx.open_url(egui::OpenUrl::new_tab(url)); + app.set_status(crate::i18n::tr("ui.easyprint_opened"), false); + } + Err(e) => app.set_status(crate::i18n::format("ui.easyprint_failed", &[("error", &e)]), true), + } +} + +/// The question: what is uploaded where, for how long. +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + let Some(params) = app.easyprint.ask.clone() else { return }; + let _language = crate::i18n::scope(&app.preferences.language); + let (closed, action) = ui_kit::Confirm::new(egui::Id::new("sc_easyprint_confirm"), "mesh_export", crate::i18n::tr_label("Open with EasyPrint")) + .actions("Upload", "Cancel", None) + .show(ctx, true, |ui| { + ui_kit::text(ui, crate::i18n::tr("ui.easyprint_consent"), ui_kit::Text::Report("easyprint_consent", false)); + }); + match action { + ui_kit::Action::Ok => { + app.easyprint.ask = None; + app.preferences.easyprint_consent = true; + go(app, params); + } + ui_kit::Action::Cancel => app.easyprint.ask = None, + _ if closed => app.easyprint.ask = None, + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scenario::Harness; + use serde_json::json; + use std::sync::Mutex; + + type Names = Arc>>; + + /// A host that records each upload's file name and answers `answer` at once, with the app set + /// up for it and a box selected. + fn harness(answer: Answer) -> (Harness, Names) { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length": 2, "width": 3, "height": 4})).unwrap(); + h.app.run("select.set", json!({"items": [solidcraft_engine::Sel::Body { name: "Body1".into() }]})).unwrap(); + let names = Names::default(); + let log = names.clone(); + h.app.services.easyprint_upload = Some(Arc::new(move |name, _bytes, done| { + log.lock().unwrap().push(name.to_string()); + done.send(answer.clone()).unwrap(); + })); + install(&mut h.app); + (h, names) + } + + /// A few frames, then the address the app opened since the last call. + fn opened(h: &mut Harness) -> Option { + h.frames(4); + h.app.easyprint.opened.take() + } + + fn status(h: &Harness) -> (String, bool) { + h.app.status.clone().map(|(text, _, error)| (text, error)).unwrap_or_default() + } + + #[test] + fn the_first_upload_asks_and_nothing_goes_before_the_answer() { + let (mut h, names) = harness(Ok("https://www.printables.com/slice?f=1".into())); + h.app.start("file.open_in_easyprint"); + h.frames(2); + h.step(&json!({"widget": "Send"})).unwrap(); + h.frames(3); + assert!(names.lock().unwrap().is_empty(), "asked first"); + assert!(!h.app.preferences.easyprint_consent); + h.step(&json!({"widget": "Cancel"})).unwrap(); + assert_eq!(opened(&mut h), None); + assert!(names.lock().unwrap().is_empty() && h.app.easyprint.ask.is_none()); + } + + #[test] + fn agreeing_uploads_the_model_and_opens_the_answer_and_the_next_one_does_not_ask() { + let (mut h, names) = harness(Ok("https://www.printables.com/slice?f=1".into())); + h.app.start("file.open_in_easyprint"); + h.frames(2); + h.step(&json!({"widget": "Send"})).unwrap(); + h.frames(3); + h.step(&json!({"widget": "Upload"})).unwrap(); + assert_eq!(opened(&mut h).as_deref(), Some("https://www.printables.com/slice?f=1")); + assert!(h.app.preferences.easyprint_consent); + let names = names.lock().unwrap().clone(); + assert!(names.len() == 1 && names[0].ends_with(".3mf"), "{names:?}"); + // Remembered: the next send goes at once. + request(&mut h.app, json!({"bodies": ["Body1"]})); + assert_eq!(opened(&mut h).as_deref(), Some("https://www.printables.com/slice?f=1")); + } + + #[test] + fn a_failed_upload_is_an_error_toast_and_opens_nothing() { + let (mut h, _) = harness(Err("EasyPrint answered HTTP 500".into())); + h.app.preferences.easyprint_consent = true; + request(&mut h.app, json!({"bodies": ["Body1"]})); + assert_eq!(opened(&mut h), None); + let (text, error) = status(&h); + assert!(error && text.contains("HTTP 500"), "{text}"); + // It can be tried again: the failure ended the upload. + request(&mut h.app, json!({"bodies": ["Body1"]})); + h.frames(2); + assert!(status(&h).0.contains("HTTP 500")); + } + + #[test] + fn nothing_selected_or_no_host_is_an_error_and_uploads_nothing() { + let (mut h, names) = harness(Ok("https://www.printables.com/slice".into())); + h.app.preferences.easyprint_consent = true; + request(&mut h.app, json!({"bodies": ["Nope"]})); + assert_eq!(opened(&mut h), None); + assert!(status(&h).1 && names.lock().unwrap().is_empty()); + let mut bare = Harness::new(); + assert!(!available(&bare.app)); + bare.app.start("file.open_in_easyprint"); + bare.frames(2); + assert!(bare.app.dialog.is_none() && status(&bare).1, "unavailable, with a reason"); + } + + #[test] + fn the_row_makes_a_command_without_a_slicer_and_a_browser_has_only_that_row() { + let (mut h, _) = harness(Ok("https://www.printables.com/slice".into())); + assert!(crate::dialogs_save_mesh::available(&h.app), "no program dialog, but EasyPrint"); + h.app.start("file.open_in_easyprint"); + h.frames(2); + let Some(crate::dialogs::Kind::SaveMesh(k)) = h.app.dialog.as_ref().map(|d| &d.kind) else { panic!("no dialog") }; + let input = crate::selection::SelInput { + items: vec![solidcraft_engine::Sel::Body { name: "Body1".into() }], + ..crate::selection::SelInput::new("Bodies", crate::selection::BODIES, true) + }; + let (id, p) = crate::dialogs_save_mesh::commands(k, &[input]).unwrap().remove(0); + assert_eq!((id.as_str(), p.get("slicer"), p["format"].as_str()), ("file.open_in_easyprint", None, Some("3mf"))); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 164bf187b..18e95a8ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -56,6 +56,7 @@ mod dimension_create_ui_tests; pub mod documents; pub mod drag_extrude; pub mod drag_snap; +pub mod easyprint_ui; pub mod edit_clipboard; mod feature_edit; #[cfg(test)] @@ -401,6 +402,9 @@ pub struct Services { pub agent_http: Option, /// The system keychain, for API agents' keys; None: keys can't be stored. pub secrets: Option>, + /// Upload a model to EasyPrint (Printables' slicer in the browser) and answer with the address + /// to open (`easyprint_ui`); None: this host can't, and the menu doesn't offer it. + pub easyprint_upload: Option, } /// The view before a sketch opened and the view that faced the sketch then (#7038). @@ -430,6 +434,10 @@ pub struct SolveApp { pub pre_sketch_cam: Option, pub services: Services, file_picker: Option, + /// A slicer started alone and waited for before the file is sent (Send to Slicer). + pub(crate) slicer_wait: Option, + /// Open with EasyPrint: the upload in flight and the question before the first one. + pub(crate) easyprint: easyprint_ui::State, /// A Save or Save As being written on a worker (see [`save_job`]). saving: Option, pub viewport: viewport::ViewportState, @@ -619,7 +627,9 @@ impl SolveApp { } let mut render_workspace = render_workspace::State::default(); render_workspace.image_host = image_host; - SolveApp { + #[cfg(not(target_arch = "wasm32"))] + solidcraft_engine::slicer_files::clean_old(); + let mut app = SolveApp { session, ui: UiState::default(), shell: Default::default(), @@ -630,6 +640,8 @@ impl SolveApp { pre_sketch_cam: None, services, file_picker: None, + slicer_wait: None, + easyprint: Default::default(), saving: None, viewport: viewport::ViewportState::default(), render_workspace, @@ -722,7 +734,9 @@ impl SolveApp { applied_fonts_language: "en".into(), applied_ui_font: String::new(), applied_system_fonts: false, - } + }; + easyprint_ui::install(&mut app); + app } /// Translate text using the active language preference. @@ -931,6 +945,10 @@ impl SolveApp { if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() { return Err("a file operation is in progress".into()); } + // Commands may start only detected slicers and the programs the user added under Custom…. + if matches!(id, "file.save_mesh" | "file.send_to_slicer") { + solidcraft_engine::slicers::set_chosen_programs(&self.preferences.custom_slicers); + } let t0 = now_ms(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS; @@ -1195,6 +1213,11 @@ impl SolveApp { let _ = self.run(id, json!({"enabled": !self.preferences.ambient_occlusion})); return; } + // Send to Slicer always asks which slicer (the dialog pre-selects the last one). + if matches!(id, "file.send_to_slicer" | "file.open_in_easyprint") && !dialogs_save_mesh::available(self) { + self.set_status(self.tr("ui.send_to_slicer_unavailable").to_string(), true); + return; + } if id == "view.perspective" { let _ = self.run(id, json!({"enabled": !self.ui.perspective})); return; @@ -1910,6 +1933,8 @@ impl SolveApp { pub fn logic(&mut self, ctx: &egui::Context) { frame_watch::begin(self); file_picker::tick(self, ctx); + dialogs_save_mesh::tick_wait(self, ctx); + easyprint_ui::tick(self, ctx); render_workspace::sync_backend(self); render_workspace::tick(self, ctx); file_load::tick(self, ctx); @@ -2202,6 +2227,7 @@ impl SolveApp { context_menu::show(self, ui.ctx()); mouse_gesture::show(self, ui.ctx()); delete::show(self, ui.ctx()); + easyprint_ui::show(self, ui.ctx()); linked_source::show_copies(self, ui.ctx()); shortcut_box::show(self, ui.ctx()); prefs::show(self, ui.ctx()); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index c1638fbd1..8f7390a98 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -684,23 +684,31 @@ preference_settings! { check_updates: bool = true, 0; /// When the last update check ran, and the versions skipped or put off (`update::Memo`). update: crate::update::Memo = crate::update::Memo::default(); - /// Save as mesh: the last format (`stl` or `3mf`), whether it was sent to a slicer, which one - /// (an installed slicer's id or a program path), and the programs the user added (newest first). /// The variant last started in each split tool family (Rectangle, Circle, Arc, Slot, Polygon, Line, /// Spline): the family's button and shortcut start it again (`sketch_families`). sketch_variants: crate::sketch_families::Choices = crate::sketch_families::Choices::default(); /// Personal Hole parameter combinations, shared by every design in this profile. /// No page reset discards this user-authored library. hole_presets: crate::hole_presets::Library = crate::hole_presets::Library::default(); + /// Save as mesh: the last format (`stl` or `3mf`). Older versions also kept a "send to slicer" + /// choice here (`save_mesh_send`, `save_mesh_slicer`); a settings file that still has them loads, + /// and they are ignored. save_mesh_format: String = "stl".into(); /// Hidden edges in the current-view DXF export (false: omit, true: dashed). view_dxf_dashed: bool = false; /// Model-space chord tolerance for current-view DXF curves, in millimetres. view_dxf_tolerance: f64 = 0.01; - save_mesh_send: bool = false; - save_mesh_slicer: String = String::new(); + /// Send to Slicer: the last slicer used (an installed slicer's id or a program path). + send_slicer: String = String::new(); + /// Slicers that can load a file into the window that is already open do so (default on). + slicer_single_instance: bool = true, 0; + /// The line about sending again replacing the slicer's file has been shown. + slicer_resend_hint_seen: bool = false; + /// The user has agreed to Open with EasyPrint uploading a model to Printables' servers. + easyprint_consent: bool = false; /// Save as mesh: the last quality (`standard`, `fine` or `finest`, #4747). save_mesh_quality: String = "standard".into(); + /// The programs the user added to the slicer list, newest first. custom_slicers: Vec = Vec::new(); /// AI features (docs/agent-chat.md): the master switch. Off: no AI button, shortcut, menu /// entry or panel, and nothing is looked for or started. diff --git a/crates/ui-egui/src/prefs/general.rs b/crates/ui-egui/src/prefs/general.rs index b2a618837..bc4596bdf 100644 --- a/crates/ui-egui/src/prefs/general.rs +++ b/crates/ui-egui/src/prefs/general.rs @@ -42,6 +42,12 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { ui_kit::text(ui, app.tr("prefs.crash_reports_note"), ui_kit::Text::Hint("crash_reports")); }); }); + ui_kit::settings_section(ui, "slicer", app.tr("ui.slicer"), |ui| { + ui_kit::settings_block(ui, app.tr("ui.slicer"), labels, |ui| { + let (single, tip) = (app.tr("ui.slicer_single_instance").to_string(), app.tr("ui.slicer_single_instance_tip").to_string()); + ui_kit::checkbox(ui, &single, &mut app.preferences.slicer_single_instance).on_hover_text(tip); + }); + }); ui_kit::settings_section(ui, "updates", app.tr("prefs.updates"), |ui| { ui_kit::settings_block(ui, app.tr("update.prefs_label"), labels, |ui| crate::update::prefs_rows(app, ui)); }); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 653f86dc3..ddef8a21b 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -672,6 +672,10 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { FileAction::ExportMesh("3mf").run(app); close = true; } + if item_if(ui, "Send to Slicer", "", "mesh_export", shown && crate::dialogs_save_mesh::available(app)) { + app.start("file.send_to_slicer"); + close = true; + } if item_if(ui, "Export STEP…", "", "export", shown) { FileAction::Export("step").run(app); close = true; @@ -1691,6 +1695,8 @@ fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft let description = match command.id { "render.scene" => Some(app.tr("render.preview_help")), "render.start" => Some(app.tr("render.image_help")), + // Sending again replaces the file the slicer has open. + "file.send_to_slicer" => Some(app.tr("ui.slicer_resend_hint")), "render.preset.resolve" | "render.preset.apply" => Some(app.tr("render.ribbon_studios_help")), "render.library.appearance.apply" | "render.library.surface.bind" => Some(app.tr("render.ribbon_materials_help")), "render.library.studio.prepare" | "render.library.studio.apply" => Some(app.tr("render.ribbon_lights_help")), diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index c4e39c25d..79137d317 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -141,7 +141,7 @@ pub const SECTIONS: &[Section] = &[ tab: "INSERT", panel: "FILES", promoted: 3, - ids: &["file.insert_step", "file.insert_mesh", "component.insert_design", "file.save_mesh"], + ids: &["file.insert_step", "file.insert_mesh", "component.insert_design", "file.save_mesh", "file.send_to_slicer"], }, Section { tab: "INSERT", panel: "IMAGES", promoted: 3, ids: &["canvas.insert", "canvas.decal", "canvas.edit"] }, Section { tab: "INSERT", panel: "2D", promoted: 2, ids: &["sketch.insert_dxf", "sketch.insert_svg"] }, diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 6cafbaee8..f5316fd1d 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -44,10 +44,51 @@ negative volumes come in as ordinary solid geometry. **File → Export STL…** and **File → Export 3MF…** (also **Save As Mesh** on the Insert tab's Files panel, and in the right-click menu of a body) open the same dialog with that format chosen; it saves -the selected bodies as STL, 3MF or 3MF with face tags (below), and you can change the format there. With **Send to slicer** ticked, it writes the file to -a temporary folder and opens it in the chosen slicer instead of asking for a file name. The slicer -list shows the slicers found on the computer with their icons; **Custom…** adds any other program -to the top of the list (kept between runs; hover an entry you added and press Delete to remove it). +the selected bodies as STL, 3MF or 3MF with face tags (below) to a file you name, and you can change +the format there. + +**File → Send to Slicer** (also on the Insert tab's Files panel, and in the right-click menu of a +body) is the short way: it saves the selected bodies as a 3MF in millimetres, without face tags, +and sends it to a slicer. It always asks which one and pre-selects the slicer you used last time, +so the usual case is one click or Enter. The list shows the slicers found on the computer with their +icons; **Custom…** adds any other program to the top of the list (kept between runs; hover an entry +you added and press Delete to remove it). On Linux only, a program whose desktop entry says it opens +3MF or STL files is listed even if SolidCraft doesn't know it by name. Windows and macOS list the +known slicers only, found in the usual program folders and on `PATH`. It falls back to an STL if the +3MF can't be written. Scripts and the control channel use `file.send_to_slicer` +with a `slicer`, which sends without a dialog. They can start only the slicers in the +list and programs you added under **Custom…**; any other program path is refused, and an AI agent's +request to save a mesh or send it to a slicer asks first and names the slicer. + +The list also has a plain **EasyPrint (Printables, in the browser)** row, and it is the one entry +that works in the browser build too. EasyPrint is Printables' slicer, so choosing it uploads the +selected bodies (a 3MF, 100 MB at most) to Printables' servers and opens the model there in your +browser. The link expires after 30 minutes, and you need to be signed in to Printables. SolidCraft +asks once before the first upload and remembers that you agreed. Nothing is uploaded unless you pick +this row. SolidCraft isn't affiliated with Printables. Scripts use `file.open_in_easyprint`, which refuses unless it gets `consent: true`, +and an AI agent's request to use it asks first. + +Files sent to a slicer go to a folder only you can +read: `~/.cache/solidcraft/slicer` on Linux, `~/Library/Caches/SolidCraft/slicer` on macOS and +`%LOCALAPPDATA%\SolidCraft\slicer` on Windows. The name stays the same for the same design and +the same bodies, so sending again **replaces the file the slicer has open**: use the slicer's +Reload from disk to pick it up. If Windows won't let the file be replaced because the slicer holds +it, the new copy gets a number (`name-2.3mf`) and the status line says so. Files older than seven days are +deleted the next time SolidCraft starts. + +If the slicer is already running, PrusaSlicer, SuperSlicer and Cura load the file in +the open window instead of starting another one (they are started with `--single-instance`). +Other slicers, Bambu Studio and OrcaSlicer among them, are started as they are, so they may open a +second window. You can turn this off in +Preferences → General, except for PrusaSlicer 3.0, whose launcher can't hand a file to a running +window without it. Scripts pass `single_instance: false` to `file.send_to_slicer` or `file.save_mesh`. + +PrusaSlicer 2 and 3 behave differently, so SolidCraft reads which one an install is from the +version in its installed metadata (a Flatpak's own files, or the `metainfo` file of a package); it +never runs the program to ask. PrusaSlicer 2 is sent the file with `--single-instance`. PrusaSlicer 3 +is started on its own first, SolidCraft waits up to ten seconds for it to be ready, and then sends the +file. If the version can't be read, the command decides: the `slic3r-app-launcher` launcher is +treated as PrusaSlicer 3, and any other entry is left as it is. Closed mechanical meshes with a constant cross-section can be rebuilt as solids with the `mesh.convert` command (command palette, scripts and the control channel).