Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ on:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
test:
runs-on: macos-15
Expand All @@ -14,10 +17,8 @@ jobs:
run: brew install xcodegen
- name: Generate project
run: xcodegen generate
- name: Test
run: xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -derivedDataPath build/DerivedData test
- name: Build Release
run: xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter -configuration Release -derivedDataPath build/DerivedData build
- name: Build, verify signatures and test
run: ./scripts/build.sh --test
- name: Package
run: ./scripts/package.sh
- uses: actions/upload-artifact@v4
Expand Down
5 changes: 3 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ Thanks for helping 3D printing on the Mac get a little less annoying.

```sh
brew install xcodegen
xcodegen generate
xcodebuild -project SlicerRouter.xcodeproj -scheme SlicerRouter test
./scripts/build.sh --test
./scripts/build.sh --install # try it for real
```

- Keep it dependency-free; macOS frameworks only.
- Routing rules live in one pure function (`Router.decide`). Every new rule gets a unit test.
- UI strings go through `L10n` (English + Portuguese).
- Keep routing and preview generation offline; do not add model endpoints or credential settings.
- Use `./scripts/build.sh --native --test` when the Xcode build service is unavailable.
- Never commit customer or proprietary models. Generate samples procedurally.
130 changes: 88 additions & 42 deletions README.md

Large diffs are not rendered by default.

126 changes: 84 additions & 42 deletions README.pt-BR.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.moraesdev.3dslicerrouter.indexer</string>
<string>com.moraesdev.3dslicerrouter.previews.v2</string>
<key>BundleProgram</key>
<string>Contents/MacOS/3dSlicerRouter</string>
<string>Contents/Helpers/3dSlicerIndexer</string>
<key>ProgramArguments</key>
<array>
<string>3dSlicerRouter</string>
<string>--index-agent</string>
<string>3dSlicerIndexer</string>
</array>
<key>RunAtLoad</key>
<true/>
Expand Down
28 changes: 20 additions & 8 deletions Sources/App/Indexer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import ServiceManagement
/// Acha todos os .3mf e .gcode pelo Spotlight, cataloga e pré-renderiza os previews que faltam,
/// só quando o Mac está na tomada e ocioso. Roda pelo LaunchAgent do app (`--index-agent`).
enum Indexer {
static let agentPlist = "com.moraesdev.3dslicerrouter.indexer.plist"
static let agentPlist = "com.moraesdev.3dslicerrouter.previews.v2.plist"
static let minIdle: TimeInterval = 180
/// Arquivos maiores que isso são catalogados mas não renderizados (malhas de centenas de MB).
static let maxRenderBytes = 250_000_000
static let maxRenderBytes = PreviewRenderer.maxRenderBytes
static let log = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Logs/3dSlicerRouter/indexer.log")

Expand Down Expand Up @@ -106,35 +106,47 @@ enum Indexer {
var printer: String?, plates = 1, embedded = false, preview: String?, rendered = false, error: String?
}

static func index(_ url: URL, size: Int, modified: Date) -> Entry {
static func index(_ url: URL, size: Int, modified: Date, cacheDirectory: URL = PreviewCache.directory,
readInfo: (URL) throws -> ThreeMFInfo = { try ThreeMF.info(url: $0) }) -> Entry {
let gcode = url.pathExtension.lowercased() == "gcode"
var entry = Entry(path: url.path, kind: gcode ? "gcode" : "3mf", size: size, modified: modified)
do {
guard let revision = PreviewCache.name(for: url) else { throw IndexError.changedDuringRender }
let render: () throws -> CGImage
if gcode {
let meta = try GCode.metadata(url: url)
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 ThreeMF.info(url: url)
let info = try readInfo(url)
entry.printer = info.printerModel
entry.plates = info.plateCount
entry.embedded = info.embeddedThumbnail != nil
render = { try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1024, height: 1024)) }
render = { try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1024, height: 1024), firstPlateOnly: true) }
}
if let cached = PreviewCache.cachedURL(for: url) {
guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender }
if let cached = PreviewCache.cachedURL(for: url, directory: cacheDirectory) {
entry.preview = cached.path
} else if !entry.embedded, size <= maxRenderBytes {
entry.preview = PreviewCache.store(try PreviewRenderer.encode(render()), for: url)?.path
} else if size <= maxRenderBytes, !gcode || !entry.embedded {
let png = try PreviewRenderer.encode(render())
guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender }
entry.preview = PreviewCache.store(png, for: url, directory: cacheDirectory, expectedName: revision)?.path
entry.rendered = entry.preview != nil
if !entry.rendered { throw IndexError.cacheWriteFailed }
// The .3mf's mtime does not change when its sidecar cache is refreshed.
// Ask Finder to request the new representation instead of retaining the embedded fallback.
NSWorkspace.shared.noteFileSystemChanged(url.path)
}
guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender }
} catch {
entry.error = "\(error)"
}
return entry
}

enum IndexError: Error { case changedDuringRender, cacheWriteFailed }

// MARK: agente em background

static var service: SMAppService { SMAppService.agent(plistName: agentPlist) }
Expand Down
67 changes: 0 additions & 67 deletions Sources/App/Laya.swift

This file was deleted.

6 changes: 3 additions & 3 deletions Sources/App/Prompt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ enum Prompt {
case let .unknownPrinter(m): alert.informativeText = L10n.reasonUnknown(m)
case let .printerChanged(from, to): alert.informativeText = L10n.reasonChanged(from ?? L10n.notDeclared, to)
case .noPrinter: alert.informativeText = L10n.reasonNoPrinter
case let .appUnavailable(name): alert.informativeText = L10n.reasonUnavailable(name)
}
if let png = info.embeddedThumbnail.flatMap({ try? ZipArchive(url: url).read($0) }), let image = NSImage(data: png) {
alert.icon = image
}

var apps = SlicerApp.known
if let s = suggested { apps.removeAll { $0 == s }; apps.insert(s, at: 0) }
let apps = SlicerApp.installed(suggested: suggested)
for app in apps { alert.addButton(withTitle: app.name) }
alert.addButton(withTitle: L10n.otherApp)
alert.addButton(withTitle: L10n.cancel)
Expand All @@ -36,7 +36,7 @@ enum Prompt {

let response = alert.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue
let remember = checkbox?.state == .on
if response < apps.count { return Choice(app: apps[response], remember: remember) }
if apps.indices.contains(response) { return Choice(app: apps[response], remember: remember) }
if response == apps.count, let other = pickApplication() { return Choice(app: other, remember: remember) }
return nil
}
Expand Down
22 changes: 7 additions & 15 deletions Sources/App/RouterApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ final class RouterApp: NSObject, NSApplicationDelegate {

func application(_ app: NSApplication, open urls: [URL]) {
handledFiles = true
pending += 1
defer { pending -= 1; finishWhenIdle() }
let option = NSEvent.modifierFlags.contains(.option)
for url in urls { route(url, optionHeld: option) }
finishWhenIdle()
}

// MARK: roteamento
Expand All @@ -32,13 +33,8 @@ final class RouterApp: NSObject, NSApplicationDelegate {
let mappings = store.mappings()
var decision = Router.decide(info: info, record: record, mappings: mappings, optionHeld: optionHeld)

if decision == .classify {
let guess = Laya.classify(info: info, fileName: url.lastPathComponent)
if let guess, guess.probability >= Laya.minProbability {
decision = .open(guess.app, reason: String(format: "LAYA %.0f%%", guess.probability * 100))
} else {
decision = .ask(.noPrinter, suggested: guess?.app)
}
if case let .open(app, _) = decision, SlicerApp.installedURL(for: app) == nil {
decision = .ask(.appUnavailable(app.name), suggested: nil)
}

let app: SlicerApp, reason: String, override: Bool
Expand All @@ -50,24 +46,20 @@ final class RouterApp: NSObject, NSApplicationDelegate {
app = choice.app; reason = "escolha do dono"
override = info.printerModel.flatMap(mappings.app(for:)) != choice.app
if choice.remember, let model = info.printerModel { store.remember(printer: model, app: choice.app) }
case .classify:
return
}

guard open(url, with: app) else { return }
let uuid = record?.uuid ?? UUID().uuidString
store.save(FileRecord(uuid: uuid, printerModel: info.printerModel, app: app, override: override,
settingsHash: info.settingsHash), for: url, reason: reason)
// Só o xattr mudou (ex.: escolha com ⌥): pede ao Finder para reler o ícone.
// Notify Finder after updating this file's routing metadata.
NSWorkspace.shared.noteFileSystemChanged(url.path)
}

@discardableResult
func open(_ url: URL, with app: SlicerApp) -> Bool {
let appURL = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleID)
?? URL(fileURLWithPath: app.path)
guard FileManager.default.fileExists(atPath: appURL.path) else {
Prompt.error(L10n.notFound(app.name), detail: appURL.path)
guard let appURL = SlicerApp.installedURL(for: app) else {
Prompt.error(L10n.notFound(app.name), detail: app.path)
return false
}
pending += 1
Expand Down
18 changes: 11 additions & 7 deletions Sources/App/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ final class Store {
private let coder = JSONEncoder()
private let decoder = JSONDecoder()

init() {
try? FileManager.default.createDirectory(at: Self.supportDir, withIntermediateDirectories: true)
let path = Self.supportDir.appendingPathComponent("router.sqlite").path
init(directory: URL = Store.supportDir) {
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let path = directory.appendingPathComponent("router.sqlite").path
if sqlite3_open(path, &db) != SQLITE_OK { db = nil; return }
exec("""
CREATE TABLE IF NOT EXISTS files(uuid TEXT PRIMARY KEY, path TEXT, record TEXT, updated_at REAL);
Expand Down Expand Up @@ -71,13 +71,17 @@ final class Store {
// MARK: catálogo (indexador)

func isCatalogued(_ path: String, size: Int, modified: Date) -> Bool {
!query("SELECT 1 FROM catalog WHERE path = ? AND size = ? AND mtime = ?",
[path, Double(size), modified.timeIntervalSince1970.rounded()]).isEmpty
guard let preview = query("SELECT CASE WHEN kind = 'gcode' AND embedded = 1 THEN 'embedded-gcode' ELSE preview END FROM catalog WHERE path = ? AND size = ? AND mtime = ? AND error = ''",
[path, Double(size), modified.timeIntervalSince1970]).first else { return false }
if preview == "embedded-gcode" { return true }
if size > Indexer.maxRenderBytes { return true }
return !preview.isEmpty && URL(fileURLWithPath: preview).lastPathComponent == PreviewCache.name(for: URL(fileURLWithPath: path))
&& FileManager.default.fileExists(atPath: preview)
}

func upsertCatalog(_ e: Indexer.Entry) {
run("INSERT OR REPLACE INTO catalog VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[e.path, e.kind, Double(e.size), e.modified.timeIntervalSince1970.rounded(), e.printer ?? "",
[e.path, e.kind, Double(e.size), e.modified.timeIntervalSince1970, e.printer ?? "",
Double(e.plates), Double(e.embedded ? 1 : 0), e.preview ?? "", e.error ?? "", Date().timeIntervalSince1970])
}

Expand All @@ -101,7 +105,7 @@ final class Store {
func catalogStats() -> String {
query("""
SELECT count(*) || ' arquivos: ' || sum(kind = '3mf') || ' .3mf, ' || sum(kind = 'gcode') || ' .gcode; ' ||
sum(embedded = 1) || ' com thumbnail embutida, ' || sum(preview <> '' AND embedded = 0) || ' renderizados, ' ||
sum(embedded = 1) || ' com thumbnail embutida, ' || sum(preview <> '') || ' renderizados, ' ||
sum(error <> '') || ' com erro' FROM catalog
""", []).first ?? "catálogo vazio"
}
Expand Down
22 changes: 13 additions & 9 deletions Sources/App/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ func describe(_ d: Decision) -> String {
switch d {
case let .open(app, reason): return "open \(app.name) (\(reason))"
case let .ask(why, suggested): return "ask \(why) suggested=\(suggested?.name ?? "-")"
case .classify: return "classify (LAYA)"
}
}

switch args.first {
case "--list-slicers":
for app in SlicerApp.installed() { print("\(app.name)\t\(app.bundleID)\t\(app.path)") }
case "--inspect":
let store = Store()
for path in args.dropFirst() {
Expand All @@ -27,9 +28,6 @@ case "--inspect":
let info = try ThreeMF.info(url: url)
let record = store.record(for: url)
let decision = Router.decide(info: info, record: record, mappings: store.mappings(), optionHeld: false)
let laya = decision == .classify
? Laya.classify(info: info, fileName: url.lastPathComponent).map { String(format: "%@ %.0f%%", $0.app.name, $0.probability * 100) } ?? "sem palpite"
: "-"
print("""
\(url.lastPathComponent)
printer_model: \(info.printerModel ?? "-") brand: \(info.brand ?? "-")
Expand All @@ -38,7 +36,7 @@ case "--inspect":
thumbnail: \(info.embeddedThumbnail ?? "nenhuma (gera preview)")
record: \(record.map { "\($0.uuid) \($0.printerModel ?? "-") → \($0.app.name)" } ?? "-")
decision: \(describe(decision))
laya: \(laya) (abre direto a partir de \(Int(Laya.minProbability * 100))%)
target_app: \(Router.expectedApp(info: info, record: record, mappings: store.mappings()).map { "\($0.bundleID) → \($0.path)" } ?? "-")
aberto agora: \(OpenProjects.find(url, running: RouterApp.process(pid:)).map { "\($0.bundleID) pid \($0.pid)\($0.dirty ? " (alterações não salvas)" : "")" } ?? "não")
""")
} catch {
Expand Down Expand Up @@ -80,8 +78,13 @@ case "--index":
let s = Indexer.run(store: Store(), force: true, limit: limit, budget: .infinity)
print("achados \(s.found), renderizados \(s.rendered), já ok \(s.skipped), erros \(s.failed)")
case "--index-agent":
// Chamado pelo LaunchAgent: só trabalha na tomada e com o Mac ocioso.
Indexer.run(store: Store(), force: false)
// Bootstrap signed as the host for SMAppService, then replace the process image.
// Never render in the Finder handler: LaunchServices would reuse this busy process.
let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/3dSlicerIndexer").path
var argv = ([helper] + args.dropFirst()).map { strdup($0) } + [nil]
execv(helper, &argv)
perror("3dSlicerIndexer")
exit(1)
case "--index-status":
print("background: \(Indexer.statusText())")
print("agora: \(Indexer.whyNotNow() ?? "pronto para indexar (na tomada e ocioso)")")
Expand All @@ -92,12 +95,13 @@ case "--catalog":
case "--background":
do {
switch args.count > 1 ? args[1] : "status" {
case "on": try Indexer.service.register()
case "on":
try Indexer.service.register()
if Indexer.service.status == .requiresApproval { SMAppService.openSystemSettingsLoginItems() }
case "off": try Indexer.service.unregister()
default: break
}
print("background: \(Indexer.statusText())")
if Indexer.service.status == .requiresApproval { SMAppService.openSystemSettingsLoginItems() }
} catch {
print("erro: \(error.localizedDescription)"); exit(1)
}
Expand Down
Loading
Loading