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.
[](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml)

@@ -13,7 +13,7 @@ Double-click a 3MF on your Mac. 3dSlicerRouter reads the printer saved inside th

[](LICENSE)
-
+
[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 Lab A1`, `A1 mini`, `P1S`, `X1C`, `H2D`, … | **Bambu Studio** |
-| | `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 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.
[](https://github.com/MoraesGil/3dSlicerRouter/actions/workflows/ci.yml)

@@ -13,7 +13,7 @@ Dê dois cliques num 3MF no Mac. O 3dSlicerRouter lê a impressora salva dentro

[](LICENSE)
-
+
[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 Lab A1`, `A1 mini`, `P1S`, `X1C`, `H2D`, … | **Bambu Studio** |
-| | `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 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.v2BundleProgram
- Contents/MacOS/3dSlicerRouter
+ Contents/Helpers/3dSlicerIndexerProgramArguments
- 3dSlicerRouter
- --index-agent
+ 3dSlicerIndexerRunAtLoad
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(#"