diff --git a/README.md b/README.md index d59032c..a6079c4 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ Big projects take seconds to render. Turn on the indexer and they are ready befo - It finds every `.3mf` and `.gcode` on the Mac through Spotlight (no disk crawling) and keeps a catalog. - It wakes every 30 minutes at background priority and **only works on AC power, outside Low Power Mode, while the Mac is cool and you have been away for 3 minutes**. It stops as soon as you are back. +- Quick Look, thumbnails and the indexer share one heavy render slot. Geometry generation requires CPU and GPU below 30%, at least 25% available memory, normal power mode and acceptable temperature. If GPU usage is unavailable, the Mac must also be idle for 3 minutes. Busy requests use a cached or embedded image when available. - Rendering runs in a separate executable, with a 20-minute run limit and conditions checked every 5 seconds even during a complex preview, so it cannot occupy the Finder handler. - Previews go to `~/Library/Application Support/3dSlicerRouter/previews`. Saves invalidate the generated @@ -286,7 +287,7 @@ attributes, opening still works; Finder uses the extension icon or thumbnail fal **Does the preview update after I edit the project?** A save invalidates the generated preview. Finder's next request renders current first-plate geometry if no indexed image is ready; the optional indexer -prepares it during its next idle pass. Only the error/large-project fallback can retain an old slicer +prepares it during its next idle pass. The busy/error/large-project fallback can retain an old slicer screenshot. Closing without saving changes nothing. **Does it need special permissions?** Opening a file and generating its preview do not require diff --git a/README.pt-BR.md b/README.pt-BR.md index 1837046..fef9bb8 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -134,6 +134,7 @@ abrir o Finder: - Acha todos os `.3mf` e `.gcode` do Mac pelo Spotlight (sem varrer o disco) e mantém um catálogo. - Acorda a cada 30 minutos com prioridade de background e **só trabalha na tomada, fora do modo de pouca energia, com o Mac frio e você ausente há 3 minutos**. Para assim que você volta. +- O Quick Look, as miniaturas e o indexador compartilham uma vaga para gerar geometria. A geração exige CPU e GPU abaixo de 30%, pelo menos 25% de memória disponível, temperatura adequada e modo de pouca energia desligado. Se a leitura da GPU estiver indisponível, o Mac também deve estar ocioso há 3 minutos. Sob carga, o Finder usa uma imagem em cache ou embutida quando disponível. - Os previews ficam em `~/Library/Application Support/3dSlicerRouter/previews`. Salvar invalida a imagem gerada, inclusive com o mesmo tamanho dentro do mesmo segundo. A próxima passada elegível renderiza a geometria atual da primeira chapa mesmo com imagem embutida antiga e avisa o Finder. Falhas e caches ausentes são repetidos. @@ -284,7 +285,7 @@ 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 -opcional a prepara na próxima passada ociosa. Apenas o fallback de erro/projeto grande pode manter um +opcional a prepara na próxima passada ociosa. O fallback de carga, erro ou projeto grande pode manter um screenshot antigo do fatiador. Fechar sem salvar não muda nada. **Precisa de permissão especial?** Abrir um arquivo e gerar seu preview não exige Acessibilidade, diff --git a/Sources/App/Indexer.swift b/Sources/App/Indexer.swift index 5a404fc..30a1079 100644 --- a/Sources/App/Indexer.swift +++ b/Sources/App/Indexer.swift @@ -23,21 +23,11 @@ enum Indexer { return type == kIOPMACPowerKey } - /// Segundos desde o último evento de teclado/mouse (IOHIDSystem, sem permissão especial). - static var idleSeconds: TimeInterval { - let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOHIDSystem")) - defer { IOObjectRelease(service) } - guard service != 0, - let value = IORegistryEntryCreateCFProperty(service, "HIDIdleTime" as CFString, kCFAllocatorDefault, 0)? - .takeRetainedValue() as? NSNumber else { return 0 } - return value.doubleValue / 1_000_000_000 - } - static func whyNotNow() -> String? { if !onACPower { return "na bateria" } if ProcessInfo.processInfo.isLowPowerModeEnabled { return "modo de pouca energia" } if ProcessInfo.processInfo.thermalState.rawValue >= ProcessInfo.ThermalState.serious.rawValue { return "Mac quente" } - let idle = idleSeconds + let idle = PreviewGate.idleSeconds() if idle < minIdle { return String(format: "em uso (ocioso há %.0fs)", idle) } return nil } @@ -71,7 +61,9 @@ enum Indexer { write("pulado: \(reason)") return summary } + guard (try? PreviewGate.check()) != nil else { summary.stoppedEarly = true; return summary } let start = Date() + var nextCheck = ProcessInfo.processInfo.systemUptime + 2 var files = discover().compactMap { url -> (URL, Int, Date)? in guard let v = try? url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]), let size = v.fileSize, let modified = v.contentModificationDate else { return nil } @@ -89,6 +81,10 @@ enum Indexer { summary.stoppedEarly = true break } + if ProcessInfo.processInfo.systemUptime >= nextCheck { + guard (try? PreviewGate.check()) != nil else { summary.stoppedEarly = true; break } + nextCheck = ProcessInfo.processInfo.systemUptime + 2 + } if store.isCatalogued(url.path, size: size, modified: modified) { refreshIcon(for: url, store: store) summary.skipped += 1 @@ -96,6 +92,10 @@ enum Indexer { } autoreleasepool { let entry = index(url, size: size, modified: modified) + if entry.deferred { + summary.skipped += 1 + return // Retry on a later pass without cataloguing partial work. + } store.upsertCatalog(entry) if entry.error != nil { summary.failed += 1 } else if entry.rendered { summary.rendered += 1 } else { summary.skipped += 1 } } @@ -107,6 +107,7 @@ enum Indexer { struct Entry { let path: String, kind: String, size: Int, modified: Date + var deferred = false var printer: String?, plates = 1, embedded = false, preview: String?, rendered = false, error: String? } @@ -117,12 +118,13 @@ enum Indexer { } static func index(_ url: URL, size: Int, modified: Date, cacheDirectory: URL = PreviewCache.directory, + admit: (URL, (_ check: @escaping () throws -> Void) throws -> CGImage) throws -> CGImage = PreviewGate.run, 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 + let render: (_ check: @escaping () throws -> Void) throws -> CGImage if gcode { let meta = try GCode.metadata(url: url) if let document = try? RoutableDocument.read(url: url) { @@ -131,7 +133,7 @@ enum Indexer { } 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)) } + render = { checkpoint in try PreviewRenderer.renderGCode(url: url, info: meta.info, size: CGSize(width: 1024, height: 1024), checkpoint: checkpoint) } } else { let info = try readInfo(url) let preferences = RoutingPreferences.read(for: url) @@ -139,13 +141,13 @@ enum Indexer { 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), firstPlateOnly: true) } + render = { checkpoint in try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1024, height: 1024), firstPlateOnly: true, checkpoint: checkpoint) } } 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 size <= maxRenderBytes, !gcode || !entry.embedded { - let png = try PreviewRenderer.encode(render()) + let png = try PreviewRenderer.encode(admit(url, 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 @@ -155,6 +157,8 @@ enum Indexer { NSWorkspace.shared.noteFileSystemChanged(url.path) } guard revision == PreviewCache.name(for: url) else { throw IndexError.changedDuringRender } + } catch is PreviewGate.Busy { + entry.deferred = true } catch { entry.error = "\(error)" } diff --git a/Sources/Core/GCode.swift b/Sources/Core/GCode.swift index eead575..41a8dc1 100644 --- a/Sources/Core/GCode.swift +++ b/Sources/Core/GCode.swift @@ -61,7 +61,7 @@ public enum GCode { } /// Caminho de extrusão em coordenadas da mesa, uma lista de segmentos (pares de pontos) por cor. - public static func toolpath(url: URL, info: ThreeMFInfo, maxSegments: Int = 1_500_000) throws -> PrintScene { + public static func toolpath(url: URL, info: ThreeMFInfo, maxSegments: Int = 1_500_000, checkpoint: () throws -> Void = {}) throws -> PrintScene { let data = try Data(contentsOf: url, options: .alwaysMapped) var scene = PrintScene() scene.beds = PrintScene.bedLayout(count: 1, min: info.bedMin, max: info.bedMax) @@ -76,11 +76,16 @@ public enum GCode { var segments: [Int: [SIMD3]] = [:] var count = 0 - data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in + try data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) in let bytes = raw.bindMemory(to: UInt8.self) var i = 0 let n = bytes.count + var nextCheck = 0 while i < n { + if i >= nextCheck { + try checkpoint() + nextCheck = i + 256 * 1024 + } var end = i while end < n && bytes[end] != 10 { end += 1 } defer { i = end + 1 } diff --git a/Sources/Core/PreviewGate.swift b/Sources/Core/PreviewGate.swift new file mode 100644 index 0000000..b4e1e00 --- /dev/null +++ b/Sources/Core/PreviewGate.swift @@ -0,0 +1,120 @@ +import Foundation +import IOKit + +/// Admission for automatic geometry work. Cheap cached and embedded images bypass it. +enum PreviewGate { + struct Busy: LocalizedError { + var errorDescription: String? { + L10n.t("Prévia 3D adiada. Tente novamente quando o Mac estiver livre.", + "3D preview deferred. Try again when the Mac is available.") + } + } + + static func permits(cpu: Double?, gpu: Double?, idle: Double, available: Double, + thermal: ProcessInfo.ThermalState, lowPower: Bool) -> Bool { + guard let cpu, cpu < 30, available >= 0.25, !lowPower, thermal.rawValue < ProcessInfo.ThermalState.serious.rawValue else { return false } + // Some Intel drivers and extension sandboxes do not expose GPU counters. + return gpu.map { $0 < 30 } ?? (idle >= 180) + } + + static func idleSeconds() -> Double { + let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOHIDSystem")) + guard service != 0 else { return 0 } + defer { IOObjectRelease(service) } + let value = IORegistryEntryCreateCFProperty(service, "HIDIdleTime" as CFString, nil, 0)?.takeRetainedValue() + return ((value as? NSNumber)?.doubleValue ?? 0) / 1e9 + } + + private static func gpuPercent() -> Double? { + var entries: io_iterator_t = 0 + guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &entries) == KERN_SUCCESS else { return nil } + defer { IOObjectRelease(entries) } + var peak: Double? + while case let entry = IOIteratorNext(entries), entry != 0 { + defer { IOObjectRelease(entry) } + let stats = IORegistryEntryCreateCFProperty(entry, "PerformanceStatistics" as CFString, nil, 0)?.takeRetainedValue() as? NSDictionary + guard let number = stats?["Device Utilization %"] as? NSNumber else { continue } + peak = max(peak ?? 0, number.doubleValue) + } + return peak + } + + private static func cpuTicks() -> (UInt32, UInt32)? { + var info = host_cpu_load_info() + var count = mach_msg_type_number_t(MemoryLayout.size(ofValue: info) / MemoryLayout.size) + let host = mach_host_self() + defer { mach_port_deallocate(mach_task_self_, host) } + let result = withUnsafeMutablePointer(to: &info) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + host_statistics(host, HOST_CPU_LOAD_INFO, $0, &count) + } + } + let (user, system, idle, nice) = info.cpu_ticks + return result == KERN_SUCCESS ? (user &+ system &+ nice, idle) : nil + } + + private static func availableBytes() -> Double { + var vm = vm_statistics64() + var count = mach_msg_type_number_t(MemoryLayout.size(ofValue: vm) / MemoryLayout.size) + let host = mach_host_self() + defer { mach_port_deallocate(mach_task_self_, host) } + let result = withUnsafeMutablePointer(to: &vm) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + host_statistics64(host, HOST_VM_INFO64, $0, &count) + } + } + guard result == KERN_SUCCESS else { return 0 } + return (Double(vm.free_count) + Double(vm.inactive_count)) * Double(vm_kernel_page_size) + } + + static func check(reserving bytes: Double = 0) throws { + guard let first = cpuTicks() else { throw Busy() } + Thread.sleep(forTimeInterval: 0.12) + guard let last = cpuTicks() else { throw Busy() } + let busy = Double(last.0 &- first.0) + let total = busy + Double(last.1 &- first.1) + let gpu = gpuPercent() + guard permits(cpu: total > 0 ? 100 * busy / total : nil, gpu: gpu, + idle: gpu == nil ? idleSeconds() : 0, available: (availableBytes() - bytes) / Double(ProcessInfo.processInfo.physicalMemory), + thermal: ProcessInfo.processInfo.thermalState, + lowPower: ProcessInfo.processInfo.isLowPowerModeEnabled) else { throw Busy() } + } + + // One advisory lock per user, shared across installations and Quick Look containers. + // Only this empty file needs write access. The kernel releases the lock on exit. + static func withSlot(at file: URL, _ body: () throws -> T) throws -> T { + let fd = open(file.path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) + guard fd >= 0 else { throw Busy() } + defer { close(fd) } + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { throw Busy() } + return try body() + } + + // Estimate working memory before inflation. XML, parsed buffers and the display geometry + // can coexist. Later checkpoints use observed memory so the estimate is not counted twice. + static func estimatedBytes(for url: URL) throws -> Double { + if url.pathExtension.lowercased() == "gcode" { + return Double(try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) * 4 + } + let zip = try ZipArchive(url: url) + let modelBytes = zip.entries.reduce(0.0) { total, entry in + total + (entry.key.lowercased().hasSuffix(".model") ? Double(entry.value.size) : 0) + } + return modelBytes * 3 + } + + static func run(for url: URL, _ body: (_ checkpoint: @escaping () throws -> Void) throws -> T) throws -> T { + let support = PreviewCache.directory.deletingLastPathComponent().deletingLastPathComponent() + let slot = support.appendingPathComponent("com.moraesdev.3dslicerrouter.render-slot") + return try withSlot(at: slot) { + try check(reserving: try estimatedBytes(for: url)) + var next = ProcessInfo.processInfo.systemUptime + 2 + return try body { + if ProcessInfo.processInfo.systemUptime >= next { + try check() + next = ProcessInfo.processInfo.systemUptime + 2 + } + } + } + } +} diff --git a/Sources/Core/PreviewRenderer.swift b/Sources/Core/PreviewRenderer.swift index aa0b7e3..539a412 100644 --- a/Sources/Core/PreviewRenderer.swift +++ b/Sources/Core/PreviewRenderer.swift @@ -30,7 +30,7 @@ public enum PreviewRenderer { } public static func thumbnail(url: URL, info: ThreeMFInfo, size: CGSize, - cacheDirectory: URL = PreviewCache.directory) throws -> CGImage { + cacheDirectory: URL = PreviewCache.directory, checkpoint: @escaping () throws -> Void = {}) throws -> CGImage { if let cached = PreviewCache.cachedURL(for: url, directory: cacheDirectory) .flatMap({ try? Data(contentsOf: $0) }).flatMap(decode) { return cached } let zip = try ZipArchive(url: url) @@ -39,13 +39,17 @@ public enum PreviewRenderer { guard bytes <= maxRenderBytes else { throw RenderError.tooLarge } // Quick Look can retain this result until the next save. Never seed its cache // with an old slicer screenshot when current first-plate geometry can render. - return try render(url: url, info: info, size: size, firstPlateOnly: true) + return try render(url: url, info: info, size: size, firstPlateOnly: true, checkpoint: checkpoint) } catch { if let embedded = info.embeddedThumbnail.flatMap({ try? zip.read($0) }).flatMap(decode) { return embedded } throw error } } + static func cachedImage(_ url: URL) -> CGImage? { + PreviewCache.cachedURL(for: url).flatMap { try? Data(contentsOf: $0) }.flatMap(decode) + } + static func decode(_ data: Data) -> CGImage? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return CGImageSourceCreateImageAtIndex(source, 0, nil) @@ -58,15 +62,19 @@ public enum PreviewRenderer { return png } - public static func render(url: URL, info: ThreeMFInfo, size: CGSize, firstPlateOnly: Bool = false) throws -> CGImage { + public static func render(url: URL, info: ThreeMFInfo, size: CGSize, firstPlateOnly: Bool = false, checkpoint: @escaping () throws -> Void = {}) throws -> CGImage { var label = info if firstPlateOnly { label.plateCount = 1 } - return try render(scene: PrintScene.load(url: url, info: info, firstPlateOnly: firstPlateOnly), info: label, size: size) + let scene = try PrintScene.load(url: url, info: info, firstPlateOnly: firstPlateOnly, checkpoint: checkpoint) + try checkpoint() + return try render(scene: scene, info: label, size: size) } /// Caminho de extrusão de um G-code, no mesmo estilo de mesa. - public static func renderGCode(url: URL, info: ThreeMFInfo, size: CGSize) throws -> CGImage { - try render(scene: GCode.toolpath(url: url, info: info), info: info, size: size) + public static func renderGCode(url: URL, info: ThreeMFInfo, size: CGSize, checkpoint: @escaping () throws -> Void = {}) throws -> CGImage { + let scene = try GCode.toolpath(url: url, info: info, checkpoint: checkpoint) + try checkpoint() + return try render(scene: scene, info: info, size: size) } public static func render(scene: PrintScene, info: ThreeMFInfo, size: CGSize) throws -> CGImage { @@ -79,8 +87,10 @@ public enum PreviewRenderer { return try overlay(shot, size: size, info: info) } - public static func prepare(url: URL, info: ThreeMFInfo, aspect: Float) throws -> Prepared { - try prepare(scene: PrintScene.load(url: url, info: info), aspect: aspect) + public static func prepare(url: URL, info: ThreeMFInfo, aspect: Float, checkpoint: @escaping () throws -> Void = {}) throws -> Prepared { + let scene = try PrintScene.load(url: url, info: info, checkpoint: checkpoint) + try checkpoint() + return prepare(scene: scene, aspect: aspect) } public static func prepare(scene: PrintScene, aspect: Float) -> Prepared { diff --git a/Sources/Core/PrintScene.swift b/Sources/Core/PrintScene.swift index 6b54719..7c568e6 100644 --- a/Sources/Core/PrintScene.swift +++ b/Sources/Core/PrintScene.swift @@ -36,7 +36,7 @@ public struct PrintScene { } } - public static func load(url: URL, info: ThreeMFInfo, firstPlateOnly: Bool = false) throws -> PrintScene { + public static func load(url: URL, info: ThreeMFInfo, firstPlateOnly: Bool = false, checkpoint: @escaping () throws -> Void = {}) throws -> PrintScene { let zip = try ZipArchive(url: url) var scene = PrintScene() scene.beds = bedLayout(count: firstPlateOnly ? 1 : info.plateCount, min: info.bedMin, max: info.bedMax) @@ -44,15 +44,15 @@ public struct PrintScene { let settings = (try? zip.read("Metadata/model_settings.config")).map(ModelSettings.init) ?? ModelSettings() if firstPlateOnly, info.plateCount > 1, settings.plates.isEmpty { throw PrintSceneError.missingFirstPlate } var models: [String: ModelFile] = [:] - func model(_ path: String) -> ModelFile? { + func model(_ path: String) throws -> ModelFile? { if let m = models[path] { return m } guard let data = try? zip.read(path) else { return nil } - let m = ModelFile(data: data) + let m = try ModelFile(data: data, checkpoint: checkpoint) models[path] = m return m } let root = "3D/3dmodel.model" - guard let main = model(root) else { throw ZipError.missing(root) } + guard let main = try model(root) else { throw ZipError.missing(root) } func colour(_ extruder: Int) -> String { let list = info.filamentColours @@ -61,13 +61,15 @@ public struct PrintScene { return c.count >= 7 ? String(c.prefix(7)).uppercased() : "#B8B4AC" } - func emit(path: String, id: String, transform: simd_float4x4, extruder: Int, top: String, depth: Int) { - guard depth < 16, let file = model(path), let object = file.objects[id] else { return } + func emit(path: String, id: String, transform: simd_float4x4, extruder: Int, top: String, depth: Int) throws { + try checkpoint() + guard depth < 16, let file = try model(path), let object = file.objects[id] else { return } if let mesh = object.mesh, !mesh.triangles.isEmpty { let key = colour(extruder) var world: [SIMD3] = [] world.reserveCapacity(mesh.vertices.count) - for v in mesh.vertices { + for (i, v) in mesh.vertices.enumerated() { + if i.isMultiple(of: 8192) { try checkpoint() } let p4 = transform * SIMD4(v, 1) let p = SIMD3(p4.x, p4.y, p4.z) scene.boundsMin = simd_min(scene.boundsMin, p) @@ -85,6 +87,7 @@ public struct PrintScene { var painted: [String: Buffer] = [:] var next = 0 for t in 0..<(mesh.triangles.count / 3) { + if t.isMultiple(of: 4096) { try checkpoint() } let i0 = Int(mesh.triangles[3 * t]), i1 = Int(mesh.triangles[3 * t + 1]), i2 = Int(mesh.triangles[3 * t + 2]) guard next < mesh.paintTriangle.count, mesh.paintTriangle[next] == t else { plain += [UInt32(i0) + base, UInt32(i1) + base, UInt32(i2) + base] @@ -92,11 +95,9 @@ public struct PrintScene { } PaintDecoder.decode(mesh.paintCode[next][...], world[i0], world[i1], world[i2]) { a, b, c, state in let target = state == 0 ? key : colour(state) - var buffer = painted[target, default: Buffer()] - let at = UInt32(buffer.positions.count) - buffer.positions += [a, b, c] - buffer.indices += [at, at + 1, at + 2] - painted[target] = buffer + let at = UInt32(painted[target]?.positions.count ?? 0) + painted[target, default: Buffer()].positions += [a, b, c] + painted[target, default: Buffer()].indices += [at, at + 1, at + 2] } next += 1 } @@ -111,7 +112,7 @@ public struct PrintScene { for c in object.components { let part = settings.parts[top]?[c.objectID] if let subtype = part?.subtype, subtype != "normal_part" { continue } - emit(path: c.path.map(ModelFile.normalize) ?? path, id: c.objectID, + try emit(path: c.path.map(ModelFile.normalize) ?? path, id: c.objectID, transform: transform * c.transform, extruder: part?.extruder ?? extruder, top: top, depth: depth + 1) } @@ -119,7 +120,7 @@ public struct PrintScene { for item in main.build { if firstPlateOnly, let instances = settings.plates.first, !instances.contains(.init(objectID: item.objectID, instanceID: item.instanceID)) { continue } - emit(path: root, id: item.objectID, transform: item.transform, + try emit(path: root, id: item.objectID, transform: item.transform, extruder: settings.objectExtruder[item.objectID] ?? 1, top: item.objectID, depth: 0) } return scene @@ -211,12 +212,17 @@ final class ModelFile: NSObject, XMLParserDelegate { private var current: String? private var mesh: Mesh? private var instanceCounts: [String: Int] = [:] + private let checkpoint: () throws -> Void + private var elements = 0 + private var interruption: Error? - init(data: Data) { + init(data: Data, checkpoint: @escaping () throws -> Void) throws { + self.checkpoint = checkpoint super.init() let parser = XMLParser(data: data) parser.delegate = self parser.parse() + if let interruption { throw interruption } } static func normalize(_ path: String) -> String { @@ -235,14 +241,22 @@ final class ModelFile: NSObject, XMLParserDelegate { func parser(_ p: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, attributes a: [String: String]) { + elements += 1 + if elements.isMultiple(of: 4096) { + do { try checkpoint() } catch { + interruption = error + p.abortParsing() + return + } + } switch name { case "vertex": mesh?.vertices.append(SIMD3(Float(a["x"] ?? "") ?? 0, Float(a["y"] ?? "") ?? 0, Float(a["z"] ?? "") ?? 0)) case "triangle": if let v1 = a["v1"].flatMap(UInt32.init), let v2 = a["v2"].flatMap(UInt32.init), let v3 = a["v3"].flatMap(UInt32.init) { - if let paint = a["paint_color"] ?? a["slic3rpe:mmu_segmentation"], !paint.isEmpty, let m = mesh { - mesh?.paintTriangle.append(m.triangles.count / 3) + if let paint = a["paint_color"] ?? a["slic3rpe:mmu_segmentation"], !paint.isEmpty, let indexCount = mesh?.triangles.count { + mesh?.paintTriangle.append(indexCount / 3) mesh?.paintCode.append(paint) } mesh?.triangles.append(v1) diff --git a/Sources/Indexer/main.swift b/Sources/Indexer/main.swift index 65a412f..84883d5 100644 --- a/Sources/Indexer/main.swift +++ b/Sources/Indexer/main.swift @@ -11,6 +11,10 @@ let deadline = Date().addingTimeInterval(20 * 60) let monitor = DispatchSource.makeTimerSource(queue: .global(qos: .background)) monitor.schedule(deadline: .now() + 5, repeating: 5) monitor.setEventHandler { + do { try PreviewGate.check() } catch { + Indexer.write("parou: recursos ocupados") + exit(0) + } if let reason = Indexer.whyNotNow() { Indexer.write("parou durante preview: \(reason)") exit(0) diff --git a/Sources/Preview/Preview.entitlements b/Sources/Preview/Preview.entitlements index 63396c3..7dc94a8 100644 --- a/Sources/Preview/Preview.entitlements +++ b/Sources/Preview/Preview.entitlements @@ -10,5 +10,9 @@ /Library/Application Support/3dSlicerRouter/ + com.apple.security.temporary-exception.files.home-relative-path.read-write + + /Library/Application Support/com.moraesdev.3dslicerrouter.render-slot + diff --git a/Sources/Preview/PreviewViewController.swift b/Sources/Preview/PreviewViewController.swift index 70164ec..10d6ba4 100644 --- a/Sources/Preview/PreviewViewController.swift +++ b/Sources/Preview/PreviewViewController.swift @@ -11,22 +11,36 @@ final class PreviewViewController: NSViewController, QLPreviewingController { func preparePreviewOfFile(at url: URL, completionHandler handler: @escaping (Error?) -> Void) { let aspect = Float(max(view.bounds.width, 1) / max(view.bounds.height, 1)) - DispatchQueue.global(qos: .userInitiated).async { + DispatchQueue.global(qos: .background).async { do { if url.pathExtension.lowercased() == "gcode" { - let info = try GCode.metadata(url: url).info - let prepared = PreviewRenderer.prepare(scene: try GCode.toolpath(url: url, info: info), aspect: aspect) - DispatchQueue.main.async { self.show(prepared, info: info); handler(nil) } + let meta = try GCode.metadata(url: url) + do { + let prepared = try PreviewGate.run(for: url) { check in + let scene = try GCode.toolpath(url: url, info: meta.info, checkpoint: check) + try check() + return PreviewRenderer.prepare(scene: scene, aspect: aspect) + } + DispatchQueue.main.async { self.show(prepared, info: meta.info); handler(nil) } + } catch is PreviewGate.Busy { + try self.showFallback(url, embedded: meta.thumbnail, handler: handler) + } return } - let info = try ThreeMF.info(url: url) - if info.plateCount > 1 { - // The indexer's cache is intentionally first-plate-only; Space keeps its panorama. - let image = try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1600, height: 1600)) - DispatchQueue.main.async { self.show(image: image); handler(nil) } - } else { - let prepared = try PreviewRenderer.prepare(url: url, info: info, aspect: aspect) - DispatchQueue.main.async { self.show(prepared, info: info); handler(nil) } + let zip = try ZipArchive(url: url) + let info = try ThreeMF.info(zip: zip) + do { + try PreviewGate.run(for: url) { check in + if info.plateCount > 1 { + let image = try PreviewRenderer.render(url: url, info: info, size: CGSize(width: 1600, height: 1600), checkpoint: check) + DispatchQueue.main.async { self.show(image: image); handler(nil) } + } else { + let prepared = try PreviewRenderer.prepare(url: url, info: info, aspect: aspect, checkpoint: check) + DispatchQueue.main.async { self.show(prepared, info: info); handler(nil) } + } + } + } catch is PreviewGate.Busy { + try self.showFallback(url, embedded: info.embeddedThumbnail.flatMap { try? zip.read($0) }, handler: handler) } } catch { DispatchQueue.main.async { handler(error) } @@ -34,6 +48,13 @@ final class PreviewViewController: NSViewController, QLPreviewingController { } } + private func showFallback(_ url: URL, embedded: @autoclosure () -> Data?, handler: @escaping (Error?) -> Void) throws { + guard let image = PreviewRenderer.cachedImage(url) ?? embedded().flatMap(PreviewRenderer.decode) else { + throw PreviewGate.Busy() + } + DispatchQueue.main.async { self.show(image: image); handler(nil) } + } + private func show(image: CGImage) { let imageView = NSImageView(frame: view.bounds) imageView.autoresizingMask = [.width, .height] diff --git a/Sources/Thumbnail/Thumbnail.entitlements b/Sources/Thumbnail/Thumbnail.entitlements index 63396c3..7dc94a8 100644 --- a/Sources/Thumbnail/Thumbnail.entitlements +++ b/Sources/Thumbnail/Thumbnail.entitlements @@ -10,5 +10,9 @@ /Library/Application Support/3dSlicerRouter/ + com.apple.security.temporary-exception.files.home-relative-path.read-write + + /Library/Application Support/com.moraesdev.3dslicerrouter.render-slot + diff --git a/Sources/Thumbnail/ThumbnailProvider.swift b/Sources/Thumbnail/ThumbnailProvider.swift index 2af590c..03ebef9 100644 --- a/Sources/Thumbnail/ThumbnailProvider.swift +++ b/Sources/Thumbnail/ThumbnailProvider.swift @@ -6,6 +6,12 @@ import QuickLookThumbnailing /// - 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) { + DispatchQueue.global(qos: .background).async { + self.reply(to: request, handler) + } + } + + private func reply(to 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) @@ -26,17 +32,32 @@ final class ThumbnailProvider: QLThumbnailProvider { let image: CGImage if url.pathExtension.lowercased() == "gcode" { let meta = try GCode.metadata(url: url) - if let embedded = meta.thumbnail.flatMap(Self.decode) { + if let embedded = meta.thumbnail.flatMap(PreviewRenderer.decode) { image = embedded - } else if let cached = Self.cached(url) { + } else if let cached = PreviewRenderer.cachedImage(url) { image = cached } else { - image = try PreviewRenderer.renderGCode(url: url, info: meta.info, size: CGSize(width: side, height: side)) + image = try PreviewGate.run(for: url) { check in + try PreviewRenderer.renderGCode(url: url, info: meta.info, size: CGSize(width: side, height: side), checkpoint: check) + } } } else { let zip = try ZipArchive(url: url) let info = try ThreeMF.info(zip: zip) - image = try PreviewRenderer.thumbnail(url: url, info: info, size: CGSize(width: side, height: side)) + if let cached = PreviewRenderer.cachedImage(url) { + image = cached + } else { + do { + image = try PreviewGate.run(for: url) { check in + try PreviewRenderer.thumbnail(url: url, info: info, size: CGSize(width: side, height: side), checkpoint: check) + } + } catch is PreviewGate.Busy { + guard let fallback = info.embeddedThumbnail.flatMap({ try? zip.read($0) }).flatMap(PreviewRenderer.decode) else { + throw PreviewGate.Busy() + } + image = fallback + } + } } let ratio = min(box.width / CGFloat(image.width), box.height / CGFloat(image.height)) let size = CGSize(width: CGFloat(image.width) * ratio, height: CGFloat(image.height) * ratio) @@ -50,14 +71,4 @@ final class ThumbnailProvider: QLThumbnailProvider { handler(nil, error) } } - - static func decode(_ data: Data) -> CGImage? { - guard let src = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } - return CGImageSourceCreateImageAtIndex(src, 0, nil) - } - - static func cached(_ url: URL) -> CGImage? { - PreviewCache.cachedURL(for: url).flatMap { try? Data(contentsOf: $0) }.flatMap(decode) - } - } diff --git a/Tests/PreviewGateTests.swift b/Tests/PreviewGateTests.swift new file mode 100644 index 0000000..e99cc96 --- /dev/null +++ b/Tests/PreviewGateTests.swift @@ -0,0 +1,39 @@ +import Foundation +import XCTest + +final class PreviewGateTests: XCTestCase { + func testAdmissionBoundaries() { + func permits(_ cpu: Double?, _ gpu: Double?, idle: Double = 0, available: Double = 0.25, + thermal: ProcessInfo.ThermalState = .nominal, lowPower: Bool = false) -> Bool { + PreviewGate.permits(cpu: cpu, gpu: gpu, idle: idle, available: available, thermal: thermal, lowPower: lowPower) + } + XCTAssertTrue(permits(29.9, 29.9)) + XCTAssertFalse(permits(30, 0, idle: 3600)) + XCTAssertFalse(permits(0, 30, idle: 3600)) + XCTAssertFalse(permits(nil, 0, idle: 3600)) + XCTAssertFalse(permits(0, nil, idle: 179)) + XCTAssertTrue(permits(0, nil, idle: 180)) + XCTAssertFalse(permits(0, 0, available: 0.249)) + XCTAssertFalse(permits(0, 0, thermal: .serious)) + XCTAssertFalse(permits(0, 0, lowPower: true)) + } + + func testSlotRejectsOverlapAndReleasesAfterInterruption() throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try Data().write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + XCTAssertThrowsError(try PreviewGate.withSlot(at: file) { + XCTAssertThrowsError(try PreviewGate.withSlot(at: file) { XCTFail("Overlapping render") }) + throw PreviewGate.Busy() + }) + XCTAssertEqual(try PreviewGate.withSlot(at: file) { 42 }, 42) + } + + func testMeshParserPropagatesInterruption() { + let vertices = String(repeating: "", count: 8192) + let data = Data("\(vertices)".utf8) + XCTAssertThrowsError(try ModelFile(data: data) { throw PreviewGate.Busy() }) { + XCTAssertTrue($0 is PreviewGate.Busy) + } + } +} diff --git a/Tests/RouterTests.swift b/Tests/RouterTests.swift index c5ef0f9..c26fd9b 100644 --- a/Tests/RouterTests.swift +++ b/Tests/RouterTests.swift @@ -524,7 +524,8 @@ final class RouterTests: XCTestCase { try withArchive(files: files) { url in let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) let result = Indexer.index(url, size: try XCTUnwrap(values.fileSize), modified: try XCTUnwrap(values.contentModificationDate), - cacheDirectory: url.deletingLastPathComponent().appendingPathComponent("previews")) + cacheDirectory: url.deletingLastPathComponent().appendingPathComponent("previews"), + admit: { _, render in try render({}) }) XCTAssertNil(result.error) XCTAssertTrue(result.embedded) XCTAssertTrue(result.rendered, "The idle pass must regenerate current geometry even if the slicer image is old") @@ -533,6 +534,19 @@ final class RouterTests: XCTestCase { } } + func testIndexerDefersWithoutCachingPartialGeometry() throws { + let files = sceneFiles(build: #""#, settings: "") + try withArchive(files: files) { url in + let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) + let cache = url.deletingLastPathComponent().appendingPathComponent("previews") + let entry = Indexer.index(url, size: try XCTUnwrap(values.fileSize), modified: try XCTUnwrap(values.contentModificationDate), + cacheDirectory: cache, admit: { _, _ in throw PreviewGate.Busy() }) + XCTAssertTrue(entry.deferred) + XCTAssertNil(entry.error) + XCTAssertNil(PreviewCache.cachedURL(for: url, directory: cache)) + } + } + func testIndexerRejectsSaveWhileReadingSourceMetadata() throws { let original = sceneFiles(build: #""#, settings: "") var changed = original @@ -542,12 +556,12 @@ final class RouterTests: XCTestCase { let values = try url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) let cache = url.deletingLastPathComponent().appendingPathComponent("previews") let entry = Indexer.index(url, size: try XCTUnwrap(values.fileSize), - modified: try XCTUnwrap(values.contentModificationDate), cacheDirectory: cache) { source in + modified: try XCTUnwrap(values.contentModificationDate), cacheDirectory: cache, readInfo: { source in let oldInfo = try ThreeMF.info(url: source) try Data(contentsOf: replacement).write(to: source, options: .atomic) try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSince1970: 1_800_000_000)], ofItemAtPath: source.path) return oldInfo - } + }) XCTAssertEqual(entry.error, "changedDuringRender") XCTAssertFalse(entry.rendered) XCTAssertNil(PreviewCache.cachedURL(for: url, directory: cache)) diff --git a/project.yml b/project.yml index bbb296f..9a119e6 100644 --- a/project.yml +++ b/project.yml @@ -116,6 +116,8 @@ targets: com.apple.security.files.user-selected.read-only: true com.apple.security.temporary-exception.files.home-relative-path.read-only: - /Library/Application Support/3dSlicerRouter/ + com.apple.security.temporary-exception.files.home-relative-path.read-write: + - /Library/Application Support/com.moraesdev.3dslicerrouter.render-slot settings: base: PRODUCT_BUNDLE_IDENTIFIER: com.moraesdev.3dslicerrouter.thumbnail @@ -147,6 +149,8 @@ targets: com.apple.security.files.user-selected.read-only: true com.apple.security.temporary-exception.files.home-relative-path.read-only: - /Library/Application Support/3dSlicerRouter/ + com.apple.security.temporary-exception.files.home-relative-path.read-write: + - /Library/Application Support/com.moraesdev.3dslicerrouter.render-slot settings: base: PRODUCT_BUNDLE_IDENTIFIER: com.moraesdev.3dslicerrouter.preview