diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b95df16..20de863 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,9 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: test: runs-on: macos-15 @@ -14,10 +17,8 @@ jobs: run: brew install xcodegen - name: Generate project run: xcodegen generate - - name: Test - run: xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -derivedDataPath build/DerivedData test - - name: Build Release - run: xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -configuration Release -derivedDataPath build/DerivedData build + - name: Build, verify signatures and test + run: ./scripts/build.sh --test - name: Package run: ./scripts/package.sh - uses: actions/upload-artifact@v4 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 05e0fd3..1020bcc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,12 +16,13 @@ Thanks for helping 3D printing on the Mac get a little less annoying. ```sh brew install xcodegen -xcodegen generate -xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter test +./scripts/build.sh --test ./scripts/build.sh --install # try it for real ``` - Keep it dependency-free; macOS frameworks only. - Routing rules live in one pure function (`Router.decide`). Every new rule gets a unit test. - UI strings go through `L10n` (English + Portuguese). +- Keep routing and preview generation offline; do not add model endpoints or credential settings. +- Use `./scripts/build.sh --native --test` when the Xcode build service is unavailable. - Never commit customer or proprietary models. Generate samples procedurally. diff --git a/README.md b/README.md index 9f07f07..50d0eb1 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ### Open every `.3mf` in the right slicer, automatically. Double-click a 3MF on your Mac. 3dSlicerRouter reads the printer saved inside the file and opens -**Bambu Studio**, **Snapmaker Orca** or any slicer you choose. +**Bambu Studio**, **OrcaSlicer**, **Snapmaker Orca** or any slicer you choose. [![CI](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml/badge.svg)](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml) ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-black?logo=apple) @@ -13,7 +13,7 @@ Double-click a 3MF on your Mac. 3dSlicerRouter reads the printer saved inside th ![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) -Animation: a Bambu Lab A1 project opens in Bambu Studio and a Snapmaker U1 project opens in Snapmaker Orca, because the router reads printer_model from each file +Animation: a Bambu Lab A1 project opens in Bambu Studio and a Snapmaker U1 project opens in OrcaSlicer, because the router reads printer_model from each file [Install](docs/INSTALL.md) · [Try the samples](samples/) · [How it decides](#how-it-decides) · [Português](README.pt-BR.md) @@ -26,20 +26,22 @@ have one default app for it. With printers from two brands you end up opening a Bambu Studio (or an A1 project in Orca) and getting preset warnings, missing filaments or a bed type that changed without you noticing. -3dSlicerRouter becomes the default app for `.3mf` and gets out of the way. It has no window: it -reads `printer_model` from the project and hands the file to the slicer that owns that printer. +3dSlicerRouter becomes the default app for `.3mf` and gets out of the way. It reads `printer_model` from the project and hands the file to the configured slicer. +When the file has no printer metadata, it asks you to choose an installed slicer. ## Any printer, any slicer | | Printer in the file | Opens in | |:-:|---|---| | Bambu Studio | `Bambu Lab A1`, `A1 mini`, `P1S`, `X1C`, `H2D`, … | **Bambu Studio** | -| Snapmaker Orca | `Snapmaker U1`, `J1`, `Artisan`, … | **Snapmaker Orca** | -| | Anything else (`Original Prusa MK4S`, `Elegoo Centauri Carbon`, …) | **Your choice**, asked once and remembered | - -For a printer it has never seen, the router asks once: Bambu Studio, Snapmaker Orca or -**Other app…**, a native picker where any slicer in `/Applications` works (OrcaSlicer, PrusaSlicer, -Creality Print, Elegoo Slicer, Cura). Tick *Always use for this printer* and you are never asked again. +| | `Snapmaker U1`, `J1`, `Artisan`, … | **OrcaSlicer (official)** | +| | `Prusa`, `Original Prusa`, … | **OrcaSlicer (official)** | +| | Anything else (`Elegoo Centauri Carbon`, …) | **OrcaSlicer (official)** | +| | No printer declared | **Ask among installed slicers** | + +The official OrcaSlicer is the default for new non-Bambu projects. Hold Option when opening to +choose among installed slicers or **Other app…**, a native picker for any slicer +in `/Applications`. Tick *Always use for this printer* to override the default for that model. You can also map printers from the terminal: ```sh @@ -52,26 +54,26 @@ Need the other slicer for one file? **Hold ⌥ (Option) while opening** and pick ## Already open? No second window -Bambu Studio and Snapmaker Orca start a **new instance** when you open a project that is already +Bambu Studio, OrcaSlicer and Snapmaker Orca start a **new instance** when you open a project that is already open, so you end up editing the same file in two windows. 3dSlicerRouter checks first. When the file is the open project of a running slicer, it tells you so, says whether it has unsaved changes, and offers: -- **Switch to the slicer**: brings that exact window forward. -- **Reload from disk**: closes that project the normal way (the slicer asks before discarding - unsaved changes) and reopens the saved file. +- **Switch to the slicer**: activates the running slicer instance. +- **Restart and reload**: closes that slicer instance, which may contain other windows. The slicer + can ask about unsaved changes before the saved file is reopened. - **Open another copy**: the old behaviour, if you really want it. It reads the recovery folders the slicers keep in `$TMPDIR` while a project is open, so it needs no extra permissions. `3dSlicerRouter --inspect file.3mf` shows the same information. -## See where a file goes before you open it +## Finder thumbnails and 3D previews The router also teaches Finder about 3MF projects: -- **List view and small icons** show the icon of the slicer the file will open in. -- **Larger icons, Gallery and the preview pane** show the plate: the image the slicer saved, or a - rendered isometric view of the declared printer's bed when the file has none. +- **Finder thumbnails at every size** show the first plate. The current indexed render takes priority; + without it, a request renders current geometry. The slicer's saved first-plate image is used only if + rendering fails or the compressed project exceeds 250 MB, so that fallback can be out of date. - **Quick Look (Space)** on a single-plate project is a 3D view you can orbit and zoom. Projects with several plates show every plate side by side. - **Painted colours are exact.** Faces painted with the slicer's colour brush are decoded triangle by @@ -86,6 +88,12 @@ The router also teaches Finder about 3MF projects: ## Background previews (optional) +> **Ad-hoc build limitation:** background startup is experimental. On the local test Mac, macOS +> intermittently rejected the helper with a launch constraint violation even when registration was +> enabled and the signature verified. Routing and on-demand previews do not depend on this helper. +> If it cannot start, use `--render` or the foreground `--index` command. Do not disable system security. + + Big projects take seconds to render. Turn on the indexer and they are ready before you open Finder: ```sh @@ -95,8 +103,11 @@ Big projects take seconds to render. Turn on the indexer and they are ready befo - It finds every `.3mf` and `.gcode` on the Mac through Spotlight (no disk crawling) and keeps a catalog. - It wakes every 30 minutes at background priority and **only works on AC power, outside Low Power Mode, while the Mac is cool and you have been away for 3 minutes**. It stops as soon as you are back. -- Previews go to `~/Library/Application Support/3dSlicerRouter/previews`. Finder and Quick Look read - them instantly; editing a file invalidates its preview. +- Rendering runs in a separate executable, with a 20-minute run limit and conditions checked every + 5 seconds even during a complex preview, so it cannot occupy the Finder handler. +- Previews go to `~/Library/Application Support/3dSlicerRouter/previews`. Saves invalidate the generated + image, including same-size saves within one second. The next eligible pass renders current first-plate + geometry even if the embedded image is old, then notifies Finder. Failed or missing previews are retried. - macOS shows *Background item added*. You can switch it off in **System Settings › General › Login Items** or with `3dSlicerRouter --background off`. The first time it reads files in Desktop, Documents, Downloads or an external drive, macOS may ask you to allow it. @@ -107,20 +118,28 @@ Big projects take seconds to render. Turn on the indexer and they are ready befo | Situation | Result | |---|---| -| First open | Slicer mapped to the file's printer; unknown printer asks once | +| First open | Explicit printer mapping; otherwise Bambu Studio for Bambu Lab, official OrcaSlicer for other printers | | Same file, same printer | Where it opened last time, manual choices included | | Printer changed within the brand (A1 → A1 mini) | Same slicer, no question | | Printer changed to Bambu Lab (U1 → A1) | Bambu Studio, no question | | Printer changed to another brand (A1 → U1) | Asks, with the mapped slicer first | -| No printer in the file | Optional local classifier, otherwise asks | +| No printer in the file | Remembered manual choice; otherwise asks among installed slicers | +| Assigned slicer was uninstalled | Asks among the remaining installed slicers | | ⌥ held while opening | Always asks | -| File already open in a slicer | Switch to it, reload from disk or open another copy | +| File already open in a slicer | Switch to it, restart and reload, or open another copy | The decision is stored in a local SQLite index and on the file as an extended attribute (`com.moraesdev.slicer-router`). Slicers replace the file when they save, which drops the attribute; the router then finds the decision by path and stamps it again. **The file's contents are never modified by the router.** +Each choice stores the app's bundle ID, path and name. Official OrcaSlicer +(`com.orcaslicer.OrcaSlicer`, `/Applications/OrcaSlicer.app`) and Snapmaker Orca +(`com.snapmaker.snapmaker-orca`, `/Applications/Snapmaker Orca.app`) are separate choices. +Existing file choices and explicit printer mappings keep priority over the new default. +The recorded installation path is preferred when it still has the matching bundle ID. +Opening a file directly in another slicer does not update the router's choice. + > Why not the `Application` field? Snapmaker Orca also writes `BambuStudio-…` there. The printer comes > from `Metadata/project_settings.config` → `printer_model`. @@ -136,17 +155,21 @@ alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRou 3dSlicerRouter --set-default ``` -Prefer a download? Grab the zip from [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). +Prebuilt packages, when available, are listed under [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). +Local builds use an ad-hoc signature. Developer ID signing and notarization are not provided by this build script. Dependencies, update and **uninstall**: [docs/INSTALL.md](docs/INSTALL.md). +If Xcode's build service stalls, `./scripts/build.sh --native --test` builds the same universal app and +runs the full test suite using `swiftc` and `xctest`. It still requires Xcode's SDK and command-line tools. + ## Try it Seven small synthetic projects in [`samples/`](samples/) cover every path: ```sh open samples/bambu-a1-keychain-tray.3mf # Bambu Studio -open samples/snapmaker-u1-four-colors.3mf # Snapmaker Orca -open samples/unknown-printer-prusa-mk4s.3mf # asks once +open samples/snapmaker-u1-four-colors.3mf # OrcaSlicer +open samples/no-printer-declared.3mf # choose an installed slicer 3dSlicerRouter --inspect samples/*.3mf # see every decision, opens nothing ``` @@ -157,10 +180,11 @@ open samples/unknown-printer-prusa-mk4s.3mf # asks once | Command | What it does | |---|---| -| `--inspect file.3mf…` | Printer, thumbnail, memory and decision, without opening or writing anything | +| `--inspect file.3mf…` | Printer, thumbnail, remembered choice and decision; does not open a slicer or change the 3MF | | `--map "" /Applications/App.app` | Send that printer to any slicer | | `--mappings` | List brand defaults and your mappings | -| `--render file.3mf\|file.gcode out.png [px]` | Isometric preview as PNG | +| `--list-slicers` | List installed slicers and their paths | +| `--render file.3mf\|file.gcode out.png [px]` | First plate of a 3MF, or G-code toolpath, as PNG | | `--background on\|off\|status` | Background preview indexer | | `--index [--limit N]` | Index and render now, ignoring the idle rule | | `--index-status` | Indexer state, catalog totals, log path | @@ -168,36 +192,58 @@ open samples/unknown-printer-prusa-mk4s.3mf # asks once | `--forget file.3mf…` | Erase the router's memory for these files | | `--set-default` | Make the router the default app for `.3mf` | -## Files with no printer (optional) +## Files with no printer -Some 3MF files carry no slicer metadata at all. For those the router can ask a local decision -model (for example LAYA) through any server that speaks the `/v1/systemone` typed-choice API and -returns probabilities. It opens directly only at 75 % confidence or more; otherwise it asks you with -its guess first. If nothing is listening on `http://127.0.0.1:8100/v1/systemone`, it simply asks. +Files without printer metadata ask which slicer to use. The picker checks `/Applications`, +`~/Applications`, their subfolders and macOS registrations for the three main slicers. Only apps +with an existing executable are listed, including PrusaSlicer and other recognized slicers when +installed. Removed apps and broken symlinks are excluded. -```sh -defaults write com.moraesdev.3dslicerrouter LayaEndpoint off # or another URL -``` +Remembered manual choices still apply to their files. Old automatic OrcaSlicer fallbacks for +files without a printer ask again. All routing runs locally. +3dSlicerRouter remains the default application for `.3mf` files. + +

+Native picker for a synthetic 3MF, showing OrcaSlicer, Bambu Studio and Snapmaker Orca installed on the test Mac +

+ +*Native picker with a synthetic sample. The list reflects the slicers installed on the test Mac.* + +## Local rendering and privacy + +Thumbnails are rendered from the file's geometry and filament colours with SceneKit and Metal. +Camera and lighting are fixed by code. No AI model is involved. In repeated local checks, the same +synthetic input produced identical PNG hashes; identical pixels across different macOS/GPU versions +are not guaranteed. + +The app keeps routing choices, a catalog and preview images in the user's Application Support +folder. The optional indexer only reads files visible to Spotlight and permitted by macOS. +There is no network client or credential configuration in the application. ## FAQ **Does it touch my files?** Only an extended attribute with the decision. The 3MF contents stay byte-for-byte the same. -**Does the preview update after I edit the project?** Yes. Finder caches thumbnails by modification -date, so the next save in the slicer refreshes the preview. Closing without saving changes nothing. +**Does the preview update after I edit the project?** A save invalidates the generated preview. Finder's +next request renders current first-plate geometry if no indexed image is ready; the optional indexer +prepares it during its next idle pass. Only the error/large-project fallback can retain an old slicer +screenshot. Closing without saving changes nothing. -**Does it need special permissions?** No. No Accessibility, Screen Recording or Full Disk Access. -macOS hands it only the file you opened. +**Does it need special permissions?** Opening a file and generating its preview do not require +Accessibility, Screen Recording or Full Disk Access. The optional background indexer may need your +approval for background activity and access to protected folders. -**Does it phone home?** No. The only network call is the optional classifier on `localhost`. +**Does it phone home?** No. Routing and previews run entirely on your Mac. No network service, +AI model, API key or account is required. **Does it run in the background?** Only if you turn on the indexer, and then only while the Mac is idle and plugged in. ## Roadmap -- [ ] Built-in defaults for OrcaSlicer, PrusaSlicer, Elegoo Slicer and Creality Print (today: *Other app…* or `--map`) +- [x] Official OrcaSlicer default, separate from Snapmaker Orca +- [ ] Built-in presets for PrusaSlicer, Elegoo Slicer and Creality Print (today: *Other app…* or `--map`) - [ ] Settings window for printer → slicer mappings - [ ] Extrusion-width ribbons in the G-code preview - [ ] Notarized release diff --git a/README.pt-BR.md b/README.pt-BR.md index c92e9be..cd3e072 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -5,7 +5,7 @@ ### Cada `.3mf` abre no fatiador certo, sozinho. Dê dois cliques num 3MF no Mac. O 3dSlicerRouter lê a impressora salva dentro do arquivo e abre o -**Bambu Studio**, o **Snapmaker Orca** ou o fatiador que você escolher. +**Bambu Studio**, o **OrcaSlicer**, o **Snapmaker Orca** ou o fatiador que você escolher. [![CI](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml/badge.svg)](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml) ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-black?logo=apple) @@ -13,7 +13,7 @@ Dê dois cliques num 3MF no Mac. O 3dSlicerRouter lê a impressora salva dentro ![Dependências](https://img.shields.io/badge/depend%C3%AAncias-0-brightgreen) [![Licença: MIT](https://img.shields.io/badge/licen%C3%A7a-MIT-blue)](LICENSE) -Animação: um projeto Bambu Lab A1 abre no Bambu Studio e um projeto Snapmaker U1 abre no Snapmaker Orca, porque o router lê o printer_model de cada arquivo +Animação: um projeto Bambu Lab A1 abre no Bambu Studio e um projeto Snapmaker U1 abre no OrcaSlicer, porque o router lê o printer_model de cada arquivo [Instalar](docs/INSTALL.pt-BR.md) · [Testar com os samples](samples/) · [Como decide](#como-decide) · [English](README.md) @@ -26,21 +26,23 @@ padrão para essa extensão. Com impressoras de duas marcas, você acaba abrindo Bambu Studio (ou um da A1 no Orca) e ganha aviso de preset, filamento faltando ou tipo de mesa trocado sem perceber. -O 3dSlicerRouter vira o app padrão de `.3mf` e sai do caminho. Ele não tem janela: lê o `printer_model` -do projeto e entrega o arquivo ao fatiador dessa impressora. +O 3dSlicerRouter vira o app padrão de `.3mf` e sai do caminho. Ele lê o `printer_model` do projeto e entrega o arquivo ao fatiador configurado. +Sem essa informação, pergunta qual fatiador instalado você quer usar. ## Qualquer impressora, qualquer fatiador | | Impressora no arquivo | Abre no | |:-:|---|---| | Bambu Studio | `Bambu Lab A1`, `A1 mini`, `P1S`, `X1C`, `H2D`, … | **Bambu Studio** | -| Snapmaker Orca | `Snapmaker U1`, `J1`, `Artisan`, … | **Snapmaker Orca** | -| | Qualquer outra (`Original Prusa MK4S`, `Elegoo Centauri Carbon`, …) | **Você escolhe**, uma vez, e fica lembrado | +| | `Snapmaker U1`, `J1`, `Artisan`, … | **OrcaSlicer oficial** | +| | `Prusa`, `Original Prusa`, … | **OrcaSlicer oficial** | +| | Qualquer outra (`Elegoo Centauri Carbon`, …) | **OrcaSlicer oficial** | +| | Sem impressora declarada | **Pergunta entre os fatiadores instalados** | -Impressora nova pergunta uma vez: Bambu Studio, Snapmaker Orca ou **Outro app…**, um seletor nativo -onde vale qualquer fatiador em `/Applications` (OrcaSlicer, PrusaSlicer, Creality Print, Elegoo -Slicer, Cura). Marque *Usar sempre para esta impressora* e nunca mais será perguntado. Também dá -para mapear pelo terminal: +O OrcaSlicer oficial é o padrão para projetos novos de impressoras que não são Bambu. Segure Option +ao abrir para escolher entre os fatiadores instalados ou **Outro app…**, um seletor nativo +para os fatiadores em `/Applications`. Marque *Usar sempre para esta impressora* para definir +uma regra para aquele modelo. Também dá para mapear pelo terminal: ```sh 3dSlicerRouter --map "Original Prusa MK4S" /Applications/PrusaSlicer.app @@ -52,26 +54,26 @@ do Finder continua funcionando, e o próximo duplo clique lê o arquivo de novo. ## Já está aberto? Nada de segunda janela -O Bambu Studio e o Snapmaker Orca abrem **outra instância** quando você abre um projeto que já está +O Bambu Studio, o OrcaSlicer e o Snapmaker Orca abrem **outra instância** quando você abre um projeto que já está aberto, e você acaba editando o mesmo arquivo em duas janelas. O 3dSlicerRouter confere antes. Se o arquivo é o projeto aberto de um fatiador em execução, ele avisa, diz se há alterações não salvas e oferece: -- **Ir para o fatiador**: traz exatamente aquela janela para a frente. -- **Recarregar do disco**: fecha esse projeto do jeito normal (o fatiador pergunta antes de descartar - alterações) e reabre o arquivo salvo. +- **Ir para o fatiador**: ativa a instância do fatiador em execução. +- **Reiniciar e recarregar**: fecha a instância do fatiador, que pode conter outras janelas. O fatiador + pode perguntar sobre alterações não salvas antes de reabrir o arquivo do disco. - **Abrir outra cópia**: o comportamento antigo, se você quiser mesmo. Ele lê as pastas de recuperação que os fatiadores mantêm em `$TMPDIR` enquanto o projeto está aberto, então não precisa de permissão extra. `3dSlicerRouter --inspect arq.3mf` mostra o mesmo. -## Veja para onde o arquivo vai antes de abrir +## Thumbnails do Finder e previews 3D O router também ensina o Finder a mostrar projetos 3MF: -- **Lista e ícones pequenos** mostram o ícone do fatiador em que o arquivo vai abrir. -- **Ícones maiores, Galeria e painel de preview** mostram a mesa: a imagem salva pelo fatiador ou, - quando o arquivo não tem, uma vista isométrica renderizada da mesa da impressora declarada. +- **Thumbnails do Finder em todos os tamanhos** mostram a primeira chapa. O render indexado da revisão + atual tem prioridade; sem ele, a solicitação renderiza a geometria atual. A imagem salva pelo fatiador + só é usada se o render falhar ou o projeto comprimido exceder 250 MB; esse fallback pode estar desatualizado. - **Quick Look (Espaço)** em projeto de uma mesa é um 3D para girar e dar zoom. Projetos com várias mesas mostram todas lado a lado. - **Cores pintadas exatas.** Faces pintadas com o pincel de cor do fatiador são decodificadas triângulo @@ -87,6 +89,12 @@ O router também ensina o Finder a mostrar projetos 3MF: ## Previews em background (opcional) +> **Limitação dos builds ad-hoc:** a inicialização em background é experimental. No Mac de teste, +> o macOS rejeitou algumas inicializações do helper por uma restrição de lançamento, mesmo com +> registro habilitado e assinatura válida. Roteamento e previews sob demanda não dependem dele. +> Se o helper não iniciar, use `--render` ou `--index` em foreground. Não desative a segurança do sistema. + + Projetos grandes levam segundos para renderizar. Ligue o indexador e eles ficam prontos antes de você abrir o Finder: @@ -97,8 +105,9 @@ abrir o Finder: - Acha todos os `.3mf` e `.gcode` do Mac pelo Spotlight (sem varrer o disco) e mantém um catálogo. - Acorda a cada 30 minutos com prioridade de background e **só trabalha na tomada, fora do modo de pouca energia, com o Mac frio e você ausente há 3 minutos**. Para assim que você volta. -- Os previews ficam em `~/Library/Application Support/3dSlicerRouter/previews`. O Finder e o Quick Look - leem na hora; editar o arquivo invalida o preview dele. +- Os previews ficam em `~/Library/Application Support/3dSlicerRouter/previews`. Salvar invalida a imagem + gerada, inclusive com o mesmo tamanho dentro do mesmo segundo. A próxima passada elegível renderiza a + geometria atual da primeira chapa mesmo com imagem embutida antiga e avisa o Finder. Falhas e caches ausentes são repetidos. - O macOS mostra *Item de segundo plano adicionado*. Dá para desligar em **Ajustes do Sistema › Geral › Itens de Início** ou com `3dSlicerRouter --background off`. Na primeira vez que ele ler arquivos da Mesa, Documentos, Downloads ou de um disco externo, o macOS pode pedir sua autorização. @@ -109,20 +118,28 @@ abrir o Finder: | Situação | Resultado | |---|---| -| Primeira abertura | Fatiador mapeado para a impressora do arquivo; impressora desconhecida pergunta uma vez | +| Primeira abertura | Regra explícita da impressora; sem regra, Bambu Studio para Bambu Lab e OrcaSlicer oficial para as demais | | Mesmo arquivo, mesma impressora | Onde abriu da última vez, inclusive escolha manual | | Impressora mudou dentro da marca (A1 → A1 mini) | Mesmo fatiador, sem perguntar | | Impressora mudou para Bambu Lab (U1 → A1) | Bambu Studio, sem perguntar | | Impressora mudou para outra marca (A1 → U1) | Pergunta, com o fatiador mapeado em primeiro | -| Arquivo sem impressora | Classificador local opcional; senão, pergunta | +| Arquivo sem impressora | Escolha manual salva; sem escolha manual, pergunta entre os fatiadores instalados | +| Fatiador definido foi desinstalado | Pergunta entre os fatiadores ainda instalados | | ⌥ segurado ao abrir | Sempre pergunta | -| Arquivo já aberto num fatiador | Ir para ele, recarregar do disco ou abrir outra cópia | +| Arquivo já aberto num fatiador | Ir para ele, reiniciar e recarregar ou abrir outra cópia | A decisão fica num índice SQLite local e no arquivo, como atributo estendido (`com.moraesdev.slicer-router`). Os fatiadores substituem o arquivo ao salvar, o que apaga o atributo; o router então acha a decisão pelo caminho e grava de novo. **O router nunca altera o conteúdo do arquivo.** +Cada escolha registra bundle ID, caminho e nome do aplicativo. O OrcaSlicer oficial +(`com.orcaslicer.OrcaSlicer`, `/Applications/OrcaSlicer.app`) e o Snapmaker Orca +(`com.snapmaker.snapmaker-orca`, `/Applications/Snapmaker Orca.app`) são escolhas separadas. +As escolhas salvas por arquivo e as regras explícitas por impressora têm prioridade sobre o novo padrão. +O caminho registrado tem prioridade enquanto o aplicativo nele tiver o bundle ID correspondente. +Abrir o arquivo diretamente em outro slicer não atualiza a escolha do router. + > Por que não o campo `Application`? O Snapmaker Orca também grava `BambuStudio-…` nele. A impressora > vem de `Metadata/project_settings.config` → `printer_model`. @@ -138,17 +155,21 @@ alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRou 3dSlicerRouter --set-default ``` -Prefere baixar pronto? O zip está em [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). +Pacotes prontos, quando disponíveis, ficam em [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). +O build local usa assinatura ad-hoc. O script não fornece assinatura Developer ID nem notarização. Dependências, atualização e **desinstalação**: [docs/INSTALL.pt-BR.md](docs/INSTALL.pt-BR.md). +Se o serviço de build do Xcode travar, `./scripts/build.sh --native --test` gera o mesmo app universal e +roda a suíte completa com `swiftc` e `xctest`. O SDK e as ferramentas de linha de comando do Xcode continuam necessários. + ## Teste Sete projetos sintéticos pequenos em [`samples/`](samples/) cobrem todos os caminhos: ```sh open samples/bambu-a1-keychain-tray.3mf # Bambu Studio -open samples/snapmaker-u1-four-colors.3mf # Snapmaker Orca -open samples/unknown-printer-prusa-mk4s.3mf # pergunta uma vez +open samples/snapmaker-u1-four-colors.3mf # OrcaSlicer +open samples/no-printer-declared.3mf # escolher um fatiador instalado 3dSlicerRouter --inspect samples/*.3mf # mostra cada decisão, sem abrir nada ``` @@ -159,9 +180,10 @@ open samples/unknown-printer-prusa-mk4s.3mf # pergunta uma vez | Comando | O que faz | |---|---| -| `--inspect arq.3mf…` | Impressora, thumbnail, memória e decisão, sem abrir nem gravar nada | +| `--inspect arq.3mf…` | Impressora, thumbnail, escolha salva e decisão; não abre fatiador nem altera o 3MF | | `--map "" /Applications/App.app` | Manda essa impressora para qualquer fatiador | | `--mappings` | Lista os padrões por marca e os seus mapeamentos | +| `--list-slicers` | Lista somente os fatiadores instalados e seus caminhos | | `--render arq.3mf\|arq.gcode out.png [px]` | Preview isométrico em PNG | | `--background on\|off\|status` | Indexador de previews em background | | `--index [--limit N]` | Indexa e renderiza agora, ignorando a regra de ociosidade | @@ -170,36 +192,56 @@ open samples/unknown-printer-prusa-mk4s.3mf # pergunta uma vez | `--forget arq.3mf…` | Apaga a memória do router nesses arquivos | | `--set-default` | Torna o router o app padrão de `.3mf` | -## Arquivos sem impressora (opcional) +## Arquivos sem impressora -Alguns 3MF não trazem nenhum metadado de fatiador. Para eles, o router pode consultar um modelo de -decisão local (o LAYA, por exemplo) por qualquer servidor que fale a API de escolha tipada -`/v1/systemone` e devolva probabilidades. Só abre direto com 75 % de confiança ou mais; abaixo disso -pergunta, com o palpite em primeiro. Se nada responder em `http://127.0.0.1:8100/v1/systemone`, ele -simplesmente pergunta. +Arquivos sem impressora declarada perguntam qual fatiador usar. O seletor verifica instalações +em `/Applications`, `~/Applications`, suas subpastas e os registros dos três fatiadores principais +no macOS. Só entram apps com executável presente, incluindo PrusaSlicer e outros fatiadores +reconhecidos quando instalados. Apps removidos e links quebrados ficam fora da lista. -```sh -defaults write com.moraesdev.3dslicerrouter LayaEndpoint off # ou outra URL -``` +Uma escolha manual salva continua válida para aquele arquivo. Decisões automáticas antigas +que usavam OrcaSlicer por falta de impressora voltam a perguntar. As regras são executadas localmente. O 3dSlicerRouter continua como app padrão da extensão `.3mf`. + +

+Seletor nativo de um 3MF sintético, com OrcaSlicer, Bambu Studio e Snapmaker Orca instalados no Mac de teste +

+ +*Seletor nativo com sample sintético. A lista corresponde aos fatiadores instalados no Mac de teste.* + +## Renderização local e privacidade + +As thumbnails usam a geometria e as cores dos filamentos, renderizadas com SceneKit e Metal. +Câmera e iluminação são definidas pelo código. Nenhum modelo de IA participa. Em verificações locais, +o mesmo sample produziu PNGs com hashes iguais. Não há garantia de pixels idênticos entre versões +de macOS ou GPUs diferentes. + +O app mantém escolhas, catálogo e previews na pasta Application Support do usuário. O indexador +opcional só lê arquivos visíveis ao Spotlight e permitidos pelo macOS. O aplicativo não tem cliente +de rede nem configuração de credenciais. ## Perguntas frequentes **Ele mexe nos meus arquivos?** Só num atributo estendido com a decisão. O conteúdo do 3MF continua idêntico, byte a byte. -**O preview atualiza depois que edito o projeto?** Sim. O Finder guarda as thumbnails pela data de -modificação, então o próximo salvamento no fatiador atualiza o preview. Fechar sem salvar não muda nada. +**O preview atualiza depois que edito o projeto?** Salvar invalida o preview gerado. Na próxima solicitação, +o Finder renderiza a geometria atual da primeira chapa se não houver imagem indexada pronta; o indexador +opcional a prepara na próxima passada ociosa. Apenas o fallback de erro/projeto grande pode manter um +screenshot antigo do fatiador. Fechar sem salvar não muda nada. -**Precisa de permissão especial?** Não. Nada de Acessibilidade, Gravação de Tela ou Acesso Total ao -Disco. O macOS entrega a ele só o arquivo que você abriu. +**Precisa de permissão especial?** Abrir um arquivo e gerar seu preview não exige Acessibilidade, +Gravação de Tela ou Acesso Total ao Disco. O indexador opcional pode exigir sua aprovação para +atividade em background e acesso a pastas protegidas. -**Manda dados para algum lugar?** Não. A única chamada de rede é o classificador opcional em `localhost`. +**Manda dados para algum lugar?** Não. Roteamento e previews são executados no seu Mac. +Não exigem serviço de rede, modelo de IA, API key nem conta. **Ele roda em background?** Só se você ligar o indexador, e mesmo assim só com o Mac ocioso e na tomada. ## Roadmap -- [ ] Padrões prontos para OrcaSlicer, PrusaSlicer, Elegoo Slicer e Creality Print (hoje: *Outro app…* ou `--map`) +- [x] OrcaSlicer oficial como padrão, separado do Snapmaker Orca +- [ ] Padrões prontos para PrusaSlicer, Elegoo Slicer e Creality Print (hoje: *Outro app…* ou `--map`) - [ ] Janela de configurações para os mapeamentos impressora → fatiador - [ ] Largura de extrusão (fitas) no preview de G-code - [ ] Release notarizado diff --git a/Resources/LaunchAgents/com.moraesdev.3dslicerrouter.indexer.plist b/Resources/LaunchAgents/com.moraesdev.3dslicerrouter.previews.v2.plist similarity index 78% rename from Resources/LaunchAgents/com.moraesdev.3dslicerrouter.indexer.plist rename to Resources/LaunchAgents/com.moraesdev.3dslicerrouter.previews.v2.plist index a7eb188..d9313fa 100644 --- a/Resources/LaunchAgents/com.moraesdev.3dslicerrouter.indexer.plist +++ b/Resources/LaunchAgents/com.moraesdev.3dslicerrouter.previews.v2.plist @@ -4,13 +4,12 @@ Label - com.moraesdev.3dslicerrouter.indexer + com.moraesdev.3dslicerrouter.previews.v2 BundleProgram - Contents/MacOS/3dSlicerRouter + Contents/Helpers/3dSlicerIndexer ProgramArguments - 3dSlicerRouter - --index-agent + 3dSlicerIndexer RunAtLoad diff --git a/Sources/App/Indexer.swift b/Sources/App/Indexer.swift index a6343c7..2d8f527 100644 --- a/Sources/App/Indexer.swift +++ b/Sources/App/Indexer.swift @@ -6,10 +6,10 @@ import ServiceManagement /// Acha todos os .3mf e .gcode pelo Spotlight, cataloga e pré-renderiza os previews que faltam, /// só quando o Mac está na tomada e ocioso. Roda pelo LaunchAgent do app (`--index-agent`). enum Indexer { - static let agentPlist = "com.moraesdev.3dslicerrouter.indexer.plist" + static let agentPlist = "com.moraesdev.3dslicerrouter.previews.v2.plist" static let minIdle: TimeInterval = 180 /// Arquivos maiores que isso são catalogados mas não renderizados (malhas de centenas de MB). - static let maxRenderBytes = 250_000_000 + static let maxRenderBytes = PreviewRenderer.maxRenderBytes static let log = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0] .appendingPathComponent("Logs/3dSlicerRouter/indexer.log") @@ -106,10 +106,12 @@ enum Indexer { var printer: String?, plates = 1, embedded = false, preview: String?, rendered = false, error: String? } - static func index(_ url: URL, size: Int, modified: Date) -> Entry { + static func index(_ url: URL, size: Int, modified: Date, cacheDirectory: URL = PreviewCache.directory, + readInfo: (URL) throws -> ThreeMFInfo = { try ThreeMF.info(url: $0) }) -> Entry { let gcode = url.pathExtension.lowercased() == "gcode" var entry = Entry(path: url.path, kind: gcode ? "gcode" : "3mf", size: size, modified: modified) do { + guard let revision = PreviewCache.name(for: url) else { throw IndexError.changedDuringRender } let render: () throws -> CGImage if gcode { let meta = try GCode.metadata(url: url) @@ -117,24 +119,34 @@ enum Indexer { entry.embedded = meta.thumbnail != nil render = { try PreviewRenderer.renderGCode(url: url, info: meta.info, size: CGSize(width: 1024, height: 1024)) } } else { - let info = try ThreeMF.info(url: url) + let info = try readInfo(url) entry.printer = info.printerModel entry.plates = info.plateCount entry.embedded = info.embeddedThumbnail != nil - render = { try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1024, height: 1024)) } + render = { try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1024, height: 1024), firstPlateOnly: true) } } - if let cached = PreviewCache.cachedURL(for: url) { + guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender } + if let cached = PreviewCache.cachedURL(for: url, directory: cacheDirectory) { entry.preview = cached.path - } else if !entry.embedded, size <= maxRenderBytes { - entry.preview = PreviewCache.store(try PreviewRenderer.encode(render()), for: url)?.path + } else if size <= maxRenderBytes, !gcode || !entry.embedded { + let png = try PreviewRenderer.encode(render()) + guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender } + entry.preview = PreviewCache.store(png, for: url, directory: cacheDirectory, expectedName: revision)?.path entry.rendered = entry.preview != nil + if !entry.rendered { throw IndexError.cacheWriteFailed } + // The .3mf's mtime does not change when its sidecar cache is refreshed. + // Ask Finder to request the new representation instead of retaining the embedded fallback. + NSWorkspace.shared.noteFileSystemChanged(url.path) } + guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender } } catch { entry.error = "\(error)" } return entry } + enum IndexError: Error { case changedDuringRender, cacheWriteFailed } + // MARK: agente em background static var service: SMAppService { SMAppService.agent(plistName: agentPlist) } diff --git a/Sources/App/Laya.swift b/Sources/App/Laya.swift deleted file mode 100644 index a2d95a6..0000000 --- a/Sources/App/Laya.swift +++ /dev/null @@ -1,67 +0,0 @@ -import Foundation - -/// Julgamento tipado do daemon LAYA local (opcional), só para arquivos sem `printer_model`. -/// Endpoint: `defaults write com.moraesdev.3dslicerrouter LayaEndpoint `; `off` desliga. -enum Laya { - static var endpoint: URL? { - let value = UserDefaults.standard.string(forKey: "LayaEndpoint") ?? "http://127.0.0.1:8100/v1/systemone" - return value == "off" ? nil : URL(string: value) - } - /// Abaixo disso o router pergunta ao dono. - static let minProbability = 0.75 - - struct Guess { let app: SlicerApp; let probability: Double } - - static func classify(info: ThreeMFInfo, fileName: String) -> Guess? { - let facts = [ - "file name: \(fileName)", - "creator application: \(info.application ?? "unknown")", - "printer preset: \(info.printerSettingsID ?? "none")", - "process preset: \(info.printSettingsID ?? "none")", - "objects: \(info.objectNames.prefix(12).joined(separator: ", "))", - ].joined(separator: "\n") - let body: [String: Any] = [ - "state": ["file": facts], - "questions": ["slicer": [ - "type": "choice", - "instructions": "Which slicer app should open the 3MF project described in `file`?", - "criteria": [ - "bambu_studio": "Bambu Lab printers (A1, A1 mini, P1S, P1P, X1C, H2D, H2C), BambuStudio projects, @BBL presets", - "snapmaker_orca": "Snapmaker printers (U1, J1, Artisan, A350), Snapmaker Orca or OrcaSlicer projects", - "unknown": "no evidence for either printer family", - ], - ]], - ] - guard let payload = try? JSONSerialization.data(withJSONObject: body), let json = post(payload), - let answer = (json["answers"] as? [String: Any])?["slicer"] as? [String: Any], - let choice = answer["choice"] as? String, - let p = (answer["probabilities"] as? [String: Double])?[choice] else { return nil } - switch choice { - case "bambu_studio": return Guess(app: .bambuStudio, probability: p) - case "snapmaker_orca": return Guess(app: .snapmakerOrca, probability: p) - default: return nil - } - } - - /// Até 3 tentativas em timeout/5xx (agora, +2 s, +8 s); 4xx e conexão recusada não se repetem. - private static func post(_ payload: Data) -> [String: Any]? { - guard let endpoint else { return nil } - for wait in [0.0, 2, 8] { - if wait > 0 { Thread.sleep(forTimeInterval: wait) } - var request = URLRequest(url: endpoint, timeoutInterval: 15) - request.httpMethod = "POST" - request.setValue("application/json", forHTTPHeaderField: "Content-Type") - request.httpBody = payload - var result: (Data?, URLResponse?, Error?) - let done = DispatchSemaphore(value: 0) - URLSession.shared.dataTask(with: request) { d, r, e in result = (d, r, e); done.signal() }.resume() - done.wait() - let status = (result.1 as? HTTPURLResponse)?.statusCode ?? 0 - if status == 200, let d = result.0 { return try? JSONSerialization.jsonObject(with: d) as? [String: Any] } - if (400..<500).contains(status) { return nil } - // Daemon não instalado/rodando: não vale esperar retry. - if (result.2 as? URLError)?.code == .cannotConnectToHost { return nil } - } - return nil - } -} diff --git a/Sources/App/Prompt.swift b/Sources/App/Prompt.swift index 47e6c27..9808ab2 100644 --- a/Sources/App/Prompt.swift +++ b/Sources/App/Prompt.swift @@ -15,13 +15,13 @@ enum Prompt { case let .unknownPrinter(m): alert.informativeText = L10n.reasonUnknown(m) case let .printerChanged(from, to): alert.informativeText = L10n.reasonChanged(from ?? L10n.notDeclared, to) case .noPrinter: alert.informativeText = L10n.reasonNoPrinter + case let .appUnavailable(name): alert.informativeText = L10n.reasonUnavailable(name) } if let png = info.embeddedThumbnail.flatMap({ try? ZipArchive(url: url).read($0) }), let image = NSImage(data: png) { alert.icon = image } - var apps = SlicerApp.known - if let s = suggested { apps.removeAll { $0 == s }; apps.insert(s, at: 0) } + let apps = SlicerApp.installed(suggested: suggested) for app in apps { alert.addButton(withTitle: app.name) } alert.addButton(withTitle: L10n.otherApp) alert.addButton(withTitle: L10n.cancel) @@ -36,7 +36,7 @@ enum Prompt { let response = alert.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue let remember = checkbox?.state == .on - if response < apps.count { return Choice(app: apps[response], remember: remember) } + if apps.indices.contains(response) { return Choice(app: apps[response], remember: remember) } if response == apps.count, let other = pickApplication() { return Choice(app: other, remember: remember) } return nil } diff --git a/Sources/App/RouterApp.swift b/Sources/App/RouterApp.swift index abb0e43..91ce7e1 100644 --- a/Sources/App/RouterApp.swift +++ b/Sources/App/RouterApp.swift @@ -15,9 +15,10 @@ final class RouterApp: NSObject, NSApplicationDelegate { func application(_ app: NSApplication, open urls: [URL]) { handledFiles = true + pending += 1 + defer { pending -= 1; finishWhenIdle() } let option = NSEvent.modifierFlags.contains(.option) for url in urls { route(url, optionHeld: option) } - finishWhenIdle() } // MARK: roteamento @@ -32,13 +33,8 @@ final class RouterApp: NSObject, NSApplicationDelegate { let mappings = store.mappings() var decision = Router.decide(info: info, record: record, mappings: mappings, optionHeld: optionHeld) - if decision == .classify { - let guess = Laya.classify(info: info, fileName: url.lastPathComponent) - if let guess, guess.probability >= Laya.minProbability { - decision = .open(guess.app, reason: String(format: "LAYA %.0f%%", guess.probability * 100)) - } else { - decision = .ask(.noPrinter, suggested: guess?.app) - } + if case let .open(app, _) = decision, SlicerApp.installedURL(for: app) == nil { + decision = .ask(.appUnavailable(app.name), suggested: nil) } let app: SlicerApp, reason: String, override: Bool @@ -50,24 +46,20 @@ final class RouterApp: NSObject, NSApplicationDelegate { app = choice.app; reason = "escolha do dono" override = info.printerModel.flatMap(mappings.app(for:)) != choice.app if choice.remember, let model = info.printerModel { store.remember(printer: model, app: choice.app) } - case .classify: - return } guard open(url, with: app) else { return } let uuid = record?.uuid ?? UUID().uuidString store.save(FileRecord(uuid: uuid, printerModel: info.printerModel, app: app, override: override, settingsHash: info.settingsHash), for: url, reason: reason) - // Só o xattr mudou (ex.: escolha com ⌥): pede ao Finder para reler o ícone. + // Notify Finder after updating this file's routing metadata. NSWorkspace.shared.noteFileSystemChanged(url.path) } @discardableResult func open(_ url: URL, with app: SlicerApp) -> Bool { - let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleID) - ?? URL(fileURLWithPath: app.path) - guard FileManager.default.fileExists(atPath: appURL.path) else { - Prompt.error(L10n.notFound(app.name), detail: appURL.path) + guard let appURL = SlicerApp.installedURL(for: app) else { + Prompt.error(L10n.notFound(app.name), detail: app.path) return false } pending += 1 diff --git a/Sources/App/Store.swift b/Sources/App/Store.swift index 8fa2c3a..4bfd64f 100644 --- a/Sources/App/Store.swift +++ b/Sources/App/Store.swift @@ -10,9 +10,9 @@ final class Store { private let coder = JSONEncoder() private let decoder = JSONDecoder() - init() { - try? FileManager.default.createDirectory(at: Self.supportDir, withIntermediateDirectories: true) - let path = Self.supportDir.appendingPathComponent("router.sqlite").path + init(directory: URL = Store.supportDir) { + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let path = directory.appendingPathComponent("router.sqlite").path if sqlite3_open(path, &db) != SQLITE_OK { db = nil; return } exec(""" CREATE TABLE IF NOT EXISTS files(uuid TEXT PRIMARY KEY, path TEXT, record TEXT, updated_at REAL); @@ -71,13 +71,17 @@ final class Store { // MARK: catálogo (indexador) func isCatalogued(_ path: String, size: Int, modified: Date) -> Bool { - !query("SELECT 1 FROM catalog WHERE path = ? AND size = ? AND mtime = ?", - [path, Double(size), modified.timeIntervalSince1970.rounded()]).isEmpty + guard let preview = query("SELECT CASE WHEN kind = 'gcode' AND embedded = 1 THEN 'embedded-gcode' ELSE preview END FROM catalog WHERE path = ? AND size = ? AND mtime = ? AND error = ''", + [path, Double(size), modified.timeIntervalSince1970]).first else { return false } + if preview == "embedded-gcode" { return true } + if size > Indexer.maxRenderBytes { return true } + return !preview.isEmpty && URL(fileURLWithPath: preview).lastPathComponent == PreviewCache.name(for: URL(fileURLWithPath: path)) + && FileManager.default.fileExists(atPath: preview) } func upsertCatalog(_ e: Indexer.Entry) { run("INSERT OR REPLACE INTO catalog VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - [e.path, e.kind, Double(e.size), e.modified.timeIntervalSince1970.rounded(), e.printer ?? "", + [e.path, e.kind, Double(e.size), e.modified.timeIntervalSince1970, e.printer ?? "", Double(e.plates), Double(e.embedded ? 1 : 0), e.preview ?? "", e.error ?? "", Date().timeIntervalSince1970]) } @@ -101,7 +105,7 @@ final class Store { func catalogStats() -> String { query(""" SELECT count(*) || ' arquivos: ' || sum(kind = '3mf') || ' .3mf, ' || sum(kind = 'gcode') || ' .gcode; ' || - sum(embedded = 1) || ' com thumbnail embutida, ' || sum(preview <> '' AND embedded = 0) || ' renderizados, ' || + sum(embedded = 1) || ' com thumbnail embutida, ' || sum(preview <> '') || ' renderizados, ' || sum(error <> '') || ' com erro' FROM catalog """, []).first ?? "catálogo vazio" } diff --git a/Sources/App/main.swift b/Sources/App/main.swift index 4d7a22d..c19dc9b 100644 --- a/Sources/App/main.swift +++ b/Sources/App/main.swift @@ -14,11 +14,12 @@ func describe(_ d: Decision) -> String { switch d { case let .open(app, reason): return "open \(app.name) (\(reason))" case let .ask(why, suggested): return "ask \(why) suggested=\(suggested?.name ?? "-")" - case .classify: return "classify (LAYA)" } } switch args.first { +case "--list-slicers": + for app in SlicerApp.installed() { print("\(app.name)\t\(app.bundleID)\t\(app.path)") } case "--inspect": let store = Store() for path in args.dropFirst() { @@ -27,9 +28,6 @@ case "--inspect": let info = try ThreeMF.info(url: url) let record = store.record(for: url) let decision = Router.decide(info: info, record: record, mappings: store.mappings(), optionHeld: false) - let laya = decision == .classify - ? Laya.classify(info: info, fileName: url.lastPathComponent).map { String(format: "%@ %.0f%%", $0.app.name, $0.probability * 100) } ?? "sem palpite" - : "-" print(""" \(url.lastPathComponent) printer_model: \(info.printerModel ?? "-") brand: \(info.brand ?? "-") @@ -38,7 +36,7 @@ case "--inspect": thumbnail: \(info.embeddedThumbnail ?? "nenhuma (gera preview)") record: \(record.map { "\($0.uuid) \($0.printerModel ?? "-") → \($0.app.name)" } ?? "-") decision: \(describe(decision)) - laya: \(laya) (abre direto a partir de \(Int(Laya.minProbability * 100))%) + target_app: \(Router.expectedApp(info: info, record: record, mappings: store.mappings()).map { "\($0.bundleID) → \($0.path)" } ?? "-") aberto agora: \(OpenProjects.find(url, running: RouterApp.process(pid:)).map { "\($0.bundleID) pid \($0.pid)\($0.dirty ? " (alterações não salvas)" : "")" } ?? "não") """) } catch { @@ -80,8 +78,13 @@ case "--index": let s = Indexer.run(store: Store(), force: true, limit: limit, budget: .infinity) print("achados \(s.found), renderizados \(s.rendered), já ok \(s.skipped), erros \(s.failed)") case "--index-agent": - // Chamado pelo LaunchAgent: só trabalha na tomada e com o Mac ocioso. - Indexer.run(store: Store(), force: false) + // Bootstrap signed as the host for SMAppService, then replace the process image. + // Never render in the Finder handler: LaunchServices would reuse this busy process. + let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/3dSlicerIndexer").path + var argv = ([helper] + args.dropFirst()).map { strdup($0) } + [nil] + execv(helper, &argv) + perror("3dSlicerIndexer") + exit(1) case "--index-status": print("background: \(Indexer.statusText())") print("agora: \(Indexer.whyNotNow() ?? "pronto para indexar (na tomada e ocioso)")") @@ -92,12 +95,13 @@ case "--catalog": case "--background": do { switch args.count > 1 ? args[1] : "status" { - case "on": try Indexer.service.register() + case "on": + try Indexer.service.register() + if Indexer.service.status == .requiresApproval { SMAppService.openSystemSettingsLoginItems() } case "off": try Indexer.service.unregister() default: break } print("background: \(Indexer.statusText())") - if Indexer.service.status == .requiresApproval { SMAppService.openSystemSettingsLoginItems() } } catch { print("erro: \(error.localizedDescription)"); exit(1) } diff --git a/Sources/Core/InstalledSlicers.swift b/Sources/Core/InstalledSlicers.swift new file mode 100644 index 0000000..d55b5b4 --- /dev/null +++ b/Sources/Core/InstalledSlicers.swift @@ -0,0 +1,67 @@ +import AppKit + +extension SlicerApp { + public static func installed(directories: [URL] = applicationDirectories, + registeredURLs: [URL]? = nil, suggested: SlicerApp? = nil) -> [SlicerApp] { + let manager = FileManager.default + var urls = suggested.map { [URL(fileURLWithPath: $0.path)] } ?? [] + for directory in directories { + guard let entries = manager.enumerator(at: directory, includingPropertiesForKeys: nil, + options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { continue } + for case let url as URL in entries { + if url.pathExtension.lowercased() == "app" { + urls.append(url) + entries.skipDescendants() + } else if entries.level >= 3 { + entries.skipDescendants() + } + } + } + urls += registeredURLs ?? known.flatMap { NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0.bundleID) } + var seen = Set() + let apps = urls.compactMap(installation).filter { app in + (isSlicer(app) || app.bundleID == suggested?.bundleID) && seen.insert(app.bundleID).inserted + } + func rank(_ app: SlicerApp) -> Int { + if app.bundleID == suggested?.bundleID { return -1 } + return known.firstIndex { $0.bundleID == app.bundleID } ?? known.count + } + return apps.sorted { + rank($0) == rank($1) ? $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending : rank($0) < rank($1) + } + } + + public static var applicationDirectories: [URL] { + [URL(fileURLWithPath: "/Applications"), FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications")] + } + + /// A LaunchServices registration alone does not prove the app still exists. + /// Preserve an exact recorded installation before considering another copy. + public static func installedURL(for app: SlicerApp) -> URL? { + let saved = URL(fileURLWithPath: app.path) + if installation(at: saved)?.bundleID == app.bundleID { return saved } + return NSWorkspace.shared.urlsForApplications(withBundleIdentifier: app.bundleID) + .first { installation(at: $0)?.bundleID == app.bundleID } + } + + private static func installation(at url: URL) -> SlicerApp? { + guard let bundle = Bundle(url: url), let id = bundle.bundleIdentifier, !id.isEmpty, + id != "com.moraesdev.3dslicerrouter", let executable = bundle.executableURL, + FileManager.default.isExecutableFile(atPath: executable.path) else { return nil } + let name = known.first { $0.bundleID == id }?.name + ?? bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String + ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String + ?? url.deletingPathExtension().lastPathComponent + return SlicerApp(bundleID: id, path: url.path, name: name) + } + + private static func isSlicer(_ app: SlicerApp) -> Bool { + if known.contains(where: { $0.bundleID == app.bundleID }) { return true } + let names = ["prusaslicer", "superslicer", "cura", "ultimakercura", "crealityprint", + "anycubicslicer", "anycubicslicernext", "qidislicer", "qidistudio", "elegooslicer", + "flashprint", "ideamaker", "simplify3d"] + return [app.name, URL(fileURLWithPath: app.path).deletingPathExtension().lastPathComponent].contains { name in + names.contains(name.lowercased().filter { $0.isLetter || $0.isNumber }) + } + } +} diff --git a/Sources/Core/L10n.swift b/Sources/Core/L10n.swift index eeefc09..6a51f3d 100644 --- a/Sources/Core/L10n.swift +++ b/Sources/Core/L10n.swift @@ -22,8 +22,12 @@ public enum L10n { t("A impressora do arquivo mudou de \(from) para \(to).", "The file's printer changed from \(from) to \(to).") } public static var reasonNoPrinter: String { - t("O arquivo não declara impressora e a classificação não teve certeza.", - "The file declares no printer and the classifier was not confident.") + t("O arquivo não declara impressora. Escolha um dos fatiadores instalados.", + "The file declares no printer. Choose one of the installed slicers.") + } + public static func reasonUnavailable(_ app: String) -> String { + t("\(app) não está mais instalado. Escolha outro fatiador.", + "\(app) is no longer installed. Choose another slicer.") } public static var otherApp: String { t("Outro app…", "Other app…") } public static var cancel: String { t("Cancelar", "Cancel") } @@ -35,12 +39,14 @@ public enum L10n { public static func openFailed(_ app: String) -> String { t("Não consegui abrir no \(app)", "Could not open in \(app)") } public static func about(current: String) -> String { t(""" - Abre cada .3mf no fatiador da impressora declarada (Bambu Studio ou Snapmaker Orca). + Abre cada .3mf no fatiador definido para a impressora declarada. + Sem impressora, pergunta entre os fatiadores instalados. Segure ⌥ ao abrir para escolher o app. App padrão de .3mf agora: \(current) """, """ - Opens every .3mf in the slicer of the printer it was made for (Bambu Studio or Snapmaker Orca). + Opens every .3mf in the slicer assigned to its declared printer. + Without a printer, asks you to choose an installed slicer. Hold ⌥ while opening to pick the app. Current default app for .3mf: \(current) @@ -50,15 +56,15 @@ public enum L10n { t("\(file) já está aberto no \(app)", "\(file) is already open in \(app)") } public static func alreadyOpenDirty(_ app: String) -> String { - t("Ele tem alterações não salvas. Recarregar fecha esse projeto no \(app), que pergunta antes de descartar, e reabre o arquivo do disco.", - "It has unsaved changes. Reload closes that project in \(app), which asks before discarding them, and reopens the file from disk.") + t("Há alterações não salvas. Reiniciar fecha esta instância do \(app), que pode conter outras janelas. O fatiador pode perguntar antes de descartar alterações e reabrir o arquivo do disco.", + "There are unsaved changes. Restart closes this \(app) instance, which may contain other windows. The slicer may ask before discarding changes and reopening the file from disk.") } public static var alreadyOpenClean: String { - t("Sem alterações não salvas. Abrir de novo criaria uma segunda janela com o mesmo projeto.", - "No unsaved changes. Opening it again would start a second window with the same project.") + t("Abrir de novo pode criar outra instância com o mesmo projeto. Reiniciar fecha a instância atual, que pode conter outras janelas.", + "Opening again may start another instance with the same project. Restart closes the current instance, which may contain other windows.") } public static func switchTo(_ app: String) -> String { t("Ir para o \(app)", "Switch to \(app)") } - public static var reloadFromDisk: String { t("Recarregar do disco", "Reload from disk") } + public static var reloadFromDisk: String { t("Reiniciar e recarregar", "Restart and reload") } public static var openAnotherCopy: String { t("Abrir outra cópia", "Open another copy") } public static func closeItFirst(_ app: String) -> String { t("Feche o projeto no \(app) e abra o arquivo de novo.", "Close the project in \(app) and open the file again.") diff --git a/Sources/Core/OpenProjects.swift b/Sources/Core/OpenProjects.swift index d6f8548..420af6d 100644 --- a/Sources/Core/OpenProjects.swift +++ b/Sources/Core/OpenProjects.swift @@ -9,13 +9,14 @@ public struct OpenProject: Equatable { public let dirty: Bool } -/// Bambu Studio e Snapmaker Orca (base OrcaSlicer) gravam, por projeto aberto, +/// Bambu Studio, OrcaSlicer e Snapmaker Orca gravam, por projeto aberto, /// `$TMPDIR///##/` com `origin.txt` (caminho do projeto). /// Saída limpa apaga a pasta; sobras de processos mortos são ignoradas pela checagem do PID. -/// Layout lido do código-fonte das versões 02.07 (Bambu) e 2.3.6 (Snapmaker Orca), não é API pública. +/// Layout lido do código-fonte das versões 02.07 (Bambu), 2.5 (OrcaSlicer) e 2.3.6 (Snapmaker Orca), não é API pública. public enum OpenProjects { public static let roots = [ (folder: "bamboo_model", bundleID: "com.bambulab.bambu-studio"), + (folder: "orcaslicer_model", bundleID: "com.orcaslicer.OrcaSlicer"), (folder: "snapmaker_orca_model", bundleID: "com.snapmaker.snapmaker-orca"), ] diff --git a/Sources/Core/PreviewCache.swift b/Sources/Core/PreviewCache.swift index 3697eb1..a2f16db 100644 --- a/Sources/Core/PreviewCache.swift +++ b/Sources/Core/PreviewCache.swift @@ -12,22 +12,25 @@ public enum PreviewCache { }() public static func name(for url: URL) -> String? { - guard let values = try? url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]), + guard let values = try? URL(fileURLWithPath: url.path).resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]), let size = values.fileSize, let modified = values.contentModificationDate else { return nil } let path = url.resolvingSymlinksInPath().standardizedFileURL.path let digest = SHA256.hash(data: Data(path.utf8)).prefix(16).map { String(format: "%02x", $0) }.joined() - return "\(digest)-\(size)-\(Int(modified.timeIntervalSince1970)).png" + // Exact Double precision, shared with SQLite; v2 also expires old all-plate previews. + let stamp = String(modified.timeIntervalSince1970.bitPattern, radix: 16) + return "\(digest)-v2-first-\(size)-\(stamp).png" } - public static func cachedURL(for url: URL) -> URL? { + public static func cachedURL(for url: URL, directory: URL = directory) -> URL? { guard let name = name(for: url) else { return nil } let file = directory.appendingPathComponent(name) return FileManager.default.fileExists(atPath: file.path) ? file : nil } @discardableResult - public static func store(_ png: Data, for url: URL) -> URL? { + public static func store(_ png: Data, for url: URL, directory: URL = directory, expectedName: String? = nil) -> URL? { guard let name = name(for: url) else { return nil } + guard expectedName == nil || expectedName == name else { return nil } try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let file = directory.appendingPathComponent(name) // Remove versões antigas do mesmo arquivo (mesmo prefixo de caminho). diff --git a/Sources/Core/PreviewRenderer.swift b/Sources/Core/PreviewRenderer.swift index 17f4689..aa0b7e3 100644 --- a/Sources/Core/PreviewRenderer.swift +++ b/Sources/Core/PreviewRenderer.swift @@ -6,6 +6,8 @@ import simd /// Preview da mesa: fundo #E8E6E1, mesa clara com contorno escuro, vista isométrica. /// Uma mesa → enquadra a mesa; várias → vista panorâmica de todas. public enum PreviewRenderer { + /// Shared with the idle indexer: very large compressed projects use the saved first-plate fallback. + public static let maxRenderBytes = 250_000_000 /// Cena pronta para render ou para um `SCNView` interativo; `target` é o centro do enquadramento. public struct Prepared { public let scene: SCNScene @@ -24,7 +26,29 @@ public enum PreviewRenderer { """ public static func png(url: URL, info: ThreeMFInfo, size: CGSize = CGSize(width: 1024, height: 1024)) throws -> Data { - try encode(render(url: url, info: info, size: size)) + try encode(render(url: url, info: info, size: size, firstPlateOnly: true)) + } + + public static func thumbnail(url: URL, info: ThreeMFInfo, size: CGSize, + cacheDirectory: URL = PreviewCache.directory) throws -> CGImage { + if let cached = PreviewCache.cachedURL(for: url, directory: cacheDirectory) + .flatMap({ try? Data(contentsOf: $0) }).flatMap(decode) { return cached } + let zip = try ZipArchive(url: url) + do { + let bytes = try URL(fileURLWithPath: url.path).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? .max + guard bytes <= maxRenderBytes else { throw RenderError.tooLarge } + // Quick Look can retain this result until the next save. Never seed its cache + // with an old slicer screenshot when current first-plate geometry can render. + return try render(url: url, info: info, size: size, firstPlateOnly: true) + } catch { + if let embedded = info.embeddedThumbnail.flatMap({ try? zip.read($0) }).flatMap(decode) { return embedded } + throw error + } + } + + static func decode(_ data: Data) -> CGImage? { + guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } + return CGImageSourceCreateImageAtIndex(source, 0, nil) } public static func encode(_ image: CGImage) throws -> Data { @@ -34,8 +58,10 @@ public enum PreviewRenderer { return png } - public static func render(url: URL, info: ThreeMFInfo, size: CGSize) throws -> CGImage { - try render(scene: PrintScene.load(url: url, info: info), info: info, size: size) + public static func render(url: URL, info: ThreeMFInfo, size: CGSize, firstPlateOnly: Bool = false) throws -> CGImage { + var label = info + if firstPlateOnly { label.plateCount = 1 } + return try render(scene: PrintScene.load(url: url, info: info, firstPlateOnly: firstPlateOnly), info: label, size: size) } /// Caminho de extrusão de um G-code, no mesmo estilo de mesa. @@ -218,7 +244,7 @@ public enum PreviewRenderer { } } -public enum RenderError: Error { case noMetal, encode } +public enum RenderError: Error { case noMetal, encode, tooLarge } extension NSColor { convenience init(hex: String) { diff --git a/Sources/Core/PrintScene.swift b/Sources/Core/PrintScene.swift index 520f090..6b54719 100644 --- a/Sources/Core/PrintScene.swift +++ b/Sources/Core/PrintScene.swift @@ -36,12 +36,13 @@ public struct PrintScene { } } - public static func load(url: URL, info: ThreeMFInfo) throws -> PrintScene { + public static func load(url: URL, info: ThreeMFInfo, firstPlateOnly: Bool = false) throws -> PrintScene { let zip = try ZipArchive(url: url) var scene = PrintScene() - scene.beds = bedLayout(count: info.plateCount, min: info.bedMin, max: info.bedMax) + scene.beds = bedLayout(count: firstPlateOnly ? 1 : info.plateCount, min: info.bedMin, max: info.bedMax) let settings = (try? zip.read("Metadata/model_settings.config")).map(ModelSettings.init) ?? ModelSettings() + if firstPlateOnly, info.plateCount > 1, settings.plates.isEmpty { throw PrintSceneError.missingFirstPlate } var models: [String: ModelFile] = [:] func model(_ path: String) -> ModelFile? { if let m = models[path] { return m } @@ -116,6 +117,8 @@ public struct PrintScene { } } for item in main.build { + if firstPlateOnly, let instances = settings.plates.first, + !instances.contains(.init(objectID: item.objectID, instanceID: item.instanceID)) { continue } emit(path: root, id: item.objectID, transform: item.transform, extruder: settings.objectExtruder[item.objectID] ?? 1, top: item.objectID, depth: 0) } @@ -123,11 +126,15 @@ public struct PrintScene { } } +public enum PrintSceneError: Error { case missingFirstPlate } + /// `Metadata/model_settings.config` do Bambu/Orca: extrusora por objeto e por peça. struct ModelSettings { + struct Instance: Hashable { let objectID: String; let instanceID: Int } struct Part { var extruder: Int?; var subtype: String? } var objectExtruder: [String: Int] = [:] var parts: [String: [String: Part]] = [:] + var plates: [Set] = [] init() {} @@ -138,19 +145,28 @@ struct ModelSettings { parser.parse() objectExtruder = delegate.objectExtruder parts = delegate.parts + plates = delegate.plates } private final class Delegate: NSObject, XMLParserDelegate { var objectExtruder: [String: Int] = [:] var parts: [String: [String: Part]] = [:] + var plates: [Set] = [] var object: String? var part: String? var inPlate = false + var inInstance = false + var instanceObject: String? + var instanceID = 0 func parser(_ p: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, attributes a: [String: String]) { switch name { - case "plate": inPlate = true + case "plate": inPlate = true; plates.append([]) + case "model_instance" where inPlate: inInstance = true; instanceObject = nil; instanceID = 0 + case "metadata" where inInstance: + if a["key"] == "object_id" { instanceObject = a["value"] } + if a["key"] == "instance_id" { instanceID = a["value"].flatMap(Int.init) ?? 0 } case "object" where !inPlate: object = a["id"] case "part": part = a["id"] if let o = object, let id = part { parts[o, default: [:]][id] = Part(subtype: a["subtype"]) } @@ -163,6 +179,11 @@ struct ModelSettings { func parser(_ p: XMLParser, didEndElement name: String, namespaceURI: String?, qualifiedName: String?) { switch name { + case "model_instance": + if let id = instanceObject, !plates.isEmpty { + plates[plates.count - 1].insert(Instance(objectID: id, instanceID: instanceID)) + } + inInstance = false; instanceObject = nil case "plate": inPlate = false case "part": part = nil case "object": object = nil @@ -183,12 +204,13 @@ final class ModelFile: NSObject, XMLParserDelegate { } struct Component { let objectID: String; let path: String?; let transform: simd_float4x4 } struct Object { var mesh: Mesh?; var components: [Component] = [] } - struct Item { let objectID: String; let transform: simd_float4x4 } + struct Item { let objectID: String; let instanceID: Int; let transform: simd_float4x4 } private(set) var objects: [String: Object] = [:] private(set) var build: [Item] = [] private var current: String? private var mesh: Mesh? + private var instanceCounts: [String: Int] = [:] init(data: Data) { super.init() @@ -234,8 +256,12 @@ final class ModelFile: NSObject, XMLParserDelegate { let path = a.first(where: { $0.key.hasSuffix(":path") || $0.key == "path" })?.value objects[id]?.components.append(Component(objectID: ref, path: path, transform: Self.transform(a["transform"]))) case "item": - if let ref = a["objectid"], a["printable"] != "0" { - build.append(Item(objectID: ref, transform: Self.transform(a["transform"]))) + if let ref = a["objectid"] { + let instance = instanceCounts[ref, default: 0] + instanceCounts[ref] = instance + 1 + if a["printable"] != "0" { + build.append(Item(objectID: ref, instanceID: instance, transform: Self.transform(a["transform"]))) + } } default: break } diff --git a/Sources/Core/Routing.swift b/Sources/Core/Routing.swift index 6e858fc..8f01a71 100644 --- a/Sources/Core/Routing.swift +++ b/Sources/Core/Routing.swift @@ -13,9 +13,11 @@ public struct SlicerApp: Codable, Equatable, Hashable { public static let bambuStudio = SlicerApp( bundleID: "com.bambulab.bambu-studio", path: "/Applications/BambuStudio.app", name: "Bambu Studio") + public static let orcaSlicer = SlicerApp( + bundleID: "com.orcaslicer.OrcaSlicer", path: "/Applications/OrcaSlicer.app", name: "OrcaSlicer") public static let snapmakerOrca = SlicerApp( bundleID: "com.snapmaker.snapmaker-orca", path: "/Applications/Snapmaker Orca.app", name: "Snapmaker Orca") - public static let known = [bambuStudio, snapmakerOrca] + public static let known = [orcaSlicer, bambuStudio, snapmakerOrca] } /// Decisão gravada no arquivo (xattr) e no índice SQLite. @@ -63,12 +65,12 @@ extension FileRecord { /// Impressora → app. Modelo exato vence marca; as marcas padrão valem mesmo sem SQLite. public struct Mappings { public var byModel: [String: SlicerApp] = [:] - public var byBrand: [String: SlicerApp] = ["Bambu Lab": .bambuStudio, "Snapmaker": .snapmakerOrca] + public var byBrand: [String: SlicerApp] = ["Bambu Lab": .bambuStudio, "Snapmaker": .orcaSlicer, "Prusa": .orcaSlicer] public init() {} public func app(for model: String) -> SlicerApp? { - byModel[model] ?? ThreeMFInfo.brand(of: model).flatMap { byBrand[$0] } + byModel[model] ?? ThreeMFInfo.brand(of: model).flatMap { byBrand[$0] } ?? .orcaSlicer } } @@ -79,26 +81,28 @@ public enum AskReason: Equatable { case unknownPrinter(String) /// Impressora do arquivo mudou para outra marca que não Bambu. case printerChanged(from: String?, to: String) - /// Arquivo sem `printer_model` e o LAYA não teve certeza. + /// Arquivo sem `printer_model` nem escolha manual salva. case noPrinter + /// O app escolhido anteriormente não está mais instalado. + case appUnavailable(String) } public enum Decision: Equatable { case open(SlicerApp, reason: String) case ask(AskReason, suggested: SlicerApp?) - /// Sem `printer_model`: classificar (LAYA) antes de perguntar. - case classify } public enum Router { public static func decide(info: ThreeMFInfo, record: FileRecord?, mappings: Mappings, optionHeld: Bool) -> Decision { let model = info.printerModel let mapped = model.flatMap(mappings.app(for:)) - if optionHeld { return .ask(.manual, suggested: record?.app ?? mapped) } + if optionHeld { return .ask(.manual, suggested: record?.app ?? mapped ?? .orcaSlicer) } guard let model else { - if let record, record.printerModel == nil { return .open(record.app, reason: "lembrado (sem impressora)") } - return .classify + if let record, record.printerModel == nil, record.override { + return .open(record.app, reason: "lembrado (sem impressora)") + } + return .ask(.noPrinter, suggested: nil) } if let record { if record.printerModel == model { return .open(record.app, reason: "lembrado") } @@ -113,12 +117,11 @@ public enum Router { return .ask(.unknownPrinter(model), suggested: nil) } - /// App que o próximo duplo clique deve abrir, sem perguntar nada (ícone do Finder). + /// Read-only target preview for the CLI; asking does not open an application. public static func expectedApp(info: ThreeMFInfo, record: FileRecord?, mappings: Mappings) -> SlicerApp? { switch decide(info: info, record: record, mappings: mappings, optionHeld: false) { case let .open(app, _): return app case let .ask(_, suggested): return suggested ?? record?.app - case .classify: return record?.app } } } diff --git a/Sources/Core/ThreeMF.swift b/Sources/Core/ThreeMF.swift index 935394f..dfec129 100644 --- a/Sources/Core/ThreeMF.swift +++ b/Sources/Core/ThreeMF.swift @@ -25,17 +25,20 @@ public struct ThreeMFInfo { let m = model.trimmingCharacters(in: .whitespaces) if m.isEmpty { return nil } if m.lowercased().hasPrefix("bambu") { return "Bambu Lab" } + if m.lowercased().hasPrefix("prusa") || m.lowercased().hasPrefix("original prusa") { return "Prusa" } return String(m.split(separator: " ").first ?? Substring(m)) } static let thumbnailCandidates = [ - "Auxiliaries/.thumbnails/thumbnail_middle.png", "Metadata/plate_1.png", - "Metadata/thumbnail.png", - "Auxiliaries/.thumbnails/thumbnail_3mf.png", "Metadata/plate_1_small.png", "Metadata/top_1.png", ] + static let singlePlateThumbnailCandidates = [ + "Auxiliaries/.thumbnails/thumbnail_middle.png", + "Metadata/thumbnail.png", + "Auxiliaries/.thumbnails/thumbnail_3mf.png", + ] } public enum ThreeMF { @@ -71,10 +74,11 @@ public enum ThreeMF { } if let settings = try? zip.read("Metadata/model_settings.config") { let text = String(decoding: settings, as: UTF8.self) - info.plateCount = max(1, text.components(separatedBy: "").count - 1) + info.plateCount = max(1, ModelSettings(data: settings).plates.count) info.objectNames = text.allMatches(#"\s*= deadline { + Indexer.write("parou durante preview: limite de 20 minutos") + exit(0) + } +} +monitor.resume() +Indexer.run(store: Store(), force: false) diff --git a/Sources/Preview/PreviewViewController.swift b/Sources/Preview/PreviewViewController.swift index 65c4fab..70164ec 100644 --- a/Sources/Preview/PreviewViewController.swift +++ b/Sources/Preview/PreviewViewController.swift @@ -21,9 +21,8 @@ final class PreviewViewController: NSViewController, QLPreviewingController { } let info = try ThreeMF.info(url: url) if info.plateCount > 1 { - let image = try PreviewCache.cachedURL(for: url).flatMap { try? Data(contentsOf: $0) } - .flatMap { NSBitmapImageRep(data: $0)?.cgImage } - ?? PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1600, height: 1600)) + // The indexer's cache is intentionally first-plate-only; Space keeps its panorama. + let image = try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1600, height: 1600)) DispatchQueue.main.async { self.show(image: image); handler(nil) } } else { let prepared = try PreviewRenderer.prepare(url: url, info: info, aspect: aspect) diff --git a/Sources/Thumbnail/ThumbnailProvider.swift b/Sources/Thumbnail/ThumbnailProvider.swift index adfb395..56e25a9 100644 --- a/Sources/Thumbnail/ThumbnailProvider.swift +++ b/Sources/Thumbnail/ThumbnailProvider.swift @@ -2,11 +2,8 @@ import AppKit import QuickLookThumbnailing /// Thumbnail do Finder para .3mf e .gcode. -/// - .3mf pequeno (lista, < 64 pt): ícone do fatiador em que o arquivo vai abrir. -/// - Médio/grande: imagem embutida pelo fatiador; sem ela, o preview do indexador (cache) ou um render na hora. +/// - .3mf: primeira chapa em todos os tamanhos; cache atual antes da imagem embutida. final class ThumbnailProvider: QLThumbnailProvider { - static let iconThreshold: CGFloat = 64 - override func provideThumbnail(for request: QLFileThumbnailRequest, _ handler: @escaping (QLThumbnailReply?, Error?) -> Void) { let url = request.fileURL let box = request.maximumSize @@ -25,20 +22,7 @@ final class ThumbnailProvider: QLThumbnailProvider { } else { let zip = try ZipArchive(url: url) let info = try ThreeMF.info(zip: zip) - if max(box.width, box.height) < Self.iconThreshold, let icon = slicerIcon(url: url, info: info) { - handler(QLThumbnailReply(contextSize: box) { () -> Bool in - icon.draw(in: NSRect(origin: .zero, size: box)) - return true - }, nil) - return - } - if let embedded = info.embeddedThumbnail.flatMap({ try? zip.read($0) }).flatMap(Self.decode) { - image = embedded - } else if let cached = Self.cached(url) { - image = cached - } else { - image = try PreviewRenderer.render(url: url, info: info, size: CGSize(width: side, height: side)) - } + image = try PreviewRenderer.thumbnail(url: url, info: info, size: CGSize(width: side, height: side)) } let ratio = min(box.width / CGFloat(image.width), box.height / CGFloat(image.height)) let size = CGSize(width: CGFloat(image.width) * ratio, height: CGFloat(image.height) * ratio) @@ -62,11 +46,4 @@ final class ThumbnailProvider: QLThumbnailProvider { PreviewCache.cachedURL(for: url).flatMap { try? Data(contentsOf: $0) }.flatMap(decode) } - /// Mesma regra do roteamento: memória do xattr enquanto a impressora não mudar; senão, a impressora nova. - func slicerIcon(url: URL, info: ThreeMFInfo) -> NSImage? { - guard let app = Router.expectedApp(info: info, record: FileRecord.read(from: url), mappings: Mappings()) else { return nil } - let path = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleID)?.path ?? app.path - guard FileManager.default.fileExists(atPath: path) else { return nil } - return NSWorkspace.shared.icon(forFile: path) - } } diff --git a/Tests/RouterTests.swift b/Tests/RouterTests.swift index 4cca67e..c5ef0f9 100644 --- a/Tests/RouterTests.swift +++ b/Tests/RouterTests.swift @@ -1,7 +1,45 @@ +import AppKit import simd import XCTest final class RouterTests: XCTestCase { + func testBackgroundAgentMigratesToOneFreshRegistrationIdentity() throws { + let app = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("3dSlicerRouter.app") + let folder = app.appendingPathComponent("Contents/Library/LaunchAgents") + let current = "com.moraesdev.3dslicerrouter.previews.v2.plist" + let ownPlists = try FileManager.default.contentsOfDirectory(atPath: folder.path) + .filter { $0.hasPrefix("com.moraesdev.3dslicerrouter.") && $0.hasSuffix(".plist") }.sorted() + XCTAssertEqual(ownPlists, [current], "Ship only the new registration identity; old per-item requirements can retain a previous ad-hoc CDHash") + let plist = folder.appendingPathComponent(current) + guard FileManager.default.fileExists(atPath: plist.path) else { return } + let values = try PropertyListSerialization.propertyList(from: Data(contentsOf: plist), format: nil) as! [String: Any] + XCTAssertEqual(values["Label"] as? String, "com.moraesdev.3dslicerrouter.previews.v2") + XCTAssertEqual(values["BundleProgram"] as? String, "Contents/Helpers/3dSlicerIndexer") + XCTAssertEqual(values["ProgramArguments"] as? [String], ["3dSlicerIndexer"]) + XCTAssertEqual(values["StartInterval"] as? Int, 1800) + } + + func testBackgroundAgentDoesNotLaunchTheFinderHandler() throws { + let app = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + .appendingPathComponent("3dSlicerRouter.app") + let plist = app.appendingPathComponent("Contents/Library/LaunchAgents/\(Indexer.agentPlist)") + let values = try PropertyListSerialization.propertyList(from: Data(contentsOf: plist), format: nil) as! [String: Any] + let program = try XCTUnwrap(values["BundleProgram"] as? String) + let worker = app.appendingPathComponent(program) + XCTAssertTrue(FileManager.default.isExecutableFile(atPath: worker.path)) + let process = Process() + process.executableURL = worker + process.arguments = ["--version"] + let output = Pipe() + process.standardOutput = output + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0) + XCTAssertEqual(String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines), + "3dSlicerIndexer", "The agent must launch the headless helper directly") + } + func info(_ model: String?) -> ThreeMFInfo { var i = ThreeMFInfo() i.printerModel = model @@ -19,11 +57,34 @@ final class RouterTests: XCTestCase { func testBrandRules() { XCTAssertEqual(decide("Bambu Lab A1"), .open(.bambuStudio, reason: "regra Bambu Lab")) XCTAssertEqual(decide("Bambu Lab H2C"), .open(.bambuStudio, reason: "regra Bambu Lab")) - XCTAssertEqual(decide("Snapmaker U1"), .open(.snapmakerOrca, reason: "regra Snapmaker")) + XCTAssertEqual(decide("Snapmaker U1"), .open(officialOrca, reason: "regra Snapmaker")) + } + + var officialOrca: SlicerApp { + SlicerApp(bundleID: "com.orcaslicer.OrcaSlicer", path: "/Applications/OrcaSlicer.app", name: "OrcaSlicer") } - func testUnknownPrinterAsks() { - XCTAssertEqual(decide("Prusa MK4"), .ask(.unknownPrinter("Prusa MK4"), suggested: nil)) + func testUnknownPrinterUsesOfficialOrcaByDefault() { + XCTAssertEqual(decide("Elegoo Centauri Carbon"), .open(officialOrca, reason: "regra Elegoo")) + } + + func testBothOrcaApplicationsCanBeChosenAndRememberedSeparately() throws { + XCTAssertTrue(SlicerApp.known.contains(officialOrca)) + XCTAssertTrue(SlicerApp.known.contains(.snapmakerOrca)) + try withTempDirectory { directory in + let store = Store(directory: directory.appendingPathComponent("store")) + for (index, app) in [officialOrca, .snapmakerOrca].enumerated() { + let file = directory.appendingPathComponent("choice-\(index).3mf") + try Data("synthetic".utf8).write(to: file) + let choice = FileRecord(uuid: "choice-\(index)", printerModel: "Snapmaker U1", app: app, + override: true, settingsHash: nil) + store.save(choice, for: file, reason: "test") + XCTAssertEqual(FileRecord.read(from: file)?.app, app) + XCTAssertEqual(decide("Snapmaker U1", store.record(for: file)), .open(app, reason: "lembrado")) + FileRecord.remove(from: file) + XCTAssertEqual(store.record(for: file)?.app, app, "SQLite must preserve the exact app after a slicer replaces the file") + } + } } func testLearnedModelMapping() { @@ -32,15 +93,81 @@ final class RouterTests: XCTestCase { XCTAssertEqual(decide("Prusa MK4", mappings: m), .open(.snapmakerOrca, reason: "regra Prusa")) } - func testNoPrinterClassifies() { - XCTAssertEqual(decide(nil), .classify) - XCTAssertEqual(decide(nil, record(nil, .bambuStudio)), .open(.bambuStudio, reason: "lembrado (sem impressora)")) + func testPrusaOpensOfficialOrca() { + for model in ["Prusa MK4", "Original Prusa MK4S", "Original Prusa i3 MK3S", "prusa XL"] { + XCTAssertEqual(decide(model), .open(officialOrca, reason: "regra Prusa")) + } + XCTAssertEqual(decide("Prusa MK4", option: true), .ask(.manual, suggested: officialOrca)) + } + + func testNoPrinterAsksUnlessTheOwnerAlreadyChose() { + XCTAssertEqual(decide(nil), .ask(.noPrinter, suggested: nil)) + XCTAssertEqual(decide(nil, record(nil, officialOrca)), .ask(.noPrinter, suggested: nil), + "An old automatic fallback must not suppress the new chooser") + XCTAssertEqual(decide(nil, record(nil, .bambuStudio, override: true)), + .open(.bambuStudio, reason: "lembrado (sem impressora)")) + } + + func testSlicerDiscoveryListsOnlyExecutableInstallationsAndRefreshesAfterRemoval() throws { + try withTempDirectory { directory in + let apps = directory.resolvingSymlinksInPath().appendingPathComponent("Applications") + let orca = try slicerBundle(in: apps, name: "OrcaSlicer", id: "com.orcaslicer.OrcaSlicer") + let bambu = try slicerBundle(in: apps, name: "BambuStudio", id: "com.bambulab.bambu-studio") + let prusa = try slicerBundle(in: apps.appendingPathComponent("3D"), name: "PrusaSlicer", id: "test.prusa") + _ = try slicerBundle(in: apps, name: "TextEditor", id: "test.editor") + let incomplete = try slicerBundle(in: apps, name: "SuperSlicer", id: "test.incomplete") + try FileManager.default.removeItem(at: incomplete.appendingPathComponent("Contents/MacOS/slicer")) + let stale = SlicerApp(bundleID: "test.removed", path: apps.appendingPathComponent("Missing.app").path, name: "Removed") + let installed = SlicerApp.installed(directories: [apps], registeredURLs: [], suggested: stale) + XCTAssertEqual(installed.map(\.bundleID), ["com.orcaslicer.OrcaSlicer", "com.bambulab.bambu-studio", "test.prusa"]) + XCTAssertEqual(installed.map { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path }, + [orca, bambu, prusa].map { $0.resolvingSymlinksInPath().path }) + try FileManager.default.removeItem(at: prusa) + XCTAssertEqual(SlicerApp.installed(directories: [apps], registeredURLs: [prusa]).map(\.bundleID), + ["com.orcaslicer.OrcaSlicer", "com.bambulab.bambu-studio"]) + } + } + + func testDiscoveryFindsRenamedAppsAndSymlinksAndKeepsInstalledSuggestionFirst() throws { + try withTempDirectory { directory in + let renamed = try slicerBundle(in: directory, name: "Renamed", id: "com.orcaslicer.OrcaSlicer") + let runtime = try slicerBundle(in: directory.appendingPathComponent("runtime"), name: "Snapmaker Orca", id: "com.snapmaker.snapmaker-orca") + let apps = directory.appendingPathComponent("Applications") + try FileManager.default.createDirectory(at: apps, withIntermediateDirectories: true) + let link = apps.appendingPathComponent("Snapmaker Orca.app") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: runtime) + let suggestion = SlicerApp(bundleID: "com.snapmaker.snapmaker-orca", path: link.path, name: "Snapmaker Orca") + let installed = SlicerApp.installed(directories: [apps], registeredURLs: [renamed, link], suggested: suggestion) + XCTAssertEqual(installed.map(\.bundleID), ["com.snapmaker.snapmaker-orca", "com.orcaslicer.OrcaSlicer"]) + XCTAssertEqual(installed.first?.path, link.path) + XCTAssertEqual(installed.last?.path, renamed.path) + try FileManager.default.removeItem(at: runtime) + XCTAssertEqual(SlicerApp.installed(directories: [apps], registeredURLs: [link, renamed], suggested: suggestion).map(\.bundleID), + ["com.orcaslicer.OrcaSlicer"], "A stale registration or dangling symlink is not an installation") + } + } + + func slicerBundle(in directory: URL, name: String, id: String) throws -> URL { + let app = directory.appendingPathComponent(name + ".app") + let macos = app.appendingPathComponent("Contents/MacOS") + try FileManager.default.createDirectory(at: macos, withIntermediateDirectories: true) + let plist: [String: Any] = ["CFBundleIdentifier": id, "CFBundleName": name, + "CFBundleExecutable": "slicer", "CFBundlePackageType": "APPL"] + try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) + .write(to: app.appendingPathComponent("Contents/Info.plist")) + let executable = macos.appendingPathComponent("slicer") + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + return app } func testSamePrinterKeepsRememberedOverride() { // U1 aberto à mão no Bambu Studio continua indo para o Bambu enquanto a impressora não mudar. XCTAssertEqual(decide("Snapmaker U1", record("Snapmaker U1", .bambuStudio, override: true)), .open(.bambuStudio, reason: "lembrado")) + // Changing the default must also preserve previous automatic Snapmaker decisions. + XCTAssertEqual(decide("Snapmaker U1", record("Snapmaker U1", .snapmakerOrca)), + .open(.snapmakerOrca, reason: "lembrado")) } func testBambuToBambuDoesNotAsk() { @@ -55,7 +182,7 @@ final class RouterTests: XCTestCase { func testBambuToSnapmakerAsks() { XCTAssertEqual(decide("Snapmaker U1", record("Bambu Lab A1", .bambuStudio)), - .ask(.printerChanged(from: "Bambu Lab A1", to: "Snapmaker U1"), suggested: .snapmakerOrca)) + .ask(.printerChanged(from: "Bambu Lab A1", to: "Snapmaker U1"), suggested: officialOrca)) } func testOptionAlwaysAsks() { @@ -63,14 +190,14 @@ final class RouterTests: XCTestCase { .ask(.manual, suggested: .bambuStudio)) } - func testFinderIconFollowsPrinterChange() { + func testExpectedAppFollowsPrinterChange() { let m = Mappings() // Escolha manual vale enquanto a impressora não muda. XCTAssertEqual(Router.expectedApp(info: info("Snapmaker U1"), record: record("Snapmaker U1", .bambuStudio, override: true), mappings: m), .bambuStudio) // Retargeted para A1: o ícone já mostra o Bambu Studio. XCTAssertEqual(Router.expectedApp(info: info("Bambu Lab A1"), record: record("Snapmaker U1", .snapmakerOrca), mappings: m), .bambuStudio) // Mudou para Snapmaker: o router vai perguntar, o ícone mostra a sugestão. - XCTAssertEqual(Router.expectedApp(info: info("Snapmaker U1"), record: record("Bambu Lab A1", .bambuStudio), mappings: m), .snapmakerOrca) + XCTAssertEqual(Router.expectedApp(info: info("Snapmaker U1"), record: record("Bambu Lab A1", .bambuStudio), mappings: m), officialOrca) XCTAssertNil(Router.expectedApp(info: info(nil), record: nil, mappings: m)) } @@ -102,6 +229,18 @@ final class RouterTests: XCTestCase { XCTAssertNil(OpenProjects.find(file, tmp: tmp) { _ in .init(bundleID: "com.apple.TextEdit", launched: nil) }) } + func testDetectsOfficialOrcaProjectWithoutConfusingTheSnapmakerFork() throws { + try withTempDirectory { tmp in + let file = tmp.appendingPathComponent("synthetic.3mf") + let session = tmp.appendingPathComponent("orcaslicer_model/Sun_Nov_08/10_00_00#444#1") + try FileManager.default.createDirectory(at: session, withIntermediateDirectories: true) + try file.path.write(to: session.appendingPathComponent("origin.txt"), atomically: true, encoding: .utf8) + let found = OpenProjects.find(file, tmp: tmp) { _ in .init(bundleID: self.officialOrca.bundleID, launched: nil) } + XCTAssertEqual(found, OpenProject(pid: 444, bundleID: officialOrca.bundleID, origin: file.path, dirty: false)) + XCTAssertNil(OpenProjects.find(file, tmp: tmp) { _ in .init(bundleID: SlicerApp.snapmakerOrca.bundleID, launched: nil) }) + } + } + func paintLeaves(_ code: String) -> [(centre: SIMD3, state: Int)] { var out: [(SIMD3, Int)] = [] PaintDecoder.decode(code[...], SIMD3(0, 0, 0), SIMD3(2, 0, 0), SIMD3(0, 2, 0)) { a, b, c, s in @@ -188,9 +327,9 @@ final class RouterTests: XCTestCase { ("bambu-a1-keychain-tray.3mf", .open(.bambuStudio, reason: "regra Bambu Lab")), ("bambu-a1mini-calibration.3mf", .open(.bambuStudio, reason: "regra Bambu Lab")), ("bambu-h2d-four-plates.3mf", .open(.bambuStudio, reason: "regra Bambu Lab")), - ("snapmaker-u1-four-colors.3mf", .open(.snapmakerOrca, reason: "regra Snapmaker")), - ("unknown-printer-prusa-mk4s.3mf", .ask(.unknownPrinter("Original Prusa MK4S"), suggested: nil)), - ("no-printer-declared.3mf", .classify), + ("snapmaker-u1-four-colors.3mf", .open(officialOrca, reason: "regra Snapmaker")), + ("unknown-printer-prusa-mk4s.3mf", .open(officialOrca, reason: "regra Prusa")), + ("no-printer-declared.3mf", .ask(.noPrinter, suggested: nil)), ] for (name, expected) in cases { let info = try sample(name) @@ -226,4 +365,256 @@ final class RouterTests: XCTestCase { FileRecord.remove(from: url) XCTAssertNil(FileRecord.read(from: url)) } + + func testQuickLookExtensionsCarrySandboxEntitlements() throws { + let app = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("3dSlicerRouter.app") + for name in ["Thumbnail", "Preview"] { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign") + process.arguments = ["-d", "--entitlements", ":-", app.appendingPathComponent("Contents/PlugIns/SlicerRouter\(name).appex").path] + let output = Pipe() + process.standardOutput = output + process.standardError = FileHandle.nullDevice + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + XCTAssertEqual(process.terminationStatus, 0) + XCTAssertFalse(data.isEmpty, "\(name) must carry signed entitlements, not just an entitlements file in source") + if data.isEmpty { continue } + let values = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String: Any] + XCTAssertEqual(values["com.apple.security.app-sandbox"] as? Bool, true) + XCTAssertEqual(values["com.apple.security.files.user-selected.read-only"] as? Bool, true) + } + } + + func testEmbeddedThumbnailRepresentsFirstPlate() throws { + try withArchive(files: [ + "Metadata/model_settings.config": Data("".utf8), + "Metadata/plate_1.png": Data([1]), + "Auxiliaries/.thumbnails/thumbnail_middle.png": Data([2]), + ]) { url in + XCTAssertEqual(try ThreeMF.info(url: url).embeddedThumbnail, "Metadata/plate_1.png") + } + try withArchive(files: [ + "Metadata/model_settings.config": Data("".utf8), + "Auxiliaries/.thumbnails/thumbnail_middle.png": Data([2]), + ]) { url in + XCTAssertNil(try ThreeMF.info(url: url).embeddedThumbnail, "A multi-plate overview cannot stand in for the first plate") + } + } + + func testSameSizeSubsecondSaveInvalidatesPreviewName() throws { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("preview-\(UUID().uuidString).3mf") + defer { try? FileManager.default.removeItem(at: url) } + try Data([1]).write(to: url) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1_700_000_000.1)], ofItemAtPath: url.path) + let before = try XCTUnwrap(PreviewCache.name(for: URL(fileURLWithPath: url.path))) + try Data([2]).write(to: url) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1_700_000_000.2)], ofItemAtPath: url.path) + XCTAssertNotEqual(PreviewCache.name(for: URL(fileURLWithPath: url.path)), before) + } + + func testStaticPreviewSelectsTheFirstPlatesActualInstance() throws { + // Both build items share an object ID. Plate 1 contains its SECOND instance. + let first = #""# + let other = #""# + let instance: (Int) -> String = { #""# } + let multiple = "\(instance(1))\(instance(0))" + let single = "\(instance(0))" + try withArchive(files: sceneFiles(build: other + first, settings: multiple)) { multi in + try withArchive(files: sceneFiles(build: first, settings: single)) { expected in + let info = try ThreeMF.info(url: multi) + let scene = try PrintScene.load(url: multi, info: info) + XCTAssertEqual(scene.beds.count, 2, "The rich Space scene must retain every plate") + XCTAssertGreaterThan(scene.boundsMax.x, 500) + let firstScene = try PrintScene.load(url: multi, info: info, firstPlateOnly: true) + XCTAssertEqual(firstScene.beds.count, 1) + XCTAssertEqual(firstScene.triangleCount, 1) + XCTAssertEqual(firstScene.boundsMax.x, 50, "Plate 1 contains the second build instance at x=20, not the one at x=500") + let size = CGSize(width: 256, height: 256) + let expectedPNG = try PreviewRenderer.png(url: expected, info: ThreeMF.info(url: expected), size: size) + let actualPNG = try PreviewRenderer.png(url: multi, info: info, size: size) + XCTAssertLessThan(try pixelDifference(actualPNG, expectedPNG), 0.5, "Allow subpixel raster jitter, not other plates") + let panorama = try PreviewRenderer.encode(PreviewRenderer.render(url: multi, info: info, size: size)) + XCTAssertGreaterThan(try pixelDifference(panorama, expectedPNG), 1, "The comparison must reject the old all-plate image") + } + } + } + + func testCurrentIndexedGeometryOverridesStaleEmbeddedImage() throws { + let png = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")! + var files = sceneFiles(build: #""#, settings: "") + files["Metadata/plate_1.png"] = png + try withArchive(files: files) { url in + let directory = url.deletingLastPathComponent().appendingPathComponent("previews") + let info = try ThreeMF.info(url: url) + let fresh = try PreviewRenderer.png(url: url, info: info, size: CGSize(width: 128, height: 128)) + XCTAssertNotNil(PreviewCache.store(fresh, for: url, directory: directory)) + let image = try PreviewRenderer.thumbnail(url: url, info: info, size: CGSize(width: 256, height: 256), cacheDirectory: directory) + XCTAssertEqual(image.width, 128, "Use the current indexed geometry instead of the old embedded 1px image") + } + } + + func testColdThumbnailRendersCurrentGeometryBeforeStaleEmbeddedImage() throws { + let size = CGSize(width: 128, height: 128) + var files = sceneFiles(build: #""#, settings: "") + let model = String(decoding: files["3D/3dmodel.model"]!, as: UTF8.self) + .replacingOccurrences(of: "30", with: "160") + files["3D/3dmodel.model"] = Data(model.utf8) + try withArchive(files: files) { original in + let oldBluePNG = try PreviewRenderer.png(url: original, info: ThreeMF.info(url: original), size: size) + var changed = files + let config = String(decoding: changed["Metadata/project_settings.config"]!, as: UTF8.self) + .replacingOccurrences(of: "#2F6FED", with: "#EE6B24") + changed["Metadata/project_settings.config"] = Data(config.utf8) + changed["Metadata/plate_1.png"] = oldBluePNG + try withArchive(files: changed) { current in + let info = try ThreeMF.info(url: current) + let freshOrangePNG = try PreviewRenderer.png(url: current, info: info, size: size) + let emptyCache = current.deletingLastPathComponent().appendingPathComponent("no-indexed-cache") + let actual = try PreviewRenderer.encode(PreviewRenderer.thumbnail(url: current, info: info, size: size, cacheDirectory: emptyCache)) + XCTAssertGreaterThan(try pixelDifference(oldBluePNG, freshOrangePNG), 1, "The fixture must distinguish old blue from current orange geometry") + XCTAssertLessThan(try pixelDifference(actual, freshOrangePNG), 0.5, "Never seed the system cache with an old embedded image while current geometry can render") + } + } + } + + func testUnrenderableGeometryCanUseFirstPlateEmbeddedFallback() throws { + let png = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")! + try withArchive(files: ["Metadata/plate_1.png": png]) { url in + let image = try PreviewRenderer.thumbnail(url: url, info: ThreeMF.info(url: url), size: CGSize(width: 128, height: 128), + cacheDirectory: url.deletingLastPathComponent().appendingPathComponent("no-indexed-cache")) + XCTAssertEqual(image.width, 1, "An unavailable model may fall back to the saved first-plate image") + } + } + + func testCatalogRetriesFailedAndMissingPreviews() throws { + try withArchive(files: sceneFiles(build: #""#, settings: "")) { url in + let directory = url.deletingLastPathComponent() + let store = Store(directory: directory.appendingPathComponent("database")) + let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let size = try XCTUnwrap(values.fileSize), modified = try XCTUnwrap(values.contentModificationDate) + var entry = Indexer.Entry(path: url.path, kind: "3mf", size: size, modified: modified) + entry.error = "render failed" + store.upsertCatalog(entry) + XCTAssertFalse(store.isCatalogued(url.path, size: size, modified: modified)) + entry.error = nil + entry.preview = PreviewCache.store(Data([1]), for: url, directory: directory.appendingPathComponent("previews"))?.path + store.upsertCatalog(entry) + XCTAssertTrue(store.isCatalogued(url.path, size: size, modified: modified)) + try FileManager.default.removeItem(atPath: XCTUnwrap(entry.preview)) + XCTAssertFalse(store.isCatalogued(url.path, size: size, modified: modified)) + } + } + + func testCatalogDistinguishesSubsecondRevisions() throws { + try withArchive(files: ["data": Data([1])]) { url in + let store = Store(directory: url.deletingLastPathComponent().appendingPathComponent("database")) + let first = Date(timeIntervalSince1970: 1_700_000_000.1) + let second = Date(timeIntervalSince1970: 1_700_000_000.2) + let entry = Indexer.Entry(path: url.path, kind: "3mf", size: 1, modified: first) + store.upsertCatalog(entry) + XCTAssertFalse(store.isCatalogued(url.path, size: 1, modified: second)) + } + } + + func testIndexerRendersCurrentGeometryEvenWithEmbeddedImage() throws { + var files = sceneFiles(build: #""#, settings: "") + files["Metadata/plate_1.png"] = Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")! + try withArchive(files: files) { url in + let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let result = Indexer.index(url, size: try XCTUnwrap(values.fileSize), modified: try XCTUnwrap(values.contentModificationDate), + cacheDirectory: url.deletingLastPathComponent().appendingPathComponent("previews")) + XCTAssertNil(result.error) + XCTAssertTrue(result.embedded) + XCTAssertTrue(result.rendered, "The idle pass must regenerate current geometry even if the slicer image is old") + let png = try Data(contentsOf: URL(fileURLWithPath: XCTUnwrap(result.preview))) + XCTAssertEqual(PreviewRenderer.decode(png)?.width, 1024) + } + } + + func testIndexerRejectsSaveWhileReadingSourceMetadata() throws { + let original = sceneFiles(build: #""#, settings: "") + var changed = original + changed["Metadata/project_settings.config"] = Data(##"{"printer_model":"Snapmaker U1","filament_colour":["#EE6B24"]}"##.utf8) + try withArchive(files: original) { url in + try withArchive(files: changed) { replacement in + let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let cache = url.deletingLastPathComponent().appendingPathComponent("previews") + let entry = Indexer.index(url, size: try XCTUnwrap(values.fileSize), + modified: try XCTUnwrap(values.contentModificationDate), cacheDirectory: cache) { source in + let oldInfo = try ThreeMF.info(url: source) + try Data(contentsOf: replacement).write(to: source, options: .atomic) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1_800_000_000)], ofItemAtPath: source.path) + return oldInfo + } + XCTAssertEqual(entry.error, "changedDuringRender") + XCTAssertFalse(entry.rendered) + XCTAssertNil(PreviewCache.cachedURL(for: url, directory: cache)) + } + } + } + + func testCacheRejectsAResultFromBeforeAConcurrentSave() throws { + try withArchive(files: ["data": Data([1])]) { url in + let old = try XCTUnwrap(PreviewCache.name(for: url)) + try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1_700_000_000.5)], ofItemAtPath: url.path) + let cache = url.deletingLastPathComponent().appendingPathComponent("previews") + XCTAssertNil(PreviewCache.store(Data([1]), for: url, directory: cache, expectedName: old)) + XCTAssertNil(PreviewCache.cachedURL(for: url, directory: cache)) + } + } + + func sceneFiles(build: String, settings: String) -> [String: Data] { + let model = """ + + + + + \(build) + """ + return ["3D/3dmodel.model": Data(model.utf8), "Metadata/model_settings.config": Data(settings.utf8), + "Metadata/project_settings.config": Data(##"{"printer_model":"Snapmaker U1","filament_colour":["#2F6FED"]}"##.utf8)] + } + + func pixelDifference(_ a: Data, _ b: Data) throws -> Double { + let lhs = try XCTUnwrap(NSBitmapImageRep(data: a)), rhs = try XCTUnwrap(NSBitmapImageRep(data: b)) + XCTAssertEqual(lhs.pixelsWide, rhs.pixelsWide) + XCTAssertEqual(lhs.pixelsHigh, rhs.pixelsHigh) + XCTAssertEqual(lhs.samplesPerPixel, rhs.samplesPerPixel) + let l = try XCTUnwrap(lhs.bitmapData), r = try XCTUnwrap(rhs.bitmapData) + var total = 0 + for y in 0.. Void) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("router-test-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try body(directory) + } + + func withArchive(files: [String: Data], body: (URL) throws -> Void) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("router-test-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + for (name, data) in files { + let file = directory.appendingPathComponent(name) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: file) + } + let archive = directory.appendingPathComponent("fixture.3mf") + let zip = Process() + zip.executableURL = URL(fileURLWithPath: "/usr/bin/zip") + zip.currentDirectoryURL = directory + zip.arguments = ["-q", "-r", archive.path] + files.keys.sorted() + try zip.run(); zip.waitUntilExit() + XCTAssertEqual(zip.terminationStatus, 0) + try body(archive) + } } diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 11dad81..34c9330 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -2,117 +2,111 @@ [Português](INSTALL.pt-BR.md) -## Dependencies +## Requirements -| | What | Needed for | -|---|---|---| -| **Runtime** | macOS 14 Sonoma or newer (Apple silicon or Intel) | running the app | -| | [Bambu Studio](https://bambulab.com/en/download/studio) and/or [Snapmaker Orca](https://www.snapmaker.com/) in `/Applications` | the slicers it routes to | -| | *(optional)* a local [LAYA classifier](../README.md#files-with-no-printer-optional) | files that declare no printer | -| **Build** | Xcode 15 or newer (Command Line Tools alone are not enough) | compiling | -| | [XcodeGen](https://github.com/yonaskolb/XcodeGen): `brew install xcodegen` | generating the Xcode project | -| *Optional* | [duti](https://github.com/moretension/duti): `brew install duti` | switching default apps from the terminal | -| | Python 3 | regenerating `samples/` only | +- macOS 14 or newer, on Apple silicon or Intel. +- At least one installed slicer that can open 3MF files, such as OrcaSlicer, Bambu Studio or Snapmaker Orca. +- To build: Xcode 15 or newer, its command-line tools, and [XcodeGen](https://github.com/yonaskolb/XcodeGen). -There are **no third-party libraries**. Zip reading, SQLite, SceneKit rendering, Quick Look and -LaunchServices all come from macOS. +The app uses native macOS frameworks. There is no package manager dependency at runtime, network service, AI model, account or API key. -**Permissions:** none. The app does not ask for Accessibility, Screen Recording or Full Disk Access. -macOS hands it only the file you double-clicked. The plate preview is rendered off-screen and is not a -screenshot of any window. - -## Option A: build from source (recommended) +## Build from source ```sh brew install xcodegen git clone https://github.com/MoraesGil/3dSlicerRouter.git cd 3dSlicerRouter -./scripts/build.sh --install -/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter --set-default +./scripts/build.sh --test --install ``` -`build.sh --install`: +The script builds a universal Release app, signs the helper and extensions before the host app, verifies the signatures and extension entitlements, then installs in `/Applications/3dSlicerRouter.app`. + +If Xcode's build service is unavailable, use the same sources and SDK through the native CLI backend: -1. generates `SlicerRouter.xcodeproj` and builds Release with an ad hoc signature; -2. copies the app to `/Applications/3dSlicerRouter.app` and registers it with LaunchServices; -3. registers both Quick Look extensions (thumbnail and preview); -4. launches the app once in the background (`--version`), because macOS only activates the extensions - of an ad hoc signed app after its first launch. +```sh +./scripts/build.sh --native --test --install +``` -`--set-default` makes the router the default app for `.3mf`. You can do the same in Finder: select any -`.3mf` → **Get Info** → **Open with: 3dSlicerRouter** → **Change All…**. +Both backends require Xcode. The native backend uses `swiftc`, `lipo` and `xctest`; it does not install another toolchain. -### Check it +For terminal use, add this alias to your shell configuration: ```sh -/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter --inspect samples/*.3mf -duti -x 3mf # should print 3dSlicerRouter +alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter ``` -Finder may keep old thumbnails cached for a while. `qlmanage -r cache` and relaunching Finder -(⌥ + right-click the Finder icon in the Dock → *Relaunch*) refresh them. +## First launch and approvals + +1. Open **3dSlicerRouter** from Applications. Choose **Make default for .3mf**. This keeps the router as the default; individual files can still open in different slicers. +2. Finder thumbnails and Quick Look use the two bundled extensions. If macOS has disabled them, review **System Settings → General → Login Items & Extensions → Quick Look**. The wording can vary by macOS version. +3. Background pre-rendering is optional. Enable it explicitly with `3dSlicerRouter --background on`. If approval is pending, the app opens the native Login Items settings pane so you can approve it yourself. + +Opening a selected file and rendering its preview do not require Accessibility or Screen Recording. The optional indexer can trigger macOS requests for protected folders or removable volumes. Registration approval and successful worker execution are separate states; use `--index-status` and the local log to diagnose failures. + +## Signing and downloads + +The default build is **ad-hoc signed**. It is not Developer ID signed or notarized. A valid local signature does not prove that Gatekeeper will accept a downloaded archive on another Mac. + +Prebuilt archives, when available, are under [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). Check the version and source before running one. Building locally is the supported route while notarized distribution remains on the roadmap. Do not disable Gatekeeper or system security to install this app. + +## Verify the installation + +```sh +3dSlicerRouter --version +3dSlicerRouter --list-slicers +3dSlicerRouter --inspect samples/*.3mf +codesign --verify --deep --strict /Applications/3dSlicerRouter.app +``` -## Option B: prebuilt download +The slicer list is built from valid installations. Removed apps, broken symlinks and stale LaunchServices registrations do not become picker buttons. The sample without printer metadata asks which installed slicer to use. -1. Download `3dSlicerRouter.zip` from [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). -2. Unzip and drag **3dSlicerRouter.app** to **/Applications**. -3. The build is ad hoc signed, not notarized, so remove the download quarantine once: - ```sh - xattr -dr com.apple.quarantine /Applications/3dSlicerRouter.app - ``` -4. Open the app once from `/Applications`. A small window explains what it does; click - **Make default for .3mf**. +To check file association, use Finder: select a `.3mf` → **Get Info** → **Open with**. It should name **3dSlicerRouter**. You can set it from the CLI with `3dSlicerRouter --set-default`. + + +### Ad-hoc helper limitation + +Automatic indexer startup remains experimental in ad-hoc builds. macOS may reject a launch with +`EX_CONFIG` (78) or `Launch Constraint Violation` even when registration appears enabled. This was +observed locally; disabling system security is not a supported fix. On-demand previews remain +available. Use `--render` or foreground `--index` when needed. ## Update ```sh -cd 3dSlicerRouter && git pull && ./scripts/build.sh --install +git pull --ff-only +./scripts/build.sh --test --install ``` -Your mappings and per-file memory are kept. +The installer preserves the optional indexer's enabled state and registers the updated extensions. Printer mappings and per-file choices remain in the user's application data. Recheck any approvals requested by macOS after an update. ## Uninstall ```sh -./scripts/uninstall.sh # remove the app + data, hand .3mf to Bambu Studio -./scripts/uninstall.sh com.snapmaker.snapmaker-orca # …or hand .3mf to another app -./scripts/uninstall.sh --purge-xattrs ~/Downloads # also strip the router's memory from files there +./scripts/uninstall.sh +``` + +This removes the app, stops its optional agent, deletes its local catalog, preview cache and logs, and assigns `.3mf` to Bambu Studio when `duti` is available. To choose a different installed replacement: + +```sh +./scripts/uninstall.sh com.orcaslicer.OrcaSlicer ``` -What the script does, if you prefer to do it by hand: - -0. **Turn off the background indexer** (if you enabled it): `3dSlicerRouter --background off`. -1. **Remove the app and its Quick Look extensions.** - ```sh - /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -u /Applications/3dSlicerRouter.app - rm -rf /Applications/3dSlicerRouter.app - ``` -2. **Give `.3mf` back to a slicer, after removing the app** (the app owns the `org.3mf.3mf` type): - `duti -s com.bambulab.bambu-studio .3mf all`, or in Finder: **Get Info** → **Open with** → choose the - slicer → **Change All…**. -3. **Delete its data.** - ```sh - rm -rf ~/Library/Application\ Support/3dSlicerRouter # SQLite index, catalog and previews - rm -rf ~/Library/Logs/3dSlicerRouter # indexer log - defaults delete com.moraesdev.3dslicerrouter 2>/dev/null # settings (LAYA endpoint) - qlmanage -r cache # drop cached thumbnails - ``` -4. *(Optional)* **Remove the per-file memory.** Each routed file carries the extended attribute - `com.moraesdev.slicer-router`. It is harmless metadata, but you can strip it: - ```sh - find ~/Downloads -name '*.3mf' -exec xattr -d com.moraesdev.slicer-router {} \; 2>/dev/null - ``` - -Nothing else is installed. The only background item is the optional indexer, which lives inside the -app bundle and disappears with it; there are no kernel or system extensions. +Without `duti`, choose the replacement in Finder's **Get Info → Open with → Change All…**. No printer or slicer settings are deleted. + +Per-file routing attributes are harmless metadata and are not removed by default. To explicitly remove them from a folder: + +```sh +./scripts/uninstall.sh --purge-xattrs /path/to/your/3mf-folder +``` ## Troubleshooting -| Symptom | Fix | +| Symptom | Check | |---|---| -| Double-click still opens a slicer directly | That file has a Finder *Always Open With* override: `xattr -d com.apple.LaunchServices.OpenWith file.3mf` | -| No thumbnails or previews | Launch the app once (`open -a 3dSlicerRouter --args --version`), then `qlmanage -r cache` | -| `--set-default` points to a build folder | Build copies share the bundle id. Run `./scripts/build.sh --install` again; it unregisters them | -| "App is damaged" / cannot be opened (download) | `xattr -dr com.apple.quarantine /Applications/3dSlicerRouter.app` | -| A file keeps going to the wrong slicer | `3dSlicerRouter --forget file.3mf`, or hold ⌥ while opening to pick again | -| Testing thumbnails from the terminal hangs | `qlmanage -t` is unreliable with modern extensions. Look at Finder or use `QLThumbnailGenerator` | +| Double-click bypasses the router | Finder may have a per-file **Always Open With** override. Review it in Get Info. | +| Thumbnail is old | Save the project, confirm the Quick Look extensions are enabled, and request the preview again. An embedded-image fallback may be old. | +| The wrong app opens | Hold Option when opening to choose again, or use `--forget file.3mf`. | +| Background status is enabled but nothing renders | Check idle/power conditions, the background job's execution state and `~/Library/Logs/3dSlicerRouter/indexer.log`. Enabled registration alone does not prove a completed run. | +| A large project has only its saved preview | Compressed projects above 250 MB use the embedded first-plate fallback. | + +Please report issues with the macOS version, app version and sanitized `--inspect` output. Do not attach credentials, customer models or private file paths. diff --git a/docs/INSTALL.pt-BR.md b/docs/INSTALL.pt-BR.md index c4cc5b3..483daf1 100644 --- a/docs/INSTALL.pt-BR.md +++ b/docs/INSTALL.pt-BR.md @@ -2,117 +2,111 @@ [English](INSTALL.md) -## Dependências +## Requisitos -| | O quê | Para | -|---|---|---| -| **Para rodar** | macOS 14 Sonoma ou mais novo (Apple silicon ou Intel) | executar o app | -| | [Bambu Studio](https://bambulab.com/en/download/studio) e/ou [Snapmaker Orca](https://www.snapmaker.com/) em `/Applications` | os fatiadores de destino | -| | *(opcional)* um [classificador LAYA](../README.pt-BR.md#arquivos-sem-impressora-opcional) local | arquivos sem impressora declarada | -| **Para compilar** | Xcode 15 ou mais novo (só o Command Line Tools não basta) | compilar | -| | [XcodeGen](https://github.com/yonaskolb/XcodeGen): `brew install xcodegen` | gerar o projeto Xcode | -| *Opcional* | [duti](https://github.com/moretension/duti): `brew install duti` | trocar o app padrão pelo terminal | -| | Python 3 | só para regerar `samples/` | +- macOS 14 ou mais novo, em Apple silicon ou Intel. +- Pelo menos um fatiador instalado que abra arquivos 3MF, como OrcaSlicer, Bambu Studio ou Snapmaker Orca. +- Para compilar: Xcode 15 ou mais novo, suas ferramentas de linha de comando e [XcodeGen](https://github.com/yonaskolb/XcodeGen). -**Nenhuma biblioteca de terceiros.** Leitura de zip, SQLite, render em SceneKit, Quick Look e -LaunchServices são todos do próprio macOS. +O app usa frameworks nativos do macOS. Não exige dependência de package manager em execução, serviço de rede, modelo de IA, conta nem API key. -**Permissões:** nenhuma. O app não pede Acessibilidade, Gravação de Tela nem Acesso Total ao Disco. -O macOS entrega a ele só o arquivo em que você clicou. O preview da mesa é renderizado fora da tela e -não é screenshot de janela nenhuma. - -## Opção A: compilar do código (recomendado) +## Compilar a partir do código ```sh brew install xcodegen git clone https://github.com/MoraesGil/3dSlicerRouter.git cd 3dSlicerRouter -./scripts/build.sh --install -/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter --set-default +./scripts/build.sh --test --install +``` + +O script gera um app universal em Release. Ele assina o helper e as extensões antes do app principal, verifica as assinaturas e os entitlements das extensões e instala em `/Applications/3dSlicerRouter.app`. + +Se o serviço de build do Xcode estiver indisponível, use as mesmas fontes e o mesmo SDK pelo backend CLI nativo: + +```sh +./scripts/build.sh --native --test --install +``` + +Os dois backends exigem Xcode. O backend nativo usa `swiftc`, `lipo` e `xctest`; não instala outra toolchain. + +Para usar o terminal, adicione este alias à configuração do shell: + +```sh +alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter ``` -O `build.sh --install`: +## Primeira execução e autorizações + +1. Abra **3dSlicerRouter** em Aplicativos. Escolha **Tornar padrão para .3mf**. O Router permanece como padrão; cada arquivo pode abrir em um fatiador diferente. +2. As thumbnails e o Quick Look usam as duas extensões do app. Se o macOS as desativou, confira **Ajustes do Sistema → Geral → Itens de Início de Sessão e Extensões → Quick Look**. Os nomes podem variar entre versões do macOS. +3. A preparação de previews em background é opcional. Ative-a com `3dSlicerRouter --background on`. Se houver aprovação pendente, o app abre o painel nativo de Itens de Início para você autorizar. + +Abrir um arquivo selecionado e renderizar seu preview não exige Acessibilidade nem Gravação de Tela. O indexador opcional pode provocar pedidos do macOS para pastas protegidas ou volumes removíveis. Registro autorizado e execução correta do worker são estados diferentes. Use `--index-status` e o log local para investigar falhas. + +## Assinatura e downloads -1. gera o `SlicerRouter.xcodeproj` e compila em Release com assinatura ad hoc; -2. copia o app para `/Applications/3dSlicerRouter.app` e registra no LaunchServices; -3. registra as duas extensões do Quick Look (thumbnail e preview); -4. abre o app uma vez em background (`--version`), porque o macOS só ativa as extensões de um app - assinado ad hoc depois da primeira execução. +O build padrão usa **assinatura ad-hoc**. Ele não tem assinatura Developer ID nem notarização. Uma assinatura local válida não comprova que o Gatekeeper aceitará um arquivo baixado em outro Mac. -O `--set-default` torna o router o app padrão de `.3mf`. Pelo Finder dá no mesmo: selecione um `.3mf` -→ **Obter Informações** → **Abrir com: 3dSlicerRouter** → **Alterar Tudo…**. +Pacotes prontos, quando disponíveis, ficam em [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). Confira a versão e a origem antes de executar. Compilar localmente é o caminho suportado enquanto a distribuição notarizada permanece no roadmap. Não desative o Gatekeeper nem a segurança do sistema para instalar este app. -### Conferir +## Conferir a instalação ```sh -/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter --inspect samples/*.3mf -duti -x 3mf # deve mostrar 3dSlicerRouter +3dSlicerRouter --version +3dSlicerRouter --list-slicers +3dSlicerRouter --inspect samples/*.3mf +codesign --verify --deep --strict /Applications/3dSlicerRouter.app ``` -O Finder pode segurar thumbnails antigas no cache por um tempo. `qlmanage -r cache` e reabrir o Finder -(⌥ + clique direito no ícone do Finder no Dock → *Reabrir*) atualizam. +A lista usa instalações válidas. Apps removidos, links quebrados e registros antigos do LaunchServices não viram botões do seletor. O sample sem impressora pergunta qual fatiador instalado deve ser usado. -## Opção B: download pronto +Confira a associação no Finder: selecione um `.3mf` → **Obter Informações** → **Abrir com**. O app deve ser **3dSlicerRouter**. Também é possível configurar pelo CLI com `3dSlicerRouter --set-default`. -1. Baixe `3dSlicerRouter.zip` em [Releases](https://github.com/MoraesGil/3dSlicerRouter/releases). -2. Descompacte e arraste **3dSlicerRouter.app** para **/Applications**. -3. O build é assinado ad hoc, sem notarização. Remova a quarentena do download uma vez: - ```sh - xattr -dr com.apple.quarantine /Applications/3dSlicerRouter.app - ``` -4. Abra o app uma vez pelo `/Applications`. Uma janelinha explica o que ele faz; clique em - **Tornar padrão para .3mf**. + +### Limitação do helper ad-hoc + +A execução automática do indexador ainda é experimental em builds ad-hoc. O macOS pode rejeitar o +lançamento com `EX_CONFIG` (78) ou `Launch Constraint Violation` mesmo quando o registro aparece +habilitado. A validação local observou esse caso; não há correção baseada em desativar a segurança. +Os previews sob demanda continuam disponíveis. Use `--render` ou `--index` em foreground se necessário. ## Atualizar ```sh -cd 3dSlicerRouter && git pull && ./scripts/build.sh --install +git pull --ff-only +./scripts/build.sh --test --install ``` -Os mapeamentos e a memória dos arquivos são mantidos. +O instalador preserva o estado habilitado do indexador opcional e registra as extensões atualizadas. Os mapeamentos e as escolhas por arquivo permanecem nos dados do usuário. Confira qualquer autorização que o macOS pedir após a atualização. ## Desinstalar ```sh -./scripts/uninstall.sh # remove app + dados e devolve o .3mf ao Bambu Studio -./scripts/uninstall.sh com.snapmaker.snapmaker-orca # …ou devolve para outro app -./scripts/uninstall.sh --purge-xattrs ~/Downloads # e também limpa a memória dos arquivos dessa pasta +./scripts/uninstall.sh ``` -O que o script faz, se preferir fazer à mão: - -0. **Desligar o indexador em background** (se ligou): `3dSlicerRouter --background off`. -1. **Remover o app e as extensões do Quick Look.** - ```sh - /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -u /Applications/3dSlicerRouter.app - rm -rf /Applications/3dSlicerRouter.app - ``` -2. **Devolver o `.3mf` a um fatiador, depois de remover o app** (é o app que declara o tipo `org.3mf.3mf`): - `duti -s com.bambulab.bambu-studio .3mf all`, ou no Finder: **Obter Informações** → **Abrir com** - → escolha o fatiador → **Alterar Tudo…**. -3. **Apagar os dados.** - ```sh - rm -rf ~/Library/Application\ Support/3dSlicerRouter # índice SQLite, catálogo e previews - rm -rf ~/Library/Logs/3dSlicerRouter # log do indexador - defaults delete com.moraesdev.3dslicerrouter 2>/dev/null # configurações (endpoint LAYA) - qlmanage -r cache # limpa thumbnails em cache - ``` -4. *(Opcional)* **Remover a memória dos arquivos.** Cada arquivo roteado leva o atributo estendido - `com.moraesdev.slicer-router`. É metadado inofensivo, mas dá para limpar: - ```sh - find ~/Downloads -name '*.3mf' -exec xattr -d com.moraesdev.slicer-router {} \; 2>/dev/null - ``` - -Nada mais é instalado. O único item de segundo plano é o indexador opcional, que fica dentro do app e -some junto com ele; não há extensões de kernel nem de sistema. - -## Problemas comuns - -| Sintoma | Solução | +O script remove o app, encerra seu agente opcional, apaga catálogo, cache e logs locais e associa `.3mf` ao Bambu Studio quando `duti` estiver disponível. Para escolher outro substituto instalado: + +```sh +./scripts/uninstall.sh com.orcaslicer.OrcaSlicer +``` + +Sem `duti`, escolha o substituto no Finder em **Obter Informações → Abrir com → Alterar Tudo…**. Nenhuma configuração de impressora ou fatiador é apagada. + +Os atributos de roteamento dos arquivos são metadados e permanecem por padrão. Para removê-los explicitamente de uma pasta: + +```sh +./scripts/uninstall.sh --purge-xattrs /caminho/da/pasta-de-3mf +``` + +## Solução de problemas + +| Sintoma | Conferência | |---|---| -| Dois cliques ainda abrem um fatiador direto | O arquivo tem *Sempre abrir com* do Finder: `xattr -d com.apple.LaunchServices.OpenWith arq.3mf` | -| Sem thumbnails ou previews | Abra o app uma vez (`open -a 3dSlicerRouter --args --version`) e rode `qlmanage -r cache` | -| `--set-default` aponta para uma pasta de build | As cópias de build têm o mesmo bundle id. Rode `./scripts/build.sh --install` de novo; ele as desregistra | -| "App danificado" / não abre (download) | `xattr -dr com.apple.quarantine /Applications/3dSlicerRouter.app` | -| Um arquivo continua indo para o fatiador errado | `3dSlicerRouter --forget arq.3mf`, ou segure ⌥ ao abrir para escolher de novo | -| Testar thumbnail pelo terminal trava | O `qlmanage -t` não é confiável com extensões modernas. Veja no Finder ou use `QLThumbnailGenerator` | +| Dois cliques ignoram o Router | Pode haver uma escolha **Sempre abrir com** específica do arquivo no Finder. Confira em Obter Informações. | +| Thumbnail antiga | Salve o projeto, confira as extensões Quick Look e solicite o preview novamente. A imagem embutida de fallback pode estar antiga. | +| Abre no fatiador errado | Segure Option ao abrir e escolha novamente, ou use `--forget arq.3mf`. | +| Background habilitado, mas sem renders | Confira ociosidade, energia, execução do job e `~/Library/Logs/3dSlicerRouter/indexer.log`. Registro habilitado não comprova uma execução concluída. | +| Projeto grande mostra somente o preview salvo | Projetos comprimidos acima de 250 MB usam o fallback da primeira chapa embutida. | + +Ao abrir uma issue, informe versão do macOS, versão do app e a saída sanitizada de `--inspect`. Não anexe credenciais, modelos de clientes nem caminhos privados. diff --git a/docs/images/installed-slicers-after.png b/docs/images/installed-slicers-after.png new file mode 100644 index 0000000..2d2b8ec Binary files /dev/null and b/docs/images/installed-slicers-after.png differ diff --git a/docs/images/installed-slicers-before.png b/docs/images/installed-slicers-before.png new file mode 100644 index 0000000..8e96083 Binary files /dev/null and b/docs/images/installed-slicers-before.png differ diff --git a/docs/images/routing.svg b/docs/images/routing.svg index a6b6b15..d2a2241 100644 --- a/docs/images/routing.svg +++ b/docs/images/routing.svg @@ -1,6 +1,6 @@ 3dSlicerRouter picks the slicer from the printer inside the .3mf -A Bambu Lab A1 project opens in Bambu Studio; a Snapmaker U1 project opens in Snapmaker Orca. The router reads printer_model from each file. +A Bambu Lab A1 project opens in Bambu Studio; a Snapmaker U1 project opens in OrcaSlicer. The router reads printer_model from each file. diff --git a/project.yml b/project.yml index 0822b53..372ad57 100644 --- a/project.yml +++ b/project.yml @@ -10,8 +10,8 @@ settings: CODE_SIGN_STYLE: Manual DEVELOPMENT_TEAM: "" ENABLE_HARDENED_RUNTIME: NO - MARKETING_VERSION: "1.3.0" - CURRENT_PROJECT_VERSION: "4" + MARKETING_VERSION: "1.4.0" + CURRENT_PROJECT_VERSION: "14" targets: SlicerRouter: type: application @@ -19,7 +19,7 @@ targets: sources: - Sources/Core - Sources/App - - path: Resources/LaunchAgents/com.moraesdev.3dslicerrouter.indexer.plist + - path: Resources/LaunchAgents/com.moraesdev.3dslicerrouter.previews.v2.plist buildPhase: copyFiles: destination: wrapper @@ -57,12 +57,31 @@ targets: PRODUCT_MODULE_NAME: SlicerRouter PRODUCT_BUNDLE_IDENTIFIER: com.moraesdev.3dslicerrouter dependencies: + - target: SlicerRouterIndexer + embed: true + codeSign: true + copy: + destination: wrapper + subpath: Contents/Helpers - target: SlicerRouterThumbnail embed: true codeSign: true - target: SlicerRouterPreview embed: true codeSign: true + SlicerRouterIndexer: + type: tool + platform: macOS + sources: + - Sources/Core + - Sources/App/Store.swift + - Sources/App/Indexer.swift + - Sources/Indexer + settings: + base: + PRODUCT_NAME: 3dSlicerIndexer + PRODUCT_MODULE_NAME: SlicerRouterIndexer + SKIP_INSTALL: YES SlicerRouterThumbnail: type: app-extension platform: macOS @@ -92,6 +111,7 @@ targets: base: PRODUCT_BUNDLE_IDENTIFIER: com.moraesdev.3dslicerrouter.thumbnail PRODUCT_MODULE_NAME: SlicerRouterThumbnail + CODE_SIGN_ENTITLEMENTS: Sources/Thumbnail/Thumbnail.entitlements SlicerRouterPreview: type: app-extension platform: macOS @@ -122,11 +142,14 @@ targets: base: PRODUCT_BUNDLE_IDENTIFIER: com.moraesdev.3dslicerrouter.preview PRODUCT_MODULE_NAME: SlicerRouterPreview + CODE_SIGN_ENTITLEMENTS: Sources/Preview/Preview.entitlements SlicerRouterTests: type: bundle.unit-test platform: macOS sources: - Sources/Core + - Sources/App/Store.swift + - Sources/App/Indexer.swift - Tests settings: base: diff --git a/samples/README.md b/samples/README.md index c79b62d..2c9af9f 100644 --- a/samples/README.md +++ b/samples/README.md @@ -9,10 +9,10 @@ so the slicers import them as plain models. | `bambu-a1-keychain-tray.3mf` | Bambu Lab A1 | Bambu Studio | 6 two-colour tags on one plate | | `bambu-a1mini-calibration.3mf` | Bambu Lab A1 mini | Bambu Studio | smaller 180 mm bed | | `bambu-h2d-four-plates.3mf` | Bambu Lab H2D | Bambu Studio | 4 plates → panoramic preview | -| `snapmaker-u1-four-colors.3mf` | Snapmaker U1 | Snapmaker Orca | 4 toolheads, 4 colours | -| `snapmaker-u1-painted-faces.3mf` | Snapmaker U1 | Snapmaker Orca | faces painted with the colour brush (`paint_color`) | -| `unknown-printer-prusa-mk4s.3mf` | Original Prusa MK4S | asks once | picker + *Always use for this printer* | -| `no-printer-declared.3mf` | none | classifier or asks | plain 3MF with no slicer metadata | +| `snapmaker-u1-four-colors.3mf` | Snapmaker U1 | OrcaSlicer | 4 toolheads, 4 colours | +| `snapmaker-u1-painted-faces.3mf` | Snapmaker U1 | OrcaSlicer | faces painted with the colour brush (`paint_color`) | +| `unknown-printer-prusa-mk4s.3mf` | Original Prusa MK4S | OrcaSlicer | Prusa default (legacy sample filename) | +| `no-printer-declared.3mf` | none | Ask among installed slicers | plain 3MF with no slicer metadata | ```sh # what would happen, without opening anything diff --git a/scripts/build.sh b/scripts/build.sh index 352fda9..3d26e61 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -5,16 +5,67 @@ cd "${0:A:h}/.." LSREGISTER=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister PRODUCTS="build/DerivedData/Build/Products" - -xcodegen generate --quiet -xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -configuration Release \ - -derivedDataPath build/DerivedData build -quiet APP="$PRODUCTS/Release/3dSlicerRouter.app" +NATIVE=false +INSTALL=false +TEST=false +for arg in "$@"; do + case "$arg" in + --native) NATIVE=true ;; + --install) INSTALL=true ;; + --test) TEST=true ;; + *) echo "usage: $0 [--native] [--test] [--install]" >&2; exit 2 ;; + esac +done + +if $NATIVE; then + ./scripts/native.sh build +else + xcodegen generate --quiet + xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -configuration Release \ + -derivedDataPath build/DerivedData build -quiet +fi + +# Incremental builds must not retain this app's obsolete service definitions. +for legacy in com.moraesdev.3dslicerrouter.indexer.plist com.moraesdev.3dslicerrouter.previews.plist; do + rm -f "$APP/Contents/Library/LaunchAgents/$legacy" +done + +# Sign inside-out. Never use --deep to re-sign the host: that can discard the +# extensions' sandbox entitlements while still producing a valid outer signature. +codesign --force --sign - --identifier com.moraesdev.3dslicerrouter.indexer "$APP/Contents/Helpers/3dSlicerIndexer" +CHECK=$(mktemp "$PRODUCTS/Release/entitlements.XXXXXX") +trap 'rm -f "$CHECK"' EXIT +for name in Thumbnail Preview; do + EXTENSION="$APP/Contents/PlugIns/SlicerRouter${name}.appex" + codesign --force --sign - --entitlements "Sources/$name/$name.entitlements" --generate-entitlement-der "$EXTENSION" + for arch in arm64 x86_64; do + codesign -d --arch "$arch" --entitlements :- "$EXTENSION" > "$CHECK" 2>/dev/null + [[ "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.app-sandbox' "$CHECK")" == true ]] + [[ "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.security.files.user-selected.read-only' "$CHECK")" == true ]] + done + codesign --verify --strict "$EXTENSION" +done +codesign --force --sign - "$APP" codesign --verify --deep --strict "$APP" echo "built: $APP" -if [[ "${1:-}" == "--install" ]]; then +if $TEST; then + if $NATIVE; then + ./scripts/native.sh test + else + xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -derivedDataPath build/DerivedData test + fi +fi + +if $INSTALL; then DEST="/Applications/3dSlicerRouter.app" + BACKGROUND_WAS_ENABLED=false + # Unregister the previous revision before its executable/signature is replaced. + if [[ -x "$DEST/Contents/MacOS/3dSlicerRouter" ]]; then + [[ "$("$DEST/Contents/MacOS/3dSlicerRouter" --background status)" == "background: ativo" ]] && BACKGROUND_WAS_ENABLED=true + "$DEST/Contents/MacOS/3dSlicerRouter" --background off + fi rm -rf "$DEST" cp -R "$APP" "$DEST" # Build copies share the bundle id; keep LaunchServices pointing at /Applications only. @@ -22,8 +73,24 @@ if [[ "${1:-}" == "--install" ]]; then "$LSREGISTER" -f "$DEST" pluginkit -a "$DEST/Contents/PlugIns/SlicerRouterThumbnail.appex" pluginkit -a "$DEST/Contents/PlugIns/SlicerRouterPreview.appex" - # Ad hoc signed extensions only activate after the host app has been launched once. - open -g -a "$DEST" --args --version + # Activate the signed host through LaunchServices without opening a UI or taking focus. + xcrun swift - "$DEST" <<'SWIFT' +import AppKit +let configuration = NSWorkspace.OpenConfiguration() +configuration.activates = false +configuration.hides = true +configuration.arguments = ["--version"] +let url = URL(fileURLWithPath: CommandLine.arguments.last!) +NSWorkspace.shared.openApplication(at: url, configuration: configuration) { _, error in + if let error { + fputs("Could not activate the installed host: \(error.localizedDescription)\n", stderr) + exit(1) + } + exit(0) +} +RunLoop.main.run() +SWIFT + if $BACKGROUND_WAS_ENABLED; then "$DEST/Contents/MacOS/3dSlicerRouter" --background on; fi qlmanage -r cache >/dev/null 2>&1 || true echo "installed: $DEST" echo "make it the default for .3mf: $DEST/Contents/MacOS/3dSlicerRouter --set-default" diff --git a/scripts/make_routing_svg.py b/scripts/make_routing_svg.py index 91bf7a3..8439e23 100644 --- a/scripts/make_routing_svg.py +++ b/scripts/make_routing_svg.py @@ -6,7 +6,7 @@ Everything is embedded (no JS, no external requests) so GitHub can show it through . Needs the installed router (/Applications/3dSlicerRouter.app) for the previews, and Bambu Studio -and Snapmaker Orca in /Applications for their app icons. Uses sips (macOS) for conversions. +and official OrcaSlicer in /Applications for their app icons. Uses sips (macOS) for conversions. python3 scripts/make_routing_svg.py """ @@ -21,11 +21,11 @@ SCENES = [ {"sample": "bambu-a1-keychain-tray.3mf", "printer": "Bambu Lab A1", "app": "Bambu Studio", "target": "bambu"}, - {"sample": "snapmaker-u1-four-colors.3mf", "printer": "Snapmaker U1", "app": "Snapmaker Orca", "target": "orca"}, + {"sample": "snapmaker-u1-four-colors.3mf", "printer": "Snapmaker U1", "app": "OrcaSlicer", "target": "orca"}, ] APPS = { "bambu": ("Bambu Studio", "/Applications/BambuStudio.app/Contents/Resources/Icon.icns", "Bambu Lab printers"), - "orca": ("Snapmaker Orca", "/Applications/Snapmaker Orca.app/Contents/Resources/Icon.icns", "Snapmaker printers"), + "orca": ("OrcaSlicer", "/Applications/OrcaSlicer.app/Contents/Resources/Icon.icns", "Default for non-Bambu printers"), } @@ -89,7 +89,7 @@ def svg(thumbs, icons): return f""" 3dSlicerRouter picks the slicer from the printer inside the .3mf -A Bambu Lab A1 project opens in Bambu Studio; a Snapmaker U1 project opens in Snapmaker Orca. The router reads printer_model from each file. +A Bambu Lab A1 project opens in Bambu Studio; a Snapmaker U1 project opens in OrcaSlicer. The router reads printer_model from each file.