diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bdd3784..33dc7ea 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,7 +45,7 @@ jobs: 1. Open the DMG and drag **3dSlicerRouter** to **Applications**. 2. Eject the disk image and open the app from **Applications**. - 3. Choose **Make default for .3mf**. Keep at least one slicer installed. + 3. Choose **Use for .3mf and .gcode**. Keep at least one slicer installed. **Signing:** this release is ad-hoc signed, not Developer ID signed or notarized. macOS can block the first launch. If you trust the download, use Apple's per-app [Open Anyway instructions](https://support.apple.com/102445). Managed Macs may prevent approval. Do not disable Gatekeeper or remove quarantine. Background indexing remains experimental; routing and on-demand previews work independently. @@ -55,7 +55,7 @@ jobs: 1. Abra o DMG e arraste **3dSlicerRouter** para **Applications**. 2. Ejete a imagem e abra o app em **Aplicativos**. - 3. Escolha **Tornar padrão para .3mf**. Mantenha um fatiador instalado. + 3. Escolha **Usar para .3mf e .gcode**. Mantenha um fatiador instalado. **Assinatura:** esta versão usa assinatura ad-hoc, sem Developer ID nem notarização. O macOS pode bloquear a primeira abertura. Se você confia no download, siga as [instruções da Apple para Abrir Mesmo Assim](https://support.apple.com/102445). Macs gerenciados podem impedir essa autorização. Não desative o Gatekeeper nem remova a quarentena. A indexação em background continua experimental; o roteamento e os previews sob demanda são independentes. diff --git a/README.md b/README.md index 2738af8..7a2af02 100644 --- a/README.md +++ b/README.md @@ -9,33 +9,46 @@ **Open your projects in the right slicer, automatically.**
**See your build plate before you even open the file.** -A native macOS app for `.3mf` routing, Finder thumbnails and Quick Look previews. +A native macOS app for `.3mf` and `.gcode` routing, Finder icons, thumbnails and Quick Look previews. Everything runs locally, without an account or a network service. + + +
+

↓ Download for macOS (.dmg)

+

Apple silicon + Intel · macOS 14+
+Open the DMG and drag to Applications.
+No Xcode, Homebrew or Terminal required.

+

All releases · Installation guide

+
+ [![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) ![Swift](https://img.shields.io/badge/Swift-native-F05138?logo=swift&logoColor=white) ![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) -**[Download for macOS (.dmg)](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)** · [All releases](https://github.com/MoraesGil/3dSlicerRouter/releases) - [Install](docs/INSTALL.md) · [Routing demo](#open-in-the-right-slicer-automatically) · [Preview demo](#see-your-build-plate-before-opening-the-file) · [Português](README.pt-BR.md) ## Open in the right slicer, automatically -Keep 3dSlicerRouter as the default app for `.3mf`. Double-click a project: it reads the saved printer -and opens **Bambu Studio**, **OrcaSlicer**, **Snapmaker Orca** or your chosen slicer. -No printer metadata? It asks you to choose from the slicers installed on your Mac. +Keep 3dSlicerRouter as the default app for `.3mf` and `.gcode`. Double-click a file: it reads the saved +printer and opens **Bambu Studio**, **OrcaSlicer**, **Snapmaker Orca** or your chosen slicer. +For G-code, it also identifies the slicer that generated the file. A manual choice for the file and an +explicit printer mapping take priority over that generator. With no applicable rule, it asks you to +choose from the slicers installed on your Mac. Routing demo: a Bambu Lab A1 project opens in Bambu Studio and a Snapmaker U1 project opens in OrcaSlicer ## See your build plate before opening the file -Find the right project by its geometry and colours, directly in **Finder**. Thumbnails show the -first build plate. Select a file and press **Space** for **Quick Look**: orbit and zoom a single-plate +Router logo variants with colours and letter markers for each slicer + +**Finder** file icons use the Router logo with the chosen slicer's colour and marker. +macOS also uses this custom icon in Finder's icon view. Model thumbnails remain available to +Quick Look clients. Select a file and press **Space** for **Quick Look**: orbit and zoom a single-plate project in 3D, or see all plates together in a multi-plate project. You do not need to launch a slicer. | One plate, painted colours | Multiple plates, one overview | @@ -49,7 +62,7 @@ project in 3D, or see all plates together in a multi-plate project. You do not n extrusion path in each tool's filament colour. Quick Look opens the toolpath in 3D. - **Local rendering:** SceneKit and Metal generate the previews on your Mac. No AI model, API key or account is required. -Finder uses a current indexed thumbnail when available, or renders the current first-plate geometry +Thumbnail requests use a current indexed image when available, or render the current first-plate geometry on demand. If rendering fails or the compressed project exceeds 250 MB, it falls back to the slicer's saved first-plate image, which can be out of date. [Background indexing](#background-previews-optional) is optional. @@ -60,8 +73,9 @@ 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 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. +3dSlicerRouter becomes the default app for `.3mf` and `.gcode`. It reads `printer_model` and hands the +file to the configured slicer. For G-code, it also uses the identified generator, after manual choices +and explicit mappings. With no applicable rule, it asks you to choose an installed slicer. ## Any printer, any slicer @@ -131,14 +145,17 @@ Big projects take seconds to render. Turn on the indexer and they are ready befo ## How it decides +The table below describes 3MF routing. G-code uses: confirmed per-file choice → explicit printer mapping → declared generator → printer default or chooser. A file copied from another Mac cannot authorize a new application path. + | Situation | Result | |---|---| -| First open | Explicit printer mapping; otherwise Bambu Studio for Bambu Lab, official OrcaSlicer for other printers | +| First 3MF 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 | Remembered manual choice; otherwise asks among installed slicers | +| G-code with an identified generator | Manual file choice and explicit printer mapping take priority; otherwise uses the generator | +| No printer and no recognized generator 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, restart and reload, or open another copy | @@ -164,7 +181,7 @@ Requires macOS 14 or newer and at least one slicer. 1. **[Download 3dSlicerRouter.dmg](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)**. One app supports Apple silicon and Intel. 2. Open the DMG and drag **3dSlicerRouter** to **Applications**. Eject the disk image. -3. Open the app from **Applications** and choose **Make default for .3mf**. +3. Open the app from **Applications** and choose **Use for .3mf and .gcode**. You do not need Xcode, Homebrew or Terminal. The release includes an alternative ZIP and SHA-256 checksums. @@ -193,7 +210,7 @@ runs the full test suite using `swiftc` and `xctest`. It still requires Xcode's ## Try it -Seven small synthetic projects in [`samples/`](samples/) cover every path: +Seven small synthetic 3MF projects in [`samples/`](samples/) demonstrate printer routing and previews: ```sh open samples/bambu-a1-keychain-tray.3mf # Bambu Studio @@ -209,7 +226,7 @@ open samples/no-printer-declared.3mf # choose an installed slicer | Command | What it does | |---|---| -| `--inspect file.3mf…` | Printer, thumbnail, remembered choice and decision; does not open a slicer or change the 3MF | +| `--inspect file.3mf\|file.gcode…` | Printer, thumbnail, remembered choice and decision; does not open a slicer or change file contents | | `--map "" /Applications/App.app` | Send that printer to any slicer | | `--mappings` | List brand defaults and your mappings | | `--list-slicers` | List installed slicers and their paths | @@ -218,19 +235,20 @@ open samples/no-printer-declared.3mf # choose an installed slicer | `--index [--limit N]` | Index and render now, ignoring the idle rule | | `--index-status` | Indexer state, catalog totals, log path | | `--catalog [text]` | Every 3MF and G-code found, with printer and preview state | -| `--forget file.3mf…` | Erase the router's memory for these files | -| `--set-default` | Make the router the default app for `.3mf` | +| `--forget file.3mf\|file.gcode…` | Erase the router's memory for these files | +| `--set-default` | Make the router the default app for `.3mf` and `.gcode` | ## Files with no printer -Files without printer metadata ask which slicer to use. The picker checks `/Applications`, +Files with neither printer metadata nor a recognized G-code generator 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. 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. +3dSlicerRouter remains the default application for `.3mf` and `.gcode` files.

Native picker for a synthetic 3MF, showing OrcaSlicer, Bambu Studio and Snapmaker Orca installed on the test Mac @@ -251,8 +269,18 @@ 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 it touch my files?** It stores routing and Finder icon metadata on the file. The 3MF or G-code +contents stay byte-for-byte the same. + +**How does it choose a slicer for G-code?** The Router identifies the generator in the file comments. +A saved manual choice for the file or an explicit printer mapping takes priority. +Hold **⌥ (Option)** when opening to choose another slicer. + +**Do all file icons change immediately after installation?** No. Small icons use the Router logo with +the slicer's colour and marker. They update when a file is opened or indexed, and when Finder requests +a thumbnail. Files never opened or indexed can keep their previous icon. Finder's icon view also +shows the custom logo; press **Space** to inspect the model in Quick Look. If the file is not writable or its filesystem does not support extended +attributes, opening still works; Finder uses the extension icon or thumbnail fallback. **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 diff --git a/README.pt-BR.md b/README.pt-BR.md index 6097d93..1c68cf8 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -9,8 +9,18 @@ **Automatize a abertura no slicer correto.**
**Veja a mesa antes mesmo de abrir o arquivo.** -Um app nativo do macOS para abrir `.3mf` no slicer certo e mostrar thumbnails no Finder e previews -no Quick Look. Tudo funciona localmente, sem conta nem serviço de rede. +Um app nativo do macOS para abrir `.3mf` e `.gcode` no slicer certo, com ícones no Finder, +thumbnails e previews no Quick Look. Tudo funciona localmente, sem conta nem serviço de rede. + + + +
+

↓ Baixar para macOS (.dmg)

+

Apple silicon + Intel · macOS 14+
+Abra o DMG e arraste para Applications.
+Sem Xcode, Homebrew ou Terminal.

+

Todas as versões · Guia de instalação

+
[![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) @@ -18,24 +28,27 @@ no Quick Look. Tudo funciona localmente, sem conta nem serviço de rede. ![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) -**[Baixar para macOS (.dmg)](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)** · [Todas as versões](https://github.com/MoraesGil/3dSlicerRouter/releases) - [Instalar](docs/INSTALL.pt-BR.md) · [Demo do router](#automatize-a-abertura-no-slicer-correto) · [Demo dos previews](#veja-a-mesa-antes-mesmo-de-abrir-o-arquivo) · [English](README.md) ## Automatize a abertura no slicer correto -Mantenha o 3dSlicerRouter como app padrão de `.3mf`. Dê dois cliques em um projeto: ele lê a impressora -salva e abre o **Bambu Studio**, o **OrcaSlicer**, o **Snapmaker Orca** ou o slicer escolhido por você. -O arquivo não tem impressora definida? Ele pergunta qual dos slicers instalados no Mac você quer usar. +Mantenha o 3dSlicerRouter como app padrão de `.3mf` e `.gcode`. Dê dois cliques em um arquivo: +ele lê a impressora salva e abre o **Bambu Studio**, o **OrcaSlicer**, o **Snapmaker Orca** ou o slicer escolhido. +No G-code, ele também identifica o slicer que gerou o arquivo. A escolha manual por arquivo e o +mapeamento explícito da impressora têm prioridade sobre esse gerador. Sem uma regra aplicável, +ele pergunta qual slicer instalado usar. Demo do router: um projeto Bambu Lab A1 abre no Bambu Studio e um projeto Snapmaker U1 abre no OrcaSlicer ## Veja a mesa antes mesmo de abrir o arquivo -Encontre o projeto pela geometria e pelas cores, direto no **Finder**. As thumbnails mostram a primeira -mesa. Selecione um arquivo e pressione **Espaço** para abrir o **Quick Look**: gire e amplie um projeto +Variantes da logo do Router com cores e marcadores de cada slicer + +Os ícones de arquivo no **Finder** usam a logo do Router, com a cor e o marcador do slicer escolhido. +O macOS também usa esse ícone personalizado na visualização por ícones do Finder. As thumbnails +do modelo continuam disponíveis para clientes do Quick Look. Selecione um arquivo e pressione **Espaço** para abrir o **Quick Look**: gire e amplie um projeto de uma mesa em 3D ou veja todas as mesas juntas em um projeto com várias mesas. Não é preciso abrir o slicer. | Uma mesa, cores pintadas | Várias mesas, uma visão geral | @@ -49,7 +62,7 @@ de uma mesa em 3D ou veja todas as mesas juntas em um projeto com várias mesas. caminho de extrusão na cor do filamento de cada ferramenta. O Quick Look abre esse caminho em 3D. - **Render local:** SceneKit e Metal geram os previews no Mac. Não é preciso modelo de IA, API key ou conta. -O Finder usa a thumbnail indexada da revisão atual quando ela existe. Sem ela, renderiza a geometria +As solicitações de thumbnail usam a imagem indexada da revisão atual quando ela existe. Sem ela, renderizam a geometria atual da primeira mesa sob demanda. Se o render falhar ou o projeto comprimido exceder 250 MB, usa a imagem salva pelo slicer, que pode estar desatualizada. A [indexação em background](#previews-em-background-opcional) é opcional. @@ -60,8 +73,9 @@ 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 lê o `printer_model` do projeto e entrega o arquivo ao fatiador configurado. -Sem essa informação, pergunta qual fatiador instalado você quer usar. +O 3dSlicerRouter vira o app padrão de `.3mf` e `.gcode`. Ele lê o `printer_model` e entrega o arquivo +ao slicer configurado. No G-code, também usa o gerador identificado, depois das escolhas manuais +e dos mapeamentos explícitos. Sem uma regra aplicável, pergunta qual slicer instalado usar. ## Qualquer impressora, qualquer fatiador @@ -130,14 +144,17 @@ abrir o Finder: ## Como decide +A tabela abaixo descreve o roteamento de 3MF. No G-code: escolha confirmada por arquivo → mapeamento explícito → gerador declarado → padrão da impressora ou seletor. Um arquivo copiado de outro Mac não autoriza um novo caminho de aplicativo. + | Situação | Resultado | |---|---| -| Primeira abertura | Regra explícita da impressora; sem regra, Bambu Studio para Bambu Lab e OrcaSlicer oficial para as demais | +| Primeira abertura de 3MF | 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 | Escolha manual salva; sem escolha manual, pergunta entre os fatiadores instalados | +| G-code com gerador identificado | Escolha manual por arquivo e mapeamento explícito têm prioridade; sem eles, usa o gerador | +| Arquivo sem impressora e sem gerador reconhecido | 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, reiniciar e recarregar ou abrir outra cópia | @@ -161,7 +178,7 @@ Abrir o arquivo diretamente em outro slicer não atualiza a escolha do router. 1. **[Baixe 3dSlicerRouter.dmg](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)**. O mesmo app atende Apple silicon e Intel, no macOS 14 ou mais novo. 2. Abra o DMG e arraste **3dSlicerRouter** para **Applications**. Ejete a imagem de disco. -3. Abra o app em **Aplicativos** e escolha **Tornar padrão para .3mf**. Mantenha um fatiador instalado. +3. Abra o app em **Aplicativos** e escolha **Usar para .3mf e .gcode**. Mantenha um fatiador instalado. Você não precisa de Xcode, Homebrew nem Terminal. A Release inclui um ZIP alternativo e hashes SHA-256. @@ -192,7 +209,7 @@ roda a suíte completa com `swiftc` e `xctest`. O SDK e as ferramentas de linha ## Teste -Sete projetos sintéticos pequenos em [`samples/`](samples/) cobrem todos os caminhos: +Sete projetos 3MF sintéticos pequenos em [`samples/`](samples/) demonstram o roteamento e os previews: ```sh open samples/bambu-a1-keychain-tray.3mf # Bambu Studio @@ -208,7 +225,7 @@ open samples/no-printer-declared.3mf # escolher um fatiador instalado | Comando | O que faz | |---|---| -| `--inspect arq.3mf…` | Impressora, thumbnail, escolha salva e decisão; não abre fatiador nem altera o 3MF | +| `--inspect arq.3mf\|arq.gcode…` | Impressora, thumbnail, escolha salva e decisão; não abre slicer nem altera o conteúdo | | `--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 | @@ -217,18 +234,18 @@ open samples/no-printer-declared.3mf # escolher um fatiador instalado | `--index [--limit N]` | Indexa e renderiza agora, ignorando a regra de ociosidade | | `--index-status` | Estado do indexador, totais do catálogo e caminho do log | | `--catalog [texto]` | Todos os 3MF e G-code achados, com impressora e estado do preview | -| `--forget arq.3mf…` | Apaga a memória do router nesses arquivos | -| `--set-default` | Torna o router o app padrão de `.3mf` | +| `--forget arq.3mf\|arq.gcode…` | Apaga a memória do router nesses arquivos | +| `--set-default` | Torna o router o app padrão de `.3mf` e `.gcode` | ## Arquivos sem impressora -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 +Arquivos sem impressora declarada e sem gerador de G-code reconhecido perguntam qual slicer 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. 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`. +que usavam OrcaSlicer por falta de impressora voltam a perguntar. As regras são executadas localmente. O 3dSlicerRouter continua como app padrão de `.3mf` e `.gcode`.

Seletor nativo de um 3MF sintético, com OrcaSlicer, Bambu Studio e Snapmaker Orca instalados no Mac de teste @@ -249,8 +266,19 @@ 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. +**Ele mexe nos meus arquivos?** Ele grava metadados de roteamento e do ícone do Finder no arquivo. +O conteúdo do 3MF ou G-code continua idêntico, byte a byte. + +**Como escolhe o slicer para G-code?** O Router identifica o gerador nos comentários do arquivo. +Uma escolha manual salva por arquivo ou um mapeamento explícito da impressora tem prioridade. +Segure **⌥ (Option)** ao abrir para escolher outro slicer. + +**Todos os ícones mudam logo após instalar?** Não. Os ícones pequenos usam a logo do Router com a cor +e o marcador do slicer. Eles são atualizados ao abrir ou indexar o arquivo e quando o Finder solicita +uma thumbnail. Arquivos nunca abertos ou indexados podem manter o ícone anterior. A visualização por +ícones do Finder também mostra a logo personalizada; pressione **Espaço** para conferir o modelo no Quick Look. Se o arquivo não permitir escrita ou o sistema de arquivos +não aceitar atributos estendidos, a abertura continua funcionando; o Finder usa o ícone da extensão +ou a thumbnail de fallback. **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 diff --git a/Sources/App/Indexer.swift b/Sources/App/Indexer.swift index 2d8f527..5a404fc 100644 --- a/Sources/App/Indexer.swift +++ b/Sources/App/Indexer.swift @@ -89,7 +89,11 @@ enum Indexer { summary.stoppedEarly = true break } - if store.isCatalogued(url.path, size: size, modified: modified) { summary.skipped += 1; continue } + if store.isCatalogued(url.path, size: size, modified: modified) { + refreshIcon(for: url, store: store) + summary.skipped += 1 + continue + } autoreleasepool { let entry = index(url, size: size, modified: modified) store.upsertCatalog(entry) @@ -106,6 +110,12 @@ enum Indexer { var printer: String?, plates = 1, embedded = false, preview: String?, rendered = false, error: String? } + @discardableResult + static func refreshIcon(for url: URL, store: Store) -> Bool { + guard let document = try? RoutableDocument.read(url: url) else { return false } + return RouterFileIcon.apply(to: url, app: document.expectedApp(record: store.record(for: url), mappings: store.mappings())) + } + 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" @@ -115,11 +125,17 @@ enum Indexer { let render: () throws -> CGImage if gcode { let meta = try GCode.metadata(url: url) + if let document = try? RoutableDocument.read(url: url) { + let preferences = RoutingPreferences.read(for: url) + RouterFileIcon.apply(to: url, app: document.expectedApp(record: preferences.record, mappings: preferences.mappings)) + } entry.printer = meta.info.printerModel entry.embedded = meta.thumbnail != nil render = { try PreviewRenderer.renderGCode(url: url, info: meta.info, size: CGSize(width: 1024, height: 1024)) } } else { let info = try readInfo(url) + let preferences = RoutingPreferences.read(for: url) + RouterFileIcon.apply(to: url, app: Router.expectedApp(info: info, record: preferences.record, mappings: preferences.mappings)) entry.printer = info.printerModel entry.plates = info.plateCount entry.embedded = info.embeddedThumbnail != nil diff --git a/Sources/App/Info.plist b/Sources/App/Info.plist index 779a75d..15e5e37 100644 --- a/Sources/App/Info.plist +++ b/Sources/App/Info.plist @@ -19,6 +19,22 @@ org.3mf.3mf + CFBundleTypeIconFile + AppIcon + + + CFBundleTypeName + G-code + CFBundleTypeRole + Viewer + CFBundleTypeIconFile + AppIcon + LSHandlerRank + Owner + LSItemContentTypes + + com.moraesdev.gcode + CFBundleExecutable diff --git a/Sources/App/RouterApp.swift b/Sources/App/RouterApp.swift index 91ce7e1..05bb4db 100644 --- a/Sources/App/RouterApp.swift +++ b/Sources/App/RouterApp.swift @@ -28,10 +28,12 @@ final class RouterApp: NSObject, NSApplicationDelegate { handleAlreadyOpen(url, project, optionHeld: optionHeld) return } - let info = (try? ThreeMF.info(url: url)) ?? ThreeMFInfo() + let document = (try? RoutableDocument.read(url: url)) ?? RoutableDocument(info: ThreeMFInfo(), generator: nil, + originatingSlicer: nil, isGCode: url.pathExtension.lowercased() == "gcode") + let info = document.info let record = store.record(for: url) let mappings = store.mappings() - var decision = Router.decide(info: info, record: record, mappings: mappings, optionHeld: optionHeld) + var decision = document.decide(record: record, mappings: mappings, optionHeld: optionHeld) if case let .open(app, _) = decision, SlicerApp.installedURL(for: app) == nil { decision = .ask(.appUnavailable(app.name), suggested: nil) @@ -40,11 +42,12 @@ final class RouterApp: NSObject, NSApplicationDelegate { let app: SlicerApp, reason: String, override: Bool switch decision { case let .open(a, r): - app = a; reason = r; override = record?.override ?? false + app = SlicerApp.installedApplication(for: a) ?? a; reason = r; override = record?.override ?? false case let .ask(why, suggested): guard let choice = Prompt.choose(url: url, info: info, reason: why, suggested: suggested) else { return } app = choice.app; reason = "escolha do dono" - override = info.printerModel.flatMap(mappings.app(for:)) != choice.app + // A deliberate per-file choice survives a later change of G-code generator. + override = true if choice.remember, let model = info.printerModel { store.remember(printer: model, app: choice.app) } } @@ -132,14 +135,21 @@ final class RouterApp: NSObject, NSApplicationDelegate { let alert = NSAlert() alert.messageText = "3dSlicerRouter" let current = NSWorkspace.shared.urlForApplication(toOpen: Self.threeMFType).map { $0.lastPathComponent } ?? L10n.none - alert.informativeText = L10n.about(current: current) + let gcode = NSWorkspace.shared.urlForApplication(toOpen: UTType(filenameExtension: "gcode") ?? FileAssociations.gcode) + .map { $0.lastPathComponent } ?? L10n.none + alert.informativeText = L10n.about(current: current, gcode: gcode) alert.addButton(withTitle: L10n.makeDefault) + alert.addButton(withTitle: L10n.refreshIcons) alert.addButton(withTitle: L10n.close) - if alert.runModal() == .alertFirstButtonReturn { + let response = alert.runModal() + if response == .alertFirstButtonReturn { Self.makeDefault { error in if let error { Prompt.error(L10n.defaultFailed, detail: error.localizedDescription) } NSApp.terminate(nil) } + } else if response == .alertSecondButtonReturn { + refreshFileIcons() + NSApp.terminate(nil) } else { NSApp.terminate(nil) } @@ -148,8 +158,25 @@ final class RouterApp: NSObject, NSApplicationDelegate { static let threeMFType = UTType(filenameExtension: "3mf") ?? UTType(importedAs: "org.3mf.3mf") static func makeDefault(_ done: @escaping (Error?) -> Void) { - NSWorkspace.shared.setDefaultApplication(at: Bundle.main.bundleURL, toOpen: threeMFType) { error in - DispatchQueue.main.async { done(error) } + FileAssociations.makeDefault(at: Bundle.main.bundleURL, completion: done) + } + + private func refreshFileIcons() { + let picker = NSOpenPanel() + picker.title = L10n.refreshIcons + picker.allowedContentTypes = FileAssociations.types + picker.allowsMultipleSelection = true + picker.canChooseDirectories = false + guard picker.runModal() == .OK else { return } + var updated = 0 + for url in picker.urls { + guard let document = try? RoutableDocument.read(url: url) else { continue } + let app = document.expectedApp(record: store.record(for: url), mappings: store.mappings()) + if RouterFileIcon.apply(to: url, app: app) { updated += 1 } } + let result = NSAlert() + result.messageText = L10n.refreshedIcons(updated, total: picker.urls.count) + result.informativeText = L10n.iconMetadataOnly + result.runModal() } } diff --git a/Sources/App/Store.swift b/Sources/App/Store.swift index 4bfd64f..cf82124 100644 --- a/Sources/App/Store.swift +++ b/Sources/App/Store.swift @@ -14,6 +14,7 @@ final class Store { 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 } + sqlite3_busy_timeout(db, 1000) exec(""" CREATE TABLE IF NOT EXISTS files(uuid TEXT PRIMARY KEY, path TEXT, record TEXT, updated_at REAL); CREATE INDEX IF NOT EXISTS files_path ON files(path); @@ -29,24 +30,44 @@ final class Store { // MARK: arquivo func record(for url: URL) -> FileRecord? { - if let r = FileRecord.read(from: url) { return r } + let portable = FileRecord.read(from: url) // Sem xattr (cópia por zip/upload, por exemplo): tenta o índice pelo caminho. - return query("SELECT record FROM files WHERE path = ? ORDER BY updated_at DESC LIMIT 1", [url.path]) + let local = query("SELECT record FROM files WHERE path = ? OR (uuid = ? AND uuid <> '') ORDER BY (uuid = ? AND uuid <> '') DESC, updated_at DESC LIMIT 1", [url.path, portable?.uuid ?? "", portable?.uuid ?? ""]) .first.flatMap { try? decoder.decode(FileRecord.self, from: Data($0.utf8)) } + return RoutingPreferences.trustedRecord(portable: portable, local: local) } func save(_ record: FileRecord, for url: URL, reason: String) { - guard let data = try? coder.encode(record) else { return } - record.write(to: url) + // Serialize identity assignment with other Router processes using the same database. + guard let db, sqlite3_exec(db, "BEGIN IMMEDIATE", nil, nil, nil) == SQLITE_OK else { return } + var saved = record + if let previousPath = query("SELECT path FROM files WHERE uuid = ?", [record.uuid]).first, + previousPath != url.path { + // The old path may be offline, so never reuse its identity at a different path. + saved.uuid = UUID().uuidString + } + guard let data = try? coder.encode(saved) else { + sqlite3_exec(db, "ROLLBACK", nil, nil, nil) + return + } let json = String(decoding: data, as: UTF8.self) - run("INSERT OR REPLACE INTO files(uuid, path, record, updated_at) VALUES(?, ?, ?, ?)", - [record.uuid, url.path, json, Date().timeIntervalSince1970]) - run("INSERT INTO events VALUES(?, ?, ?, ?, ?, ?)", - [Date().timeIntervalSince1970, record.uuid, url.path, record.printerModel ?? "", record.app.bundleID, reason]) + // A new identity for an existing path must not leave a stale competing row. + guard run("DELETE FROM files WHERE path = ? AND uuid <> ?", [url.path, saved.uuid]), + run("INSERT OR REPLACE INTO files(uuid, path, record, updated_at) VALUES(?, ?, ?, ?)", + [saved.uuid, url.path, json, Date().timeIntervalSince1970]), + run("INSERT INTO events VALUES(?, ?, ?, ?, ?, ?)", + [Date().timeIntervalSince1970, saved.uuid, url.path, saved.printerModel ?? "", saved.app.bundleID, reason]), + sqlite3_exec(db, "COMMIT", nil, nil, nil) == SQLITE_OK else { + sqlite3_exec(db, "ROLLBACK", nil, nil, nil) + return + } + saved.write(to: url) + RouterFileIcon.apply(to: url, app: saved.app) } func forget(_ url: URL) { FileRecord.remove(from: url) + RouterFileIcon.remove(from: url) run("DELETE FROM files WHERE path = ?", [url.path]) } @@ -128,10 +149,11 @@ final class Store { return stmt } - private func run(_ sql: String, _ args: [Any]) { - guard let stmt = prepare(sql, args) else { return } - sqlite3_step(stmt) - sqlite3_finalize(stmt) + @discardableResult + private func run(_ sql: String, _ args: [Any]) -> Bool { + guard let stmt = prepare(sql, args) else { return false } + defer { sqlite3_finalize(stmt) } + return sqlite3_step(stmt) == SQLITE_DONE } private func query(_ sql: String, _ args: [Any]) -> [String] { diff --git a/Sources/App/main.swift b/Sources/App/main.swift index c19dc9b..366d89a 100644 --- a/Sources/App/main.swift +++ b/Sources/App/main.swift @@ -1,5 +1,6 @@ import AppKit import ServiceManagement +import UniformTypeIdentifiers // CLI para conferir sem abrir app nem roubar foco: // 3dSlicerRouter --inspect arq.3mf… decisão que seria tomada (não grava nada) @@ -7,7 +8,7 @@ import ServiceManagement // 3dSlicerRouter --forget arq.3mf… apaga a memória do arquivo // 3dSlicerRouter --map "" /Applications/App.app impressora → qualquer fatiador // 3dSlicerRouter --mappings lista os mapeamentos -// 3dSlicerRouter --set-default torna o router o app padrão de .3mf +// 3dSlicerRouter --set-default torna o router o app padrão de .3mf e .gcode let args = Array(CommandLine.arguments.dropFirst()) func describe(_ d: Decision) -> String { @@ -25,24 +26,47 @@ case "--inspect": for path in args.dropFirst() { let url = URL(fileURLWithPath: path) do { - let info = try ThreeMF.info(url: url) + let document = try RoutableDocument.read(url: url) + let info = document.info let record = store.record(for: url) - let decision = Router.decide(info: info, record: record, mappings: store.mappings(), optionHeld: false) + let decision = document.decide(record: record, mappings: store.mappings(), optionHeld: false) + let target = document.expectedApp(record: record, mappings: store.mappings()) print(""" \(url.lastPathComponent) printer_model: \(info.printerModel ?? "-") brand: \(info.brand ?? "-") application: \(info.application ?? "-") + generator: \(document.generator ?? "-") + origin_slicer: \(document.originatingSlicer?.name ?? "-") + icon_style: \(SlicerIconStyle.style(for: target).rawValue) plates: \(info.plateCount) bed: \(info.bedMin) … \(info.bedMax) thumbnail: \(info.embeddedThumbnail ?? "nenhuma (gera preview)") record: \(record.map { "\($0.uuid) \($0.printerModel ?? "-") → \($0.app.name)" } ?? "-") decision: \(describe(decision)) - target_app: \(Router.expectedApp(info: info, record: record, mappings: store.mappings()).map { "\($0.bundleID) → \($0.path)" } ?? "-") + target_app: \(target.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 { print("\(path): erro \(error)") } } +case "--render-icon": + guard args.count >= 3, let style = SlicerIconStyle(rawValue: args[1].lowercased()) else { + print("usage: --render-icon router|bambu|orca|snapmaker|prusa|cura|creality|elegoo out.png [px]"); exit(2) + } + do { + let pixels = args.count > 3 ? Int(args[3]) ?? 128 : 128 + try RouterFileIcon.png(style: style, pixels: pixels).write(to: URL(fileURLWithPath: args[2])) + print("ok \(style.rawValue) \(pixels)px") + } catch { print("error: \(error)"); exit(1) } +case "--refresh-icons": + let store = Store() + var updated = 0 + for path in args.dropFirst() { + let url = URL(fileURLWithPath: path) + guard let document = try? RoutableDocument.read(url: url) else { continue } + if RouterFileIcon.apply(to: url, app: document.expectedApp(record: store.record(for: url), mappings: store.mappings())) { updated += 1 } + } + print("icons: \(updated)/\(max(0, args.count - 1))") case "--render": guard args.count >= 3 else { print("uso: --render arq.3mf out.png [px]"); exit(2) } let url = URL(fileURLWithPath: args[1]) @@ -116,7 +140,10 @@ case "--set-default": RouterApp.makeDefault { failure = $0; done = true } while !done { RunLoop.main.run(until: Date().addingTimeInterval(0.1)) } if let failure { print("erro \(failure)"); exit(1) } - print("padrão .3mf → \(NSWorkspace.shared.urlForApplication(toOpen: RouterApp.threeMFType)?.path ?? "?")") + for ext in FileAssociations.extensions { + let type = UTType(filenameExtension: ext) ?? (ext == "3mf" ? FileAssociations.threeMF : FileAssociations.gcode) + print("default .\(ext) → \(NSWorkspace.shared.urlForApplication(toOpen: type)?.path ?? "?")") + } default: let app = NSApplication.shared let delegate = RouterApp() diff --git a/Sources/Core/FileAssociations.swift b/Sources/Core/FileAssociations.swift new file mode 100644 index 0000000..50a8856 --- /dev/null +++ b/Sources/Core/FileAssociations.swift @@ -0,0 +1,44 @@ +import AppKit +import UniformTypeIdentifiers + +/// Claim only the registered types for our two document extensions, never public.data. +public enum FileAssociations { + public static let extensions = ["3mf", "gcode"] + public static let threeMF = UTType(importedAs: "org.3mf.3mf") + public static let gcode = UTType(importedAs: "com.moraesdev.gcode") + + public static var types: [UTType] { + var seen = Set() + return ([threeMF, gcode] + extensions.flatMap { + UTType.types(tag: $0, tagClass: .filenameExtension, conformingTo: .data) + }).filter { type in + !type.isDynamic && type != .data && type != .content && type != .plainText + && seen.insert(type.identifier).inserted + } + } + + public typealias Setter = (URL, UTType, @escaping (Error?) -> Void) -> Void + + public static func makeDefault(at app: URL, types: [UTType] = FileAssociations.types, + setter: @escaping Setter = { url, type, reply in + NSWorkspace.shared.setDefaultApplication(at: url, toOpen: type) { error in reply(error) } + }, completion: @escaping (Error?) -> Void) { + let group = DispatchGroup() + let lock = NSLock() + var failures: [String] = [] + for type in types { + group.enter() + setter(app, type) { error in + if error != nil { + lock.lock(); failures.append(type.identifier); lock.unlock() + } + group.leave() + } + } + group.notify(queue: .main) { + let error: Error? = failures.isEmpty ? nil : NSError(domain: "3dSlicerRouter.FileAssociations", code: 1, + userInfo: [NSLocalizedDescriptionKey: "Could not set the default application for: \(failures.sorted().joined(separator: ", "))"]) + completion(error) + } + } +} diff --git a/Sources/Core/GCode.swift b/Sources/Core/GCode.swift index f356600..eead575 100644 --- a/Sources/Core/GCode.swift +++ b/Sources/Core/GCode.swift @@ -16,10 +16,13 @@ public enum GCode { public static func metadata(url: URL) throws -> Metadata { let data = try Data(contentsOf: url, options: .alwaysMapped) let head = String(decoding: data.prefix(headBytes), as: UTF8.self) - let tail = data.count > headBytes ? String(decoding: data.suffix(tailBytes), as: UTF8.self) : "" + .replacingOccurrences(of: "\r\n", with: "\n").trimmingCharacters(in: CharacterSet(charactersIn: "\u{feff}")) + let tail = data.count > headBytes ? String(decoding: data.suffix(tailBytes), as: UTF8.self).replacingOccurrences(of: "\r\n", with: "\n") : "" var meta = Metadata() meta.thumbnail = largestThumbnail(in: head) - meta.generator = head.firstMatch(#"(?m)^; generated by ([^\n]+)"#) + meta.generator = (head.firstMatch(#"(?im)^;[ \t]*generated (?:by|with) ([^\n]+)"#) + ?? head.firstMatch(#"(?im)^;[ \t]*generator\.name[ \t]*:[ \t]*([^\n]+)"#)) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } let config = head + "\n" + tail func value(_ key: String) -> String? { config.firstMatch("(?m)^; \(key) = ([^\\n]*)$").map { $0.trimmingCharacters(in: .whitespaces) } diff --git a/Sources/Core/InstalledSlicers.swift b/Sources/Core/InstalledSlicers.swift index d55b5b4..f6e96a1 100644 --- a/Sources/Core/InstalledSlicers.swift +++ b/Sources/Core/InstalledSlicers.swift @@ -17,14 +17,16 @@ extension SlicerApp { } } } - urls += registeredURLs ?? known.flatMap { NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0.bundleID) } + urls += registeredURLs ?? known.flatMap { app in + app.registrationIDs.flatMap { NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0) } + } 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 known.firstIndex { $0.matchesBundleID(app.bundleID) } ?? known.count } return apps.sorted { rank($0) == rank($1) ? $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending : rank($0) < rank($1) @@ -39,16 +41,24 @@ extension SlicerApp { /// 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 } + if let installed = installation(at: saved), app.matchesBundleID(installed.bundleID) { return saved } + return app.registrationIDs.flatMap { NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0) } + .first { url in installation(at: url).map { app.matchesBundleID($0.bundleID) } ?? false } + } + + public static func installedApplication(for app: SlicerApp) -> SlicerApp? { + installedURL(for: app).flatMap(installation) + } + + private var registrationIDs: [String] { + matchesBundleID("com.prusa3d.slic3r") ? [bundleID, "com.prusa3d.slic3r", "com.prusa3d.slic3r/"] : [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 + let name = known.first { $0.matchesBundleID(id) }?.name ?? bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? bundle.object(forInfoDictionaryKey: "CFBundleName") as? String ?? url.deletingPathExtension().lastPathComponent @@ -56,7 +66,7 @@ extension SlicerApp { } private static func isSlicer(_ app: SlicerApp) -> Bool { - if known.contains(where: { $0.bundleID == app.bundleID }) { return true } + if known.contains(where: { $0.matchesBundleID(app.bundleID) }) { return true } let names = ["prusaslicer", "superslicer", "cura", "ultimakercura", "crealityprint", "anycubicslicer", "anycubicslicernext", "qidislicer", "qidistudio", "elegooslicer", "flashprint", "ideamaker", "simplify3d"] diff --git a/Sources/Core/L10n.swift b/Sources/Core/L10n.swift index 6a51f3d..62dbde7 100644 --- a/Sources/Core/L10n.swift +++ b/Sources/Core/L10n.swift @@ -34,22 +34,24 @@ public enum L10n { public static func rememberFor(_ model: String) -> String { t("Usar sempre para impressoras \(model)", "Always use for \(model) printers") } - public static var pickTitle: String { t("Escolha o app para abrir o 3MF", "Choose the app to open the 3MF") } + public static var pickTitle: String { t("Escolha o fatiador para abrir o arquivo", "Choose the slicer to open the file") } public static func notFound(_ app: String) -> String { t("\(app) não foi encontrado", "\(app) was not found") } 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 { + public static func about(current: String, gcode: String) -> String { t(""" - Abre cada .3mf no fatiador definido para a impressora declarada. - Sem impressora, pergunta entre os fatiadores instalados. + Abre .3mf pela impressora e .gcode pelo fatiador que o gerou. + Sua escolha por arquivo tem prioridade. Sem metadados, pergunta. Segure ⌥ ao abrir para escolher o app. App padrão de .3mf agora: \(current) + App padrão de .gcode agora: \(gcode) """, """ - Opens every .3mf in the slicer assigned to its declared printer. - Without a printer, asks you to choose an installed slicer. + Opens .3mf by its printer and .gcode by the slicer that generated it. + Your per-file choice takes priority. Without metadata, asks you to choose. Hold ⌥ while opening to pick the app. Current default app for .3mf: \(current) + Current default app for .gcode: \(gcode) """) } public static func alreadyOpen(_ file: String, _ app: String) -> String { @@ -69,7 +71,15 @@ public enum L10n { 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.") } - public static var makeDefault: String { t("Tornar padrão para .3mf", "Make default for .3mf") } + public static var makeDefault: String { t("Usar para .3mf e .gcode", "Use for .3mf and .gcode") } + public static var refreshIcons: String { t("Atualizar ícones de arquivos…", "Refresh file icons…") } + public static func refreshedIcons(_ count: Int, total: Int) -> String { + t("Ícones atualizados: \(count) de \(total)", "Icons updated: \(count) of \(total)") + } + public static var iconMetadataOnly: String { + t("Apenas os metadados de ícone foram alterados. O conteúdo dos arquivos permanece igual.", + "Only icon metadata changed. The file contents remain unchanged.") + } public static var close: String { t("Fechar", "Close") } public static var defaultFailed: String { t("Não consegui tornar padrão", "Could not set as default") } public static var none: String { t("nenhum", "none") } diff --git a/Sources/Core/RoutableDocument.swift b/Sources/Core/RoutableDocument.swift new file mode 100644 index 0000000..4d30d5a --- /dev/null +++ b/Sources/Core/RoutableDocument.swift @@ -0,0 +1,62 @@ +import Foundation + +/// Metadata and routing for a saved document. Reading never changes its contents. +public struct RoutableDocument { + public let info: ThreeMFInfo + public let generator: String? + public let originatingSlicer: SlicerApp? + public let isGCode: Bool + + public static func read(url: URL) throws -> RoutableDocument { + guard url.pathExtension.lowercased() == "gcode" else { + return RoutableDocument(info: try ThreeMF.info(url: url), generator: nil, + originatingSlicer: nil, isGCode: false) + } + let metadata = try GCode.metadata(url: url) + return RoutableDocument(info: metadata.info, generator: metadata.generator, + originatingSlicer: slicer(for: metadata.generator), isGCode: true) + } + + private static func slicer(for generator: String?) -> SlicerApp? { + guard let value = generator?.lowercased() else { return nil } + let candidates: [(String, SlicerApp)] = [ + ("snapmaker orca", .snapmakerOrca), ("snapmakerorca", .snapmakerOrca), + ("bambu studio", .bambuStudio), ("bambustudio", .bambuStudio), + ("orcaslicer", .orcaSlicer), ("orca slicer", .orcaSlicer), + ("prusaslicer", .prusaSlicer), ("cura_steamengine", .cura), + ("ultimaker cura", .cura), ("creality print", .crealityPrint), + ("crealityprint", .crealityPrint) + ] + for (name, app) in candidates where value == name || value.hasPrefix(name + " ") || value.hasPrefix(name + "-") { + return app + } + return nil + } + + public func decide(record: FileRecord?, mappings: Mappings, optionHeld: Bool) -> Decision { + guard isGCode else { return Router.decide(info: info, record: record, mappings: mappings, optionHeld: optionHeld) } + let explicit = info.printerModel.flatMap { mappings.byModel[$0] } + let selected = record?.override == true ? record?.app : (explicit ?? originatingSlicer) + // Preserve an installed custom path only when it identifies the same app. + let target = selected.map { app in + if record?.override != true, explicit != nil { return app } + return record.map { app.matchesBundleID($0.app.bundleID) ? $0.app : app } ?? app + } + if optionHeld { + let fallback = info.printerModel.flatMap { mappings.app(for: $0) } + return .ask(.manual, suggested: target ?? fallback) + } + if let target { return .open(target, reason: record?.override == true ? "escolha manual" : (explicit != nil ? "modelo mapeado" : "gerador")) } + guard info.printerModel != nil else { return .ask(.noPrinter, suggested: nil) } + // An automatic record reflects an older file revision, not the current metadata. + return Router.decide(info: info, record: nil, mappings: mappings, optionHeld: false) + } + + public func expectedApp(record: FileRecord?, mappings: Mappings) -> SlicerApp? { + guard isGCode else { return Router.expectedApp(info: info, record: record, mappings: mappings) } + switch decide(record: record, mappings: mappings, optionHeld: false) { + case let .open(app, _): return app + case let .ask(_, suggested): return suggested + } + } +} diff --git a/Sources/Core/RouterFileIcon.swift b/Sources/Core/RouterFileIcon.swift new file mode 100644 index 0000000..275e4d1 --- /dev/null +++ b/Sources/Core/RouterFileIcon.swift @@ -0,0 +1,235 @@ +import AppKit +import CryptoKit + +/// Our logo stays recognizable; the outline and letter identify the selected slicer. +public enum SlicerIconStyle: String, CaseIterable { + case router, bambu, orca, snapmaker, prusa, cura, creality, elegoo + + public static func style(for app: SlicerApp?) -> SlicerIconStyle { + guard let app else { return .router } + let identity = (app.bundleID + " " + app.name).lowercased().filter { $0.isLetter || $0.isNumber } + if identity.contains("snapmaker") { return .snapmaker } + if identity.contains("bambu") { return .bambu } + if identity.contains("prusa") { return .prusa } + if identity.contains("orca") { return .orca } + if identity.contains("cura") { return .cura } + if identity.contains("creality") { return .creality } + if identity.contains("elegoo") { return .elegoo } + return .router + } + + public var marker: String { + switch self { + case .router: return "R" + case .bambu: return "B" + case .orca: return "O" + case .snapmaker: return "S" + case .prusa: return "P" + case .cura: return "C" + case .creality: return "CR" + case .elegoo: return "E" + } + } + + public var colour: NSColor { + let rgb: UInt32 + switch self { + case .router: rgb = 0x87D9B6 + case .bambu: rgb = 0x00AE42 + case .orca: rgb = 0x368BC7 + case .snapmaker: rgb = 0x25BBAA + case .prusa: rgb = 0xF47929 + case .cura: rgb = 0x2463D8 + case .creality: rgb = 0x00A67A + case .elegoo: rgb = 0xB64479 + } + return NSColor(srgbRed: CGFloat((rgb >> 16) & 255) / 255, + green: CGFloat((rgb >> 8) & 255) / 255, blue: CGFloat(rgb & 255) / 255, alpha: 1) + } +} + +private final class RouterIconResourceAnchor: NSObject {} + +public enum RouterFileIcon { + private static let markerName = "com.moraesdev.slicer-router.icon" + private static let lock = NSRecursiveLock() + private static var icons: [SlicerIconStyle: NSImage] = [:] + + public static var logoURL: URL? { + let bundles = [Bundle.main, Bundle(for: RouterIconResourceAnchor.self)] + var candidates: [URL] = [] + for bundle in bundles { + if bundle.bundleIdentifier == "com.moraesdev.3dslicerrouter", + let resource = bundle.url(forResource: "AppIcon", withExtension: "icns") { return resource } + var directory = bundle.bundleURL + for _ in 0..<5 { + if directory.lastPathComponent == "3dSlicerRouter.app" { + candidates.append(directory.appendingPathComponent("Contents/Resources/AppIcon.icns")) + } + directory = directory.deletingLastPathComponent() + } + candidates.append(bundle.bundleURL.deletingLastPathComponent() + .appendingPathComponent("3dSlicerRouter.app/Contents/Resources/AppIcon.icns")) + } + return candidates.first { FileManager.default.fileExists(atPath: $0.path) } + } + + public static func usesBrandIcon(maximumSize: CGSize) -> Bool { + max(maximumSize.width, maximumSize.height) <= 64 + } + + public static func image(for app: SlicerApp?) -> NSImage { + let style = SlicerIconStyle.style(for: app) + lock.lock(); defer { lock.unlock() } + if let image = icons[style] { return image } + let image = render(style: style, pixels: 512) + icons[style] = image + return image + } + + public static func png(style: SlicerIconStyle, pixels: Int) throws -> Data { + guard (16...2048).contains(pixels), + let bitmap = render(style: style, pixels: pixels).representations.first as? NSBitmapImageRep, + let png = bitmap.representation(using: .png, properties: [:]) else { + throw NSError(domain: "3dSlicerRouter.Icon", code: 1) + } + return png + } + + private static func render(style: SlicerIconStyle, pixels: Int) -> NSImage { + let size = NSSize(width: pixels, height: pixels) + let image = NSImage(size: size) + guard let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: pixels, pixelsHigh: pixels, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0), + let context = NSGraphicsContext(bitmapImageRep: bitmap) else { return image } + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = context + defer { NSGraphicsContext.restoreGraphicsState() } + let s = CGFloat(pixels) + context.imageInterpolation = .high + NSColor.clear.setFill() + NSRect(origin: .zero, size: size).fill(using: .copy) + let outline = NSBezierPath(roundedRect: NSRect(x: s * 0.05, y: s * 0.05, width: s * 0.90, height: s * 0.90), + xRadius: s * 0.20, yRadius: s * 0.20) + NSColor(srgbRed: 0.09, green: 0.11, blue: 0.14, alpha: 1).setFill(); outline.fill() + if let logo = logoURL.flatMap({ NSImage(contentsOf: $0) }) { + logo.draw(in: NSRect(x: s * 0.105, y: s * 0.105, width: s * 0.79, height: s * 0.79)) + } else { + // Keep an identifiable stacked Router mark if the resource cannot be loaded. + for y in [0.30, 0.44, 0.58] { + style.colour.setFill() + NSBezierPath(roundedRect: NSRect(x: s * 0.27, y: s * y, width: s * 0.46, height: s * 0.12), + xRadius: s * 0.025, yRadius: s * 0.025).fill() + } + } + outline.lineWidth = max(1, s * 0.055) + style.colour.setStroke(); outline.stroke() + let badge = NSRect(x: s * 0.59, y: s * 0.025, width: s * 0.39, height: s * 0.39) + let circle = NSBezierPath(ovalIn: badge) + style.colour.setFill(); circle.fill() + circle.lineWidth = max(1, s * 0.025) + NSColor(srgbRed: 0.06, green: 0.08, blue: 0.10, alpha: 1).setStroke(); circle.stroke() + let font = NSFont.systemFont(ofSize: s * (style.marker.count == 1 ? 0.255 : 0.17), weight: .heavy) + let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: NSColor.white] + let text = style.marker as NSString + let textSize = text.size(withAttributes: attributes) + text.draw(at: NSPoint(x: badge.midX - textSize.width / 2, y: badge.midY - textSize.height / 2), withAttributes: attributes) + image.addRepresentation(bitmap) + return image + } + + private static func marker(for url: URL) -> String? { + let count = getxattr(url.path, markerName, nil, 0, 0, 0) + guard count > 0, count < 256 else { return nil } + var bytes = [UInt8](repeating: 0, count: count) + guard getxattr(url.path, markerName, &bytes, count, 0, 0) == count else { return nil } + return String(bytes: bytes, encoding: .utf8) + } + + private static func hasCustomIcon(_ url: URL) -> Bool { + var finderInfo = [UInt8](repeating: 0, count: 32) + return getxattr(url.path, "com.apple.FinderInfo", &finderInfo, 32, 0, 0) == 32 && finderInfo[8] & 0x04 != 0 + } + + private static func resourceDigest(_ url: URL) -> String? { + let count = getxattr(url.path, "com.apple.ResourceFork", nil, 0, 0, 0) + guard count > 0, count <= 16_777_216 else { return nil } + var data = Data(count: count) + let read = data.withUnsafeMutableBytes { getxattr(url.path, "com.apple.ResourceFork", $0.baseAddress, count, 0, 0) } + guard read == count else { return nil } + return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + + private static func ownsIcon(_ url: URL, marker: String?) -> Bool { + guard let marker else { return false } + let fields = marker.split(separator: ":") + return fields.count == 3 && fields[0] == "v2" && resourceDigest(url) == String(fields[2]) + } + + private static func digest(_ handle: FileHandle) throws -> Data { + try handle.seek(toOffset: 0) + var hash = SHA256() + while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty { hash.update(data: chunk) } + return Data(hash.finalize()) + } + + private static func sameRevision(_ a: stat, _ b: stat) -> Bool { + a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size + && a.st_mtimespec.tv_sec == b.st_mtimespec.tv_sec && a.st_mtimespec.tv_nsec == b.st_mtimespec.tv_nsec + } + + private static func setIconPreservingDate(_ image: NSImage?, at url: URL) -> Bool { + guard let handle = try? FileHandle(forReadingFrom: url) else { return false } + defer { try? handle.close() } + var before = stat(), stable = stat() + guard fstat(handle.fileDescriptor, &before) == 0, let original = try? digest(handle), + fstat(handle.fileDescriptor, &stable) == 0, sameRevision(before, stable) else { return false } + guard NSWorkspace.shared.setIcon(image, forFile: url.path, options: []) else { return false } + // setIcon also changes mtime. Restore nanoseconds only if the data and file identity + // are still the same. Use the open fd so an atomic replacement is never backdated. + var after = stat(), currentPath = stat() + guard let current = try? digest(handle), current == original, + fstat(handle.fileDescriptor, &after) == 0, stat(url.path, ¤tPath) == 0, + before.st_dev == currentPath.st_dev && before.st_ino == currentPath.st_ino, + before.st_size == after.st_size, sameRevision(after, currentPath) else { return false } + var times = [before.st_atimespec, before.st_mtimespec] + guard futimens(handle.fileDescriptor, ×) == 0 else { return false } + return true + } + + /// Finder icon metadata only. Failure must never prevent the file from opening. + @discardableResult + public static func apply(to url: URL, app: SlicerApp?) -> Bool { + guard FileAssociations.extensions.contains(url.pathExtension.lowercased()), + FileManager.default.isWritableFile(atPath: url.path) else { return false } + let stamp = "v2:\(SlicerIconStyle.style(for: app).rawValue)" + lock.lock(); defer { lock.unlock() } + let previous = marker(for: url) + let owned = ownsIcon(url, marker: previous) + if owned, previous?.hasPrefix(stamp + ":") == true, hasCustomIcon(url) { return true } + // A user-supplied custom icon is not ours to replace during routing or indexing. + if hasCustomIcon(url), !owned { return false } + guard setIconPreservingDate(image(for: app), at: url) else { return false } + guard let resource = resourceDigest(url) else { return false } + let bytes = Data((stamp + ":" + resource).utf8) + _ = bytes.withUnsafeBytes { setxattr(url.path, markerName, $0.baseAddress, bytes.count, 0, 0) } + NSWorkspace.shared.noteFileSystemChanged(url.path) + return true + } + + @discardableResult + public static func remove(from url: URL) -> Bool { + lock.lock(); defer { lock.unlock() } + let previous = marker(for: url) + guard previous != nil else { return true } + guard ownsIcon(url, marker: previous) else { + removexattr(url.path, markerName, 0) + return true + } + guard setIconPreservingDate(nil, at: url) else { return false } + removexattr(url.path, markerName, 0) + NSWorkspace.shared.noteFileSystemChanged(url.path) + return true + } +} diff --git a/Sources/Core/Routing.swift b/Sources/Core/Routing.swift index 8f01a71..304058a 100644 --- a/Sources/Core/Routing.swift +++ b/Sources/Core/Routing.swift @@ -11,13 +11,26 @@ public struct SlicerApp: Codable, Equatable, Hashable { self.name = name } + /// PrusaSlicer releases have used both forms of the same bundle identifier. + public func matchesBundleID(_ identifier: String) -> Bool { + if bundleID == identifier { return true } + let prusaIDs: Set = ["com.prusa3d.slic3r", "com.prusa3d.slic3r/"] + return prusaIDs.contains(bundleID) && prusaIDs.contains(identifier) + } + 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 = [orcaSlicer, bambuStudio, snapmakerOrca] + public static let prusaSlicer = SlicerApp( + bundleID: "com.prusa3d.slic3r/", path: "/Applications/PrusaSlicer.app", name: "PrusaSlicer") + public static let cura = SlicerApp( + bundleID: "nl.ultimaker.cura", path: "/Applications/UltiMaker Cura.app", name: "UltiMaker Cura") + public static let crealityPrint = SlicerApp( + bundleID: "com.creality.crealityprint", path: "/Applications/CrealityPrint.app", name: "Creality Print") + public static let known = [orcaSlicer, bambuStudio, snapmakerOrca, prusaSlicer, cura, crealityPrint] } /// Decisão gravada no arquivo (xattr) e no índice SQLite. diff --git a/Sources/Core/RoutingPreferences.swift b/Sources/Core/RoutingPreferences.swift new file mode 100644 index 0000000..b976fa8 --- /dev/null +++ b/Sources/Core/RoutingPreferences.swift @@ -0,0 +1,52 @@ +import Foundation +import SQLite3 + +/// Read-only snapshot for Quick Look. Do not create a database from an extension. +public struct RoutingPreferences { + public var record: FileRecord? + public var mappings = Mappings() + + public static let directory = PreviewCache.directory.deletingLastPathComponent() + + /// A document may carry a portable hint, but cannot authorize an arbitrary local app. + public static func trustedRecord(portable: FileRecord?, local: FileRecord?) -> FileRecord? { + // The portable UUID helps find our own confirmed choice after a local copy. + // A foreign file's application path is never authority to launch an app. + local + } + + public static func read(for url: URL, directory: URL = directory) -> RoutingPreferences { + let portable = FileRecord.read(from: url) + var result = RoutingPreferences(record: trustedRecord(portable: portable, local: nil)) + var db: OpaquePointer? + let database = directory.appendingPathComponent("router.sqlite").path + guard FileManager.default.fileExists(atPath: database), + sqlite3_open_v2(database, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK else { + sqlite3_close(db); return result + } + defer { sqlite3_close(db) } + sqlite3_busy_timeout(db, 100) + let decoder = JSONDecoder() + var statement: OpaquePointer? + if sqlite3_prepare_v2(db, "SELECT record FROM files WHERE path = ? OR (uuid = ? AND uuid <> '') ORDER BY (uuid = ? AND uuid <> '') DESC, updated_at DESC LIMIT 1", -1, &statement, nil) == SQLITE_OK { + let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + sqlite3_bind_text(statement, 1, url.path, -1, transient) + sqlite3_bind_text(statement, 2, portable?.uuid ?? "", -1, transient) + sqlite3_bind_text(statement, 3, portable?.uuid ?? "", -1, transient) + if sqlite3_step(statement) == SQLITE_ROW, let bytes = sqlite3_column_text(statement, 0) { + let local = try? decoder.decode(FileRecord.self, from: Data(String(cString: bytes).utf8)) + result.record = trustedRecord(portable: portable, local: local) + } + } + sqlite3_finalize(statement); statement = nil + if sqlite3_prepare_v2(db, "SELECT model, app FROM printers", -1, &statement, nil) == SQLITE_OK { + while sqlite3_step(statement) == SQLITE_ROW { + guard let model = sqlite3_column_text(statement, 0), let json = sqlite3_column_text(statement, 1), + let app = try? decoder.decode(SlicerApp.self, from: Data(String(cString: json).utf8)) else { continue } + result.mappings.byModel[String(cString: model)] = app + } + } + sqlite3_finalize(statement) + return result + } +} diff --git a/Sources/Thumbnail/ThumbnailProvider.swift b/Sources/Thumbnail/ThumbnailProvider.swift index 56e25a9..c475fe4 100644 --- a/Sources/Thumbnail/ThumbnailProvider.swift +++ b/Sources/Thumbnail/ThumbnailProvider.swift @@ -2,13 +2,27 @@ import AppKit import QuickLookThumbnailing /// Thumbnail do Finder para .3mf e .gcode. -/// - .3mf: primeira chapa em todos os tamanhos; cache atual antes da imagem embutida. +/// - Small requests: Router logo with the preferred slicer's colour and marker. +/// - Larger requests: current model/toolpath preview, preserving geometry and painting. final class ThumbnailProvider: QLThumbnailProvider { override func provideThumbnail(for request: QLFileThumbnailRequest, _ handler: @escaping (QLThumbnailReply?, Error?) -> Void) { let url = request.fileURL let box = request.maximumSize let side = max(256, max(box.width, box.height) * request.scale) do { + if RouterFileIcon.usesBrandIcon(maximumSize: box) { + let document = try? RoutableDocument.read(url: url) + let preferences = RoutingPreferences.read(for: url) + let app = document?.expectedApp(record: preferences.record, mappings: preferences.mappings) + let picture = RouterFileIcon.image(for: app) + let reply = QLThumbnailReply(contextSize: box) { () -> Bool in + picture.draw(in: NSRect(origin: .zero, size: box)) + return true + } + reply.extensionBadge = "" + handler(reply, nil) + return + } let image: CGImage if url.pathExtension.lowercased() == "gcode" { let meta = try GCode.metadata(url: url) diff --git a/Tests/CopyPreferenceTests.swift b/Tests/CopyPreferenceTests.swift new file mode 100644 index 0000000..c62f043 --- /dev/null +++ b/Tests/CopyPreferenceTests.swift @@ -0,0 +1,107 @@ +import Foundation +import XCTest + +final class CopyPreferenceTests: XCTestCase { + private func fixture(_ body: (URL, URL, Store) throws -> Void) throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("copy-choice-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let a = dir.appendingPathComponent("A.gcode"), b = dir.appendingPathComponent("B.gcode") + try Data("; synthetic\n".utf8).write(to: a) + try body(a, b, Store(directory: dir.appendingPathComponent("db"))) + } + private func choice(_ id: String, _ app: SlicerApp) -> FileRecord { + FileRecord(uuid: id, printerModel: nil, app: app, override: true, settingsHash: nil) + } + func testCopyInheritsThenSaveForksAndKeepsBothChoices() throws { + try fixture { a, b, store in + store.save(choice("original", .orcaSlicer), for: a, reason: "test") + try FileManager.default.copyItem(at: a, to: b) + let inherited = try XCTUnwrap(store.record(for: b)) + XCTAssertEqual(inherited.app, .orcaSlicer) + store.save(choice(inherited.uuid, .bambuStudio), for: b, reason: "test") + let first = try XCTUnwrap(store.record(for: a)), second = try XCTUnwrap(store.record(for: b)) + XCTAssertEqual(first.app, .orcaSlicer) + XCTAssertEqual(second.app, .bambuStudio) + XCTAssertNotEqual(first.uuid, second.uuid) + XCTAssertEqual(FileRecord.read(from: b)?.uuid, second.uuid) + XCTAssertEqual(RoutingPreferences.read(for: a, directory: a.deletingLastPathComponent().appendingPathComponent("db")).record?.app, .orcaSlicer) + XCTAssertEqual(RoutingPreferences.read(for: b, directory: a.deletingLastPathComponent().appendingPathComponent("db")).record?.app, .bambuStudio) + } + } + func testForgetEitherCopyPreservesOther() throws { + for forgetFirst in [true, false] { + try fixture { a, b, store in + store.save(choice("original", .orcaSlicer), for: a, reason: "test") + try FileManager.default.copyItem(at: a, to: b) + store.save(choice(try XCTUnwrap(store.record(for: b)).uuid, .bambuStudio), for: b, reason: "test") + store.forget(forgetFirst ? a : b) + XCTAssertNil(store.record(for: forgetFirst ? a : b)) + XCTAssertEqual(store.record(for: forgetFirst ? b : a)?.app, forgetFirst ? .bambuStudio : .orcaSlicer) + } + } + } + func testRenameRetainsChoiceAndMissingXattrUsesPath() throws { + try fixture { a, b, store in + store.save(choice("original", .orcaSlicer), for: a, reason: "test") + try FileManager.default.moveItem(at: a, to: b) + let moved = try XCTUnwrap(store.record(for: b)) + XCTAssertEqual(moved.uuid, "original") + store.save(moved, for: b, reason: "test") + let newID = try XCTUnwrap(store.record(for: b)?.uuid) + XCTAssertNotEqual(newID, "original") + FileRecord.remove(from: b) + XCTAssertEqual(store.record(for: b)?.app, .orcaSlicer) + XCTAssertEqual(store.record(for: b)?.uuid, newID) + } + } + func testUnavailableOriginalKeepsItsChoiceAfterCopyChanges() throws { + try fixture { a, b, store in + let source = a.deletingLastPathComponent().appendingPathComponent("source") + let hidden = a.deletingLastPathComponent().appendingPathComponent("offline") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let original = source.appendingPathComponent("A.gcode") + try FileManager.default.moveItem(at: a, to: original) + store.save(choice("original", .orcaSlicer), for: original, reason: "test") + try FileManager.default.copyItem(at: original, to: b) + try FileManager.default.moveItem(at: source, to: hidden) + let inherited = try XCTUnwrap(store.record(for: b)) + XCTAssertEqual(inherited.app, .orcaSlicer) + store.save(choice(inherited.uuid, .bambuStudio), for: b, reason: "test") + try FileManager.default.moveItem(at: hidden, to: source) + XCTAssertEqual(store.record(for: original)?.app, .orcaSlicer) + XCTAssertEqual(store.record(for: b)?.app, .bambuStudio) + XCTAssertNotEqual(store.record(for: original)?.uuid, store.record(for: b)?.uuid) + } + } + + func testRenameBackUsesCurrentLocalUUIDInsteadOfStalePath() throws { + try fixture { a, b, store in + let database = a.deletingLastPathComponent().appendingPathComponent("db") + store.save(choice("original", .orcaSlicer), for: a, reason: "test") + try FileManager.default.moveItem(at: a, to: b) + let inherited = try XCTUnwrap(store.record(for: b)) + store.save(choice(inherited.uuid, .bambuStudio), for: b, reason: "test") + let current = try XCTUnwrap(store.record(for: b)) + try FileManager.default.moveItem(at: b, to: a) + XCTAssertEqual(store.record(for: a)?.app, .bambuStudio) + XCTAssertEqual(store.record(for: a)?.uuid, current.uuid) + XCTAssertEqual(RoutingPreferences.read(for: a, directory: database).record?.app, .bambuStudio) + XCTAssertEqual(RoutingPreferences.read(for: a, directory: database).record?.uuid, current.uuid) + } + } + + func testUnknownPortableUUIDFallsBackToLocalPath() throws { + try fixture { a, _, store in + let database = a.deletingLastPathComponent().appendingPathComponent("db") + store.save(choice("local", .orcaSlicer), for: a, reason: "test") + XCTAssertTrue(choice("foreign", .bambuStudio).write(to: a)) + XCTAssertEqual(store.record(for: a)?.app, .orcaSlicer) + XCTAssertEqual(RoutingPreferences.read(for: a, directory: database).record?.app, .orcaSlicer) + FileRecord.remove(from: a) + XCTAssertEqual(store.record(for: a)?.app, .orcaSlicer) + XCTAssertEqual(RoutingPreferences.read(for: a, directory: database).record?.app, .orcaSlicer) + } + } + +} diff --git a/Tests/DocumentIconTests.swift b/Tests/DocumentIconTests.swift new file mode 100644 index 0000000..8c887e3 --- /dev/null +++ b/Tests/DocumentIconTests.swift @@ -0,0 +1,202 @@ +import AppKit +import UniformTypeIdentifiers +import XCTest + +final class DocumentIconTests: XCTestCase { + func testStylesDistinguishTheSlicersAndKeepUnknownAppsNeutral() { + XCTAssertEqual(SlicerIconStyle.style(for: .bambuStudio), .bambu) + XCTAssertEqual(SlicerIconStyle.style(for: .orcaSlicer), .orca) + XCTAssertEqual(SlicerIconStyle.style(for: .snapmakerOrca), .snapmaker) + XCTAssertEqual(SlicerIconStyle.style(for: SlicerApp(bundleID: "com.prusa3d.slic3r", path: "/Synthetic/PrusaSlicer.app", name: "PrusaSlicer")), .prusa) + XCTAssertEqual(SlicerIconStyle.style(for: SlicerApp(bundleID: "test.custom", path: "/Synthetic/Custom.app", name: "Custom")), .router) + XCTAssertEqual(Set(SlicerIconStyle.allCases.map(\.marker)).count, SlicerIconStyle.allCases.count) + } + + func testSmallIconsHaveDistinctPixelsAndLargerViewsKeepTheModel() throws { + XCTAssertTrue(RouterFileIcon.usesBrandIcon(maximumSize: CGSize(width: 16, height: 16))) + XCTAssertTrue(RouterFileIcon.usesBrandIcon(maximumSize: CGSize(width: 64, height: 64))) + XCTAssertFalse(RouterFileIcon.usesBrandIcon(maximumSize: CGSize(width: 65, height: 65))) + for pixels in [16, 32, 64, 512] { + let icons = try SlicerIconStyle.allCases.map { try RouterFileIcon.png(style: $0, pixels: pixels) } + XCTAssertEqual(Set(icons).count, icons.count) + XCTAssertTrue(icons.allSatisfy { NSImage(data: $0)?.size == NSSize(width: pixels, height: pixels) }) + } + XCTAssertNotNil(RouterFileIcon.logoURL, "Use the actual Router logo from the shipped app") + } + + func testApplyingAndRemovingAnIconPreservesDocumentContents() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + for ext in FileAssociations.extensions { + let file = directory.appendingPathComponent("synthetic.\(ext)") + let contents = Data("; generated by OrcaSlicer 2.4.0\nG1 X1 Y1 E1\n".utf8) + try contents.write(to: file) + let modified = try file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate + XCTAssertTrue(RouterFileIcon.apply(to: file, app: .orcaSlicer)) + XCTAssertTrue(RouterFileIcon.apply(to: file, app: .bambuStudio)) + XCTAssertEqual(try Data(contentsOf: file), contents) + XCTAssertEqual(try file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, modified) + XCTAssertTrue(RouterFileIcon.remove(from: file)) + XCTAssertEqual(try file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, modified) + XCTAssertEqual(try Data(contentsOf: file), contents) + } + } + + func testBothDocumentTypesHaveAssociationTargetsWithoutGenericData() { + XCTAssertEqual(FileAssociations.extensions, ["3mf", "gcode"]) + let types = FileAssociations.types + XCTAssertTrue(types.contains { $0.identifier == "org.3mf.3mf" }) + XCTAssertTrue(types.contains { $0.identifier == "com.moraesdev.gcode" }) + XCTAssertEqual(Set(types.map(\.identifier)).count, types.count) + XCTAssertFalse(types.contains { $0 == .data || $0 == .content || $0 == .plainText }) + let app = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("3dSlicerRouter.app") + let values = try? PropertyListSerialization.propertyList(from: Data(contentsOf: app.appendingPathComponent("Contents/Info.plist")), format: nil) as? [String: Any] + let declarations = values?["CFBundleDocumentTypes"] as? [[String: Any]] ?? [] + XCTAssertTrue(declarations.contains { ($0["LSItemContentTypes"] as? [String])?.contains("com.moraesdev.gcode") == true }) + XCTAssertTrue(declarations.allSatisfy { $0["CFBundleTypeIconFile"] as? String == "AppIcon" }) + } + + func testPersonalCustomIconsArePreservedBeforeAndAfterRouterIcons() throws { + try withDirectory { directory in + let file = directory.appendingPathComponent("personal.gcode") + try Data("; generated by OrcaSlicer 2.4.0\n".utf8).write(to: file) + let personal = NSImage(size: NSSize(width: 32, height: 32)) + personal.lockFocus() + NSColor.magenta.setFill() + NSRect(x: 0, y: 0, width: 32, height: 32).fill() + personal.unlockFocus() + XCTAssertTrue(NSWorkspace.shared.setIcon(personal, forFile: file.path, options: [])) + let original = fork(file) + XCTAssertFalse(RouterFileIcon.apply(to: file, app: .bambuStudio)) + XCTAssertTrue(RouterFileIcon.remove(from: file)) + XCTAssertEqual(fork(file), original) + XCTAssertTrue(NSWorkspace.shared.setIcon(nil, forFile: file.path, options: [])) + XCTAssertTrue(RouterFileIcon.apply(to: file, app: .orcaSlicer)) + XCTAssertTrue(NSWorkspace.shared.setIcon(personal, forFile: file.path, options: [])) + let replacement = fork(file) + XCTAssertFalse(RouterFileIcon.apply(to: file, app: .bambuStudio)) + XCTAssertTrue(RouterFileIcon.remove(from: file)) + XCTAssertEqual(fork(file), replacement, "A stale Router marker cannot authorize removing a later personal icon") + } + } + + func testReadOnlyPreferencesUseConfirmedLocalChoicesAfterXattrsDisappear() throws { + try withDirectory { directory in + let file = directory.appendingPathComponent("choice.gcode") + let contents = Data("; generated by OrcaSlicer 2.4.0\n; printer_model = Snapmaker U1\n".utf8) + try contents.write(to: file) + let storeDirectory = directory.appendingPathComponent("store") + let store = Store(directory: storeDirectory) + let foreign = FileRecord(uuid: "foreign", printerModel: nil, + app: SlicerApp(bundleID: "com.apple.Terminal", path: "/Applications/Utilities/Terminal.app", name: "Terminal"), + override: true, settingsHash: nil) + XCTAssertTrue(foreign.write(to: file)) + XCTAssertNil(store.record(for: file)) + XCTAssertNil(RoutingPreferences.read(for: file, directory: storeDirectory).record) + let foreignKnown = FileRecord(uuid: "foreign-known", printerModel: nil, app: .bambuStudio, override: true, settingsHash: nil) + XCTAssertTrue(foreignKnown.write(to: file)) + XCTAssertNil(store.record(for: file), "Even a known slicer needs a confirmed local choice before a document can claim it as the user's preference") + let chosen = FileRecord(uuid: "confirmed", printerModel: "Snapmaker U1", app: .bambuStudio, override: true, settingsHash: nil) + store.save(chosen, for: file, reason: "synthetic user selection") + store.remember(printer: "Snapmaker U1", app: .snapmakerOrca) + let copy = directory.appendingPathComponent("local-copy.gcode") + try FileManager.default.copyItem(at: file, to: copy) + XCTAssertEqual(RoutingPreferences.read(for: copy, directory: storeDirectory).record?.app, .bambuStudio) + FileRecord.remove(from: file) + let snapshot = RoutingPreferences.read(for: file, directory: storeDirectory) + XCTAssertEqual(snapshot.record?.app, .bambuStudio) + XCTAssertEqual(snapshot.mappings.byModel["Snapmaker U1"], .snapmakerOrca) + XCTAssertEqual(try RoutableDocument.read(url: file).expectedApp(record: snapshot.record, mappings: snapshot.mappings), .bambuStudio) + XCTAssertEqual(try Data(contentsOf: file), contents) + let missing = directory.appendingPathComponent("never-create-this-directory") + _ = RoutingPreferences.read(for: file, directory: missing) + XCTAssertFalse(FileManager.default.fileExists(atPath: missing.path)) + XCTAssertEqual(RoutingPreferences.directory, PreviewCache.directory.deletingLastPathComponent()) + } + } + + func testExplicitPrinterMappingKeepsItsSelectedInstallationPath() throws { + try withDirectory { directory in + let file = directory.appendingPathComponent("mapped.gcode") + try Data("; generated by Snapmaker Orca 2.4.1\n; printer_model = Snapmaker U1\n".utf8).write(to: file) + var maps = Mappings() + let beta = SlicerApp(bundleID: SlicerApp.snapmakerOrca.bundleID, path: "/Synthetic/Beta.app", name: "Snapmaker Orca") + maps.byModel["Snapmaker U1"] = beta + let previous = FileRecord(uuid: "u", printerModel: "Snapmaker U1", app: .snapmakerOrca, override: false, settingsHash: nil) + XCTAssertEqual(try RoutableDocument.read(url: file).expectedApp(record: previous, mappings: maps)?.path, beta.path) + } + } + + func testPrusaAliasesResolveTheRealRenamedInstallationAndKeepItsPath() throws { + try withDirectory { directory in + let bundle = directory.appendingPathComponent("Renamed Prusa.app") + let executable = bundle.appendingPathComponent("Contents/MacOS/slicer") + try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("#!/bin/sh\nexit 0\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + let info: [String: Any] = ["CFBundleIdentifier": "com.prusa3d.slic3r", "CFBundleName": "PrusaSlicer", "CFBundleExecutable": "slicer", "CFBundlePackageType": "APPL"] + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0) + .write(to: bundle.appendingPathComponent("Contents/Info.plist")) + var suggestion = SlicerApp.prusaSlicer + suggestion.path = bundle.path + let actual = try XCTUnwrap(SlicerApp.installedApplication(for: suggestion)) + XCTAssertEqual(actual.bundleID, "com.prusa3d.slic3r") + XCTAssertEqual(actual.path, bundle.path) + let file = directory.appendingPathComponent("prusa.gcode") + try Data("; generated by PrusaSlicer 3.0.0\n".utf8).write(to: file) + let saved = FileRecord(uuid: "alias", printerModel: nil, app: actual, override: false, settingsHash: nil) + XCTAssertEqual(try RoutableDocument.read(url: file).expectedApp(record: saved, mappings: Mappings()), actual) + } + } + + func testCachedGeometryDoesNotPreventIconRefreshAfterMappingChanges() throws { + try withDirectory { directory in + let file = directory.appendingPathComponent("cached.gcode") + try Data("; generated by OrcaSlicer 2.4.0\n; printer_model = Snapmaker U1\n".utf8).write(to: file) + let values = try file.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let store = Store(directory: directory.appendingPathComponent("store")) + var entry = Indexer.Entry(path: file.path, kind: "gcode", size: values.fileSize!, modified: values.contentModificationDate!) + entry.embedded = true + store.upsertCatalog(entry) + XCTAssertTrue(store.isCatalogued(file.path, size: entry.size, modified: entry.modified)) + XCTAssertTrue(Indexer.refreshIcon(for: file, store: store)) + let oldIcon = fork(file) + store.remember(printer: "Snapmaker U1", app: .bambuStudio) + XCTAssertTrue(Indexer.refreshIcon(for: file, store: store)) + XCTAssertNotEqual(fork(file), oldIcon) + XCTAssertTrue(store.isCatalogued(file.path, size: entry.size, modified: entry.modified)) + XCTAssertEqual(try file.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, entry.modified) + } + } + + private func fork(_ url: URL) -> Data? { + let size = getxattr(url.path, "com.apple.ResourceFork", nil, 0, 0, 0) + guard size > 0 else { return nil } + var data = Data(count: size) + let read = data.withUnsafeMutableBytes { getxattr(url.path, "com.apple.ResourceFork", $0.baseAddress, size, 0, 0) } + return read == size ? data : nil + } + + private func withDirectory(_ body: (URL) throws -> Void) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + try body(directory) + } + + func testDefaultAssociationWaitsForBothTypesAndReportsFailure() { + let done = expectation(description: "all association requests complete") + var requested: [String] = [] + let types = [UTType(importedAs: "org.3mf.3mf"), UTType(importedAs: "com.moraesdev.gcode")] + FileAssociations.makeDefault(at: URL(fileURLWithPath: "/Synthetic/Router.app"), types: types, setter: { _, type, reply in + requested.append(type.identifier) + reply(type.identifier == "com.moraesdev.gcode" ? NSError(domain: "synthetic", code: 1) : nil) + }) { error in + XCTAssertNotNil(error) + XCTAssertEqual(requested, types.map(\.identifier)) + done.fulfill() + } + wait(for: [done], timeout: 3) + } +} diff --git a/Tests/GCodeRoutingTests.swift b/Tests/GCodeRoutingTests.swift new file mode 100644 index 0000000..f9f5467 --- /dev/null +++ b/Tests/GCodeRoutingTests.swift @@ -0,0 +1,92 @@ +import Foundation +import XCTest + +final class GCodeRoutingTests: XCTestCase { + private func document(_ content: String, check: (RoutableDocument, URL) throws -> Void) throws { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("route-\(UUID().uuidString).gcode") + let bytes = Data(content.utf8) + try bytes.write(to: url) + defer { try? FileManager.default.removeItem(at: url) } + try check(RoutableDocument.read(url: url), url) + XCTAssertEqual(try Data(contentsOf: url), bytes) + } + private func record(_ app: SlicerApp, override: Bool = false) -> FileRecord { + FileRecord(uuid: "test", printerModel: "Bambu Lab A1", app: app, override: override, settingsHash: nil) + } + func testGeneratorWinsPrinterAndOldAutomaticRecord() throws { + try document("; generated by Snapmaker Orca 2.4.1\n; printer_model = Bambu Lab A1\n") { doc, _ in + XCTAssertEqual(doc.originatingSlicer, .snapmakerOrca) + XCTAssertEqual(doc.expectedApp(record: self.record(.bambuStudio), mappings: Mappings()), .snapmakerOrca) + } + } + func testManualOverrideAndOption() throws { + try document("; generated by OrcaSlicer 2.3.0\n") { doc, _ in + let record = self.record(.bambuStudio, override: true) + XCTAssertEqual(doc.expectedApp(record: record, mappings: Mappings()), .bambuStudio) + XCTAssertEqual(doc.decide(record: record, mappings: Mappings(), optionHeld: true), .ask(.manual, suggested: .bambuStudio)) + } + } + func testExplicitModelMappingWinsGeneratorAndAnOldAutomaticPath() throws { + try document("; generated by OrcaSlicer 2.3.0\n; printer_model = Bambu Lab A1\n") { doc, _ in + var mappings = Mappings(); mappings.byModel["Bambu Lab A1"] = .snapmakerOrca + let custom = SlicerApp(bundleID: SlicerApp.snapmakerOrca.bundleID, path: "/Custom/Snapmaker.app", name: "Custom") + XCTAssertEqual(doc.expectedApp(record: self.record(custom), mappings: mappings), .snapmakerOrca) + XCTAssertEqual(doc.expectedApp(record: self.record(custom, override: true), mappings: mappings), custom) + } + } + func testNoMetadataAsksAndIgnoresOldAutomaticChoice() throws { + try document("G1 X10 Y10\n; use OrcaSlicer someday\n") { doc, _ in + XCTAssertNil(doc.originatingSlicer) + XCTAssertEqual(doc.decide(record: self.record(.bambuStudio), mappings: Mappings(), optionHeld: false), .ask(.noPrinter, suggested: nil)) + XCTAssertNil(doc.expectedApp(record: self.record(.bambuStudio), mappings: Mappings())) + } + } + func testHeadersCRLFBOMAndLargestThumbnail() throws { + let content = "\u{feff}; generated by Bambu Studio 1.9\r\n; printer_model = Bambu Lab A1\r\n; thumbnail begin 1x1 4\r\n; AQ==\r\n; thumbnail end\r\n; thumbnail begin 2x2 4\r\n; Ag==\r\n; thumbnail end\r\n" + try document(content) { doc, url in + XCTAssertEqual(doc.originatingSlicer, .bambuStudio) + XCTAssertEqual(doc.info.printerModel, "Bambu Lab A1") + XCTAssertEqual(try GCode.metadata(url: url).thumbnail, Data([2])) + } + } + func testDeclaredGeneratorVariants() throws { + let cases: [(String, SlicerApp)] = [ + ("; generated by OrcaSlicer 2.2", .orcaSlicer), + ("; generated by BambuStudio 2.0", .bambuStudio), + ("; generated by SnapmakerOrca 2.4", .snapmakerOrca), + ("; generated by PrusaSlicer 2.9", .prusaSlicer), + (";Generated with Cura_SteamEngine 5.8.0", .cura), + ("; generated by Creality Print 6.0", .crealityPrint) + ] + for (header, app) in cases { + try document(header + "\n") { doc, _ in XCTAssertEqual(doc.originatingSlicer, app, header) } + } + } + func testStructuredGeneratorWithoutPrinterAndManualChoice() throws { + try document(";START_OF_HEADER\r\n;generator.name:PrusaSlicer\r\n;GENERATOR.VERSION:2.9\r\n;END_OF_HEADER\r\n") { doc, _ in + XCTAssertEqual(doc.originatingSlicer, .prusaSlicer) + XCTAssertEqual(doc.expectedApp(record: nil, mappings: Mappings()), .prusaSlicer) + XCTAssertEqual(doc.expectedApp(record: self.record(.bambuStudio, override: true), mappings: Mappings()), .bambuStudio) + } + } + + func testStructuredCuraAndOriginalGeneratedBy() throws { + for header in [";GENERATOR.NAME:Cura_SteamEngine", ";Generated with Cura_SteamEngine 5.8"] { + try document(header + "\n") { doc, _ in + XCTAssertEqual(doc.originatingSlicer, .cura) + XCTAssertEqual(doc.expectedApp(record: nil, mappings: Mappings()), .cura) + } + } + } + + func testPrusaBundleIDAliasesOnly() { + XCTAssertTrue(SlicerApp.prusaSlicer.matchesBundleID("com.prusa3d.slic3r/")) + XCTAssertTrue(SlicerApp.prusaSlicer.matchesBundleID("com.prusa3d.slic3r")) + let noSlash = SlicerApp(bundleID: "com.prusa3d.slic3r", path: "/tmp/Prusa.app", name: "Prusa") + XCTAssertTrue(noSlash.matchesBundleID("com.prusa3d.slic3r/")) + XCTAssertFalse(noSlash.matchesBundleID("com.prusa3d.slic3r.other")) + XCTAssertFalse(SlicerApp.orcaSlicer.matchesBundleID(SlicerApp.orcaSlicer.bundleID + "/")) + XCTAssertTrue(SlicerApp.orcaSlicer.matchesBundleID(SlicerApp.orcaSlicer.bundleID)) + } + +} diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 530dce3..642153e 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -14,7 +14,7 @@ The app uses native macOS frameworks. There is no package manager dependency at 1. **[Download 3dSlicerRouter.dmg](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)** from the [latest Release](https://github.com/MoraesGil/3dSlicerRouter/releases/latest). The same app supports Apple silicon and Intel. 2. Open the DMG. Drag **3dSlicerRouter** onto **Applications** in that window. -3. Eject the disk image. Open **3dSlicerRouter** from **Applications** and choose **Make default for .3mf**. +3. Eject the disk image. Open **3dSlicerRouter** from **Applications** and choose **Use for .3mf and .gcode**. You do not need Xcode, Homebrew, Git or Terminal. A ZIP is also available; extract it and move the app to Applications. `SHA256SUMS` contains the checksums for both downloads. @@ -49,12 +49,20 @@ alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRou ## 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. +1. Open **3dSlicerRouter** from Applications. Choose **Use for .3mf and .gcode**. 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. +## Finder file icons + +Small icons retain the Router logo. The outline colour and marker indicate the selected slicer: Bambu Studio (B), OrcaSlicer (O), Snapmaker Orca (S), PrusaSlicer (P), Cura (C), Creality Print (CR) or Elegoo (E). Unknown slicers use the neutral Router (R). Large thumbnails and Quick Look still show the model or toolpath. + +For G-code, a saved manual choice wins, followed by an explicit printer mapping and the declared generator. A plain brand default does not override a recognized generator. Hold Option while opening to choose again. + +Icons refresh when opening a file, indexing it, or requesting a small thumbnail. To refresh existing files without opening a slicer, open the Router, choose **Refresh file icons…**, and select the files. This changes Finder icon metadata, not the file contents. Read-only files or filesystems without supported metadata may retain a fallback icon. + ## 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. @@ -101,7 +109,7 @@ The build script preserves the optional indexer's enabled state and registers th ## Uninstall -Turn off the optional background item in System Settings if enabled, then move **3dSlicerRouter** from **Applications** to the Trash. Use Finder's **Get Info → Open with → Change All…** to assign `.3mf` to another installed slicer. This leaves the local catalog, cache, logs and routing choices in Application Support. +Turn off the optional background item in System Settings if enabled, then move **3dSlicerRouter** from **Applications** to the Trash. Use Finder's **Get Info → Open with → Change All…** to assign `.3mf` and `.gcode` to another installed slicer. This leaves the local catalog, cache, logs and routing choices in Application Support. For a source installation, this script also removes the app's catalog, preview cache and logs: diff --git a/docs/INSTALL.pt-BR.md b/docs/INSTALL.pt-BR.md index 27cd5f8..39512b3 100644 --- a/docs/INSTALL.pt-BR.md +++ b/docs/INSTALL.pt-BR.md @@ -14,7 +14,7 @@ O app usa frameworks nativos do macOS. Não exige dependência de package manage 1. **[Baixe 3dSlicerRouter.dmg](https://github.com/MoraesGil/3dSlicerRouter/releases/latest/download/3dSlicerRouter.dmg)** na [Release mais recente](https://github.com/MoraesGil/3dSlicerRouter/releases/latest). O mesmo app atende Apple silicon e Intel. 2. Abra o DMG. Arraste **3dSlicerRouter** para **Applications** nessa janela. -3. Ejete a imagem de disco. Abra **3dSlicerRouter** em **Aplicativos** e escolha **Tornar padrão para .3mf**. +3. Ejete a imagem de disco. Abra **3dSlicerRouter** em **Aplicativos** e escolha **Usar para .3mf e .gcode**. Você não precisa de Xcode, Homebrew, Git nem Terminal. Há também um ZIP: extraia-o e mova o app para Aplicativos. `SHA256SUMS` contém os hashes dos dois downloads. @@ -49,12 +49,20 @@ alias 3dSlicerRouter=/Applications/3dSlicerRouter.app/Contents/MacOS/3dSlicerRou ## 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. +1. Abra **3dSlicerRouter** em Aplicativos. Escolha **Usar para .3mf e .gcode**. 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. +## Ícones dos arquivos no Finder + +Os ícones pequenos mantêm a logo do Router. A cor da borda e o marcador indicam o slicer escolhido: Bambu Studio (B), OrcaSlicer (O), Snapmaker Orca (S), PrusaSlicer (P), Cura (C), Creality Print (CR) ou Elegoo (E). Slicers desconhecidos usam o Router neutro (R). As miniaturas grandes e o Quick Look continuam mostrando a peça ou o toolpath. + +No G-code, a escolha manual salva tem prioridade. Depois vêm o mapeamento explícito da impressora e o gerador declarado. O padrão de uma marca não substitui um gerador reconhecido. Segure Option ao abrir para escolher novamente. + +Os ícones são atualizados ao abrir ou indexar o arquivo, ou ao solicitar uma thumbnail pequena. Para atualizar arquivos existentes sem abrir um slicer, abra o Router, escolha **Atualizar ícones de arquivos…** e selecione os arquivos. Isso altera metadados de ícone do Finder, sem mudar o conteúdo do arquivo. Arquivos somente leitura ou em sistemas sem suporte a esses metadados podem manter um ícone de fallback. + ## Assinatura e downloads 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. @@ -101,7 +109,7 @@ O script de build preserva o estado habilitado do indexador opcional e registra ## Desinstalar -Desative o item opcional em background nos Ajustes do Sistema, se estiver ativo. Mova **3dSlicerRouter** de **Aplicativos** para a Lixeira. No Finder, use **Obter Informações → Abrir com → Alterar Tudo…** para associar `.3mf` a outro fatiador instalado. Isso mantém catálogo, cache, logs e escolhas de roteamento nos dados do usuário. +Desative o item opcional em background nos Ajustes do Sistema, se estiver ativo. Mova **3dSlicerRouter** de **Aplicativos** para a Lixeira. No Finder, use **Obter Informações → Abrir com → Alterar Tudo…** para associar `.3mf` e `.gcode` a outro fatiador instalado. Isso mantém catálogo, cache, logs e escolhas de roteamento nos dados do usuário. Para uma instalação a partir do código, este script também remove catálogo, cache de previews e logs do app: diff --git a/docs/images/router-file-icons.png b/docs/images/router-file-icons.png new file mode 100644 index 0000000..e0ab585 Binary files /dev/null and b/docs/images/router-file-icons.png differ diff --git a/docs/images/router-file-icons.svg b/docs/images/router-file-icons.svg new file mode 100644 index 0000000..5c70ff2 --- /dev/null +++ b/docs/images/router-file-icons.svg @@ -0,0 +1,19 @@ + + + +Router + +Bambu + +Orca + +Snapmaker + +Prusa + +Cura + +Creality + +Elegoo + diff --git a/project.yml b/project.yml index 9f2c596..e13f7af 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.4.0" - CURRENT_PROJECT_VERSION: "14" + MARKETING_VERSION: "1.5.0" + CURRENT_PROJECT_VERSION: "15" targets: SlicerRouter: type: application @@ -51,9 +51,15 @@ targets: public.filename-extension: [gcode, GCODE] CFBundleDocumentTypes: - CFBundleTypeName: 3MF Project + CFBundleTypeIconFile: AppIcon CFBundleTypeRole: Viewer LSHandlerRank: Owner LSItemContentTypes: [org.3mf.3mf] + - CFBundleTypeName: G-code + CFBundleTypeIconFile: AppIcon + CFBundleTypeRole: Viewer + LSHandlerRank: Owner + LSItemContentTypes: [com.moraesdev.gcode] settings: base: PRODUCT_NAME: 3dSlicerRouter diff --git a/scripts/build.sh b/scripts/build.sh index 3d26e61..59e6451 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -93,5 +93,5 @@ 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" + echo "make it the default for .3mf and .gcode: $DEST/Contents/MacOS/3dSlicerRouter --set-default" fi diff --git a/scripts/make_file_icons_svg.py b/scripts/make_file_icons_svg.py new file mode 100644 index 0000000..ae56c2a --- /dev/null +++ b/scripts/make_file_icons_svg.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Render the real app's file icons into a self-contained README illustration.""" +import base64 +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parent.parent +APP = ROOT / "build/DerivedData/Build/Products/Release/3dSlicerRouter.app/Contents/MacOS/3dSlicerRouter" +STYLES = [("router", "Router"), ("bambu", "Bambu"), ("orca", "Orca"), + ("snapmaker", "Snapmaker"), ("prusa", "Prusa"), ("cura", "Cura"), + ("creality", "Creality"), ("elegoo", "Elegoo")] + + +def main(): + if not APP.exists(): + raise SystemExit("Build first: ./scripts/build.sh --native") + items = [] + with tempfile.TemporaryDirectory(prefix="slicerrouter-icons-") as temporary: + for index, (style, label) in enumerate(STYLES): + png = Path(temporary) / f"{style}.png" + subprocess.run([str(APP), "--render-icon", style, str(png), "128"], check=True, capture_output=True) + encoded = base64.b64encode(png.read_bytes()).decode("ascii") + centre = 62.5 + index * 125 + items.append(f'') + items.append(f'{label}') + svg = '\n' + svg += '\n' + svg += "\n".join(items) + "\n\n" + destination = ROOT / "docs/images/router-file-icons.svg" + destination.write_text(svg) + png = destination.with_suffix(".png") + subprocess.run(["sips", "-s", "format", "png", str(destination), "--out", str(png)], check=True, capture_output=True) + print(destination.relative_to(ROOT)) + print(png.relative_to(ROOT)) + + +if __name__ == "__main__": + main() diff --git a/scripts/package.sh b/scripts/package.sh index 9519c90..2773b4c 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -17,7 +17,7 @@ Apple silicon + Intel INSTALL 1. Drag 3dSlicerRouter.app onto Applications in this window. 2. Eject this disk image. Open 3dSlicerRouter from Applications. -3. Choose “Make default for .3mf”. Keep at least one slicer installed. +3. Choose “Use for .3mf and .gcode”. Keep at least one slicer installed. This release is ad-hoc signed, not Developer ID signed or notarized. macOS may block the first launch. If you trust this download, follow @@ -28,7 +28,7 @@ Do not disable Gatekeeper or remove quarantine from the app. INSTALAR 1. Arraste 3dSlicerRouter.app para Applications nesta janela. 2. Ejete esta imagem de disco. Abra 3dSlicerRouter em Aplicativos. -3. Escolha “Tornar padrão para .3mf”. Mantenha um fatiador instalado. +3. Escolha “Usar para .3mf e .gcode”. Mantenha um fatiador instalado. Esta versão usa assinatura ad-hoc, sem Developer ID nem notarização. O macOS pode bloquear a primeira abertura. Se você confia no download, diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh index 94ffb9c..c898c59 100755 --- a/scripts/uninstall.sh +++ b/scripts/uninstall.sh @@ -1,7 +1,7 @@ #!/bin/zsh # Uninstall 3dSlicerRouter. -# ./scripts/uninstall.sh [bundle-id-for-.3mf] [--purge-xattrs ] -# Default: remove the app, its index and settings, then hand .3mf back to Bambu Studio. +# ./scripts/uninstall.sh [bundle-id-for-.3mf-and-.gcode] [--purge-xattrs ] +# Default: remove the app, its index and settings, then hand .3mf and .gcode back to Bambu Studio. set -uo pipefail TARGET="com.bambulab.bambu-studio" @@ -19,6 +19,11 @@ LSREGISTER=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchSe # Stop the optional background indexer before its bundle disappears. [[ -x "$APP/Contents/MacOS/3dSlicerRouter" ]] && "$APP/Contents/MacOS/3dSlicerRouter" --background off >/dev/null 2>&1 +# Explicit purge removes only Router-owned file icon metadata, before the binary is removed. +if [[ -n "$PURGE" && -x "$APP/Contents/MacOS/3dSlicerRouter" ]]; then + find "$PURGE" -type f \( -iname '*.3mf' -o -iname '*.gcode' \) -exec "$APP/Contents/MacOS/3dSlicerRouter" --forget {} + +fi + # Remove first: the app owns the org.3mf.3mf type declaration, so the new default must be set after it is gone. [[ -d "$APP" ]] && "$LSREGISTER" -u "$APP" rm -rf "$APP" @@ -28,12 +33,14 @@ qlmanage -r cache >/dev/null 2>&1 echo "removed app, index and settings" if command -v duti >/dev/null; then - duti -s "$TARGET" .3mf all && echo "default for .3mf → $TARGET" + for ext in .3mf .gcode; do + duti -s "$TARGET" "$ext" all && echo "default for $ext → $TARGET" + done else echo "duti not found: set the default in Finder (Get Info → Open with → Change All…)" fi if [[ -n "$PURGE" ]]; then - find "$PURGE" -name '*.3mf' -exec xattr -d com.moraesdev.slicer-router {} \; 2>/dev/null - echo "stripped router memory from .3mf files under $PURGE" + find "$PURGE" -type f \( -iname '*.3mf' -o -iname '*.gcode' \) -exec xattr -d com.moraesdev.slicer-router {} \; 2>/dev/null + echo "stripped router memory from .3mf and .gcode files under $PURGE" fi