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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
34 changes: 19 additions & 15 deletions Sources/App/Indexer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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 }
Expand All @@ -89,13 +81,21 @@ 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
continue
}
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 }
}
Expand All @@ -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?
}

Expand All @@ -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) {
Expand All @@ -131,21 +133,21 @@ 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)
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
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
Expand All @@ -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)"
}
Expand Down
9 changes: 7 additions & 2 deletions Sources/Core/GCode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -76,11 +76,16 @@ public enum GCode {
var segments: [Int: [SIMD3<Float>]] = [:]
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 }
Expand Down
120 changes: 120 additions & 0 deletions Sources/Core/PreviewGate.swift
Original file line number Diff line number Diff line change
@@ -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<integer_t>.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<integer_t>.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<T>(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<T>(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
}
}
}
}
}
Loading
Loading