mirror of
https://github.com/bitsycore/Allofit.git
synced 2026-10-07 05:17:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc386bef67 | ||
|
|
c8ba0a735c | ||
|
|
1a1235e215 |
+2
-1
@@ -10,8 +10,9 @@ xcuserdata/
|
|||||||
DerivedData/
|
DerivedData/
|
||||||
*.xcuserstate
|
*.xcuserstate
|
||||||
|
|
||||||
# Build output produced by ./build-app.sh
|
# Build output produced by ./build-app.sh and ./build-dmg.sh
|
||||||
Allofit.app/
|
Allofit.app/
|
||||||
|
*.dmg
|
||||||
|
|
||||||
# Service log files (also live in /tmp but local copies happen during dev)
|
# Service log files (also live in /tmp but local copies happen during dev)
|
||||||
allofit-service.log
|
allofit-service.log
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import Foundation
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
// AccessManager holds the in-memory mapping from FileRecord.ID to the
|
||||||
|
// staged user-readable copy produced by an "Authorize" tap. Both the
|
||||||
|
// Table (which shows a lock badge on the selected row when the preview
|
||||||
|
// pane is closed) and the PreviewPane (which gates the QLPreviewView
|
||||||
|
// behind the same badge) observe this so the badge disappears and the
|
||||||
|
// preview switches to the staged URL as soon as the sudo copy lands.
|
||||||
|
//
|
||||||
|
// All published mutations happen on the main actor; the actual sudo cp
|
||||||
|
// runs inside a Task.detached spawned by `authorize(_:)` so the AppleScript
|
||||||
|
// password prompt doesn't block the main runloop.
|
||||||
|
@MainActor
|
||||||
|
final class AccessManager: ObservableObject {
|
||||||
|
|
||||||
|
// id -> URL of the user-readable copy in ~/Library/Caches/Allofit/elevated
|
||||||
|
@Published private(set) var stagedURLs: [FileRecord.ID: URL] = [:]
|
||||||
|
// ids currently being authorized (admin script in flight); used to
|
||||||
|
// render a small spinner inside the lock badge
|
||||||
|
@Published private(set) var authorizingIds: Set<FileRecord.ID> = []
|
||||||
|
// most recent authorization error (cancelled prompt, sudo failure,
|
||||||
|
// etc); surfaced as the badge's accessibility / tooltip text
|
||||||
|
@Published private(set) var lastError: String?
|
||||||
|
|
||||||
|
// returns the URL to use when previewing / opening the file: the
|
||||||
|
// staged copy if we have one, otherwise the original path
|
||||||
|
func effectiveURL(for inRecord: FileRecord) -> URL {
|
||||||
|
if let vStaged = stagedURLs[inRecord.id] {
|
||||||
|
return vStaged
|
||||||
|
}
|
||||||
|
return URL(fileURLWithPath: inRecord.fullPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// true if the effective URL (staged or original) isn't readable by
|
||||||
|
// the current user - this is what drives the lock-badge visibility
|
||||||
|
func needsAuthorization(for inRecord: FileRecord) -> Bool {
|
||||||
|
let vUrl = effectiveURL(for: inRecord)
|
||||||
|
return !ElevatedAccess.canRead(path: vUrl.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// true while an authorize task is in flight for the given record id
|
||||||
|
func isAuthorizing(_ inId: FileRecord.ID) -> Bool {
|
||||||
|
return authorizingIds.contains(inId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// runs the sudo cp + chown flow for one record. The first call inside
|
||||||
|
// the system's admin-auth-cache window (~5 min) prompts for the
|
||||||
|
// password; subsequent calls within that window are silent.
|
||||||
|
func authorize(_ inRecord: FileRecord) async {
|
||||||
|
let vId = inRecord.id
|
||||||
|
// idempotency: a double-tap on the badge shouldn't kick off two
|
||||||
|
// concurrent admin scripts for the same file
|
||||||
|
guard !authorizingIds.contains(vId) else { return }
|
||||||
|
authorizingIds.insert(vId)
|
||||||
|
lastError = nil
|
||||||
|
let vOriginalUrl = URL(fileURLWithPath: inRecord.fullPath)
|
||||||
|
do {
|
||||||
|
// Task.detached so the synchronous NSAppleScript admin prompt
|
||||||
|
// runs on a background thread; the prompt itself is shown on
|
||||||
|
// main by AppKit regardless of where we invoke it from
|
||||||
|
let vStaged = try await Task.detached(priority: .userInitiated) {
|
||||||
|
try ElevatedAccess.stage(vOriginalUrl)
|
||||||
|
}.value
|
||||||
|
stagedURLs[vId] = vStaged
|
||||||
|
} catch {
|
||||||
|
lastError = error.localizedDescription
|
||||||
|
}
|
||||||
|
authorizingIds.remove(vId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// wipes the in-memory mapping. Called after ElevatedAccess.cleanup()
|
||||||
|
// removes the on-disk files so the two stay consistent.
|
||||||
|
func reset() {
|
||||||
|
stagedURLs.removeAll()
|
||||||
|
authorizingIds.removeAll()
|
||||||
|
lastError = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import Foundation
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
// AdminShell runs short shell commands with administrator privileges by
|
||||||
|
// wrapping them in `do shell script ... with administrator privileges`
|
||||||
|
// via NSAppleScript. The system shows its native password prompt the
|
||||||
|
// first time within a session; subsequent calls inside the auth-cache
|
||||||
|
// window (about 5 minutes) re-use the credential without re-prompting.
|
||||||
|
//
|
||||||
|
// Used by both ServiceInstaller (LaunchDaemon install/uninstall and
|
||||||
|
// cache-clear-and-restart) and ElevatedAccess (sudo cp of a single
|
||||||
|
// unreadable file into the per-user staging cache).
|
||||||
|
enum AdminShell {
|
||||||
|
|
||||||
|
// surfaces an AppleScript failure - typically the user clicked
|
||||||
|
// Cancel on the password prompt, or the embedded shell command
|
||||||
|
// returned a non-zero exit code
|
||||||
|
enum Error: Swift.Error, LocalizedError {
|
||||||
|
case scriptFailed(String)
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .scriptFailed(let vMsg): return vMsg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runs inScript as root via NSAppleScript. Returns the script's
|
||||||
|
// stdout. Throws Error.scriptFailed if NSAppleScript reports an
|
||||||
|
// error (cancelled prompt, non-zero shell exit, etc).
|
||||||
|
@discardableResult
|
||||||
|
static func run(_ inScript: String) throws -> String {
|
||||||
|
// AppleScript string literal needs backslashes and double quotes
|
||||||
|
// escaped before we embed the shell command
|
||||||
|
let vEscaped = inScript
|
||||||
|
.replacingOccurrences(of: "\\", with: "\\\\")
|
||||||
|
.replacingOccurrences(of: "\"", with: "\\\"")
|
||||||
|
let vSource = "do shell script \"\(vEscaped)\" with administrator privileges"
|
||||||
|
let vAppleScript = NSAppleScript(source: vSource)
|
||||||
|
var vErr: NSDictionary?
|
||||||
|
let vResult = vAppleScript?.executeAndReturnError(&vErr)
|
||||||
|
guard let vDescriptor = vResult else {
|
||||||
|
let vMessage = vErr?[NSAppleScript.errorMessage] as? String
|
||||||
|
?? "Authorization cancelled or failed"
|
||||||
|
throw Error.scriptFailed(vMessage)
|
||||||
|
}
|
||||||
|
return vDescriptor.stringValue ?? ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// POSIX-style single-quote escape so a string can be safely embedded
|
||||||
|
// inside the inScript argument of run(_:). Each embedded single
|
||||||
|
// quote becomes the escape sequence '\''. Use for any user-supplied
|
||||||
|
// path or argument; literal command names should not be quoted.
|
||||||
|
static func quote(_ inString: String) -> String {
|
||||||
|
return "'" + inString.replacingOccurrences(of: "'", with: "'\\''") + "'"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,16 +10,22 @@ struct AllofitApp: App {
|
|||||||
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
|
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
|
||||||
// shared application state injected into the view tree
|
// shared application state injected into the view tree
|
||||||
@StateObject private var model = AppModel()
|
@StateObject private var model = AppModel()
|
||||||
|
// session-scoped store of sudo-staged user-readable copies. Sits
|
||||||
|
// alongside AppModel so both the Table (lock badge on rows) and
|
||||||
|
// the PreviewPane observe the same authorization state.
|
||||||
|
@StateObject private var access = AccessManager()
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup("Allofit") {
|
WindowGroup("Allofit") {
|
||||||
ContentView()
|
ContentView()
|
||||||
.environmentObject(model)
|
.environmentObject(model)
|
||||||
.environmentObject(Preferences.shared)
|
.environmentObject(Preferences.shared)
|
||||||
|
.environmentObject(access)
|
||||||
.frame(minWidth: 760, minHeight: 480)
|
.frame(minWidth: 760, minHeight: 480)
|
||||||
.background(MainWindowMarker())
|
.background(MainWindowMarker())
|
||||||
}
|
}
|
||||||
.windowToolbarStyle(.unified)
|
.windowToolbarStyle(.unified)
|
||||||
|
.defaultSize(width: 1100, height: 640)
|
||||||
.commands {
|
.commands {
|
||||||
// custom About panel with a clickable repo link in the credits
|
// custom About panel with a clickable repo link in the credits
|
||||||
CommandGroup(replacing: .appInfo) {
|
CommandGroup(replacing: .appInfo) {
|
||||||
@@ -46,6 +52,7 @@ struct AllofitApp: App {
|
|||||||
SettingsView()
|
SettingsView()
|
||||||
.environmentObject(model)
|
.environmentObject(model)
|
||||||
.environmentObject(Preferences.shared)
|
.environmentObject(Preferences.shared)
|
||||||
|
.environmentObject(access)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,6 +133,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
// bundle - covers the SwiftPM "swift run" case
|
// bundle - covers the SwiftPM "swift run" case
|
||||||
NSApp.setActivationPolicy(.regular)
|
NSApp.setActivationPolicy(.regular)
|
||||||
NSApp.activate(ignoringOtherApps: true)
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
// wipe any elevated-access staging files left over from a previous
|
||||||
|
// run so a crash or hard-kill doesn't accumulate privileged copies
|
||||||
|
// in ~/Library/Caches across sessions
|
||||||
|
ElevatedAccess.cleanup()
|
||||||
// bring the main window to the front so it accepts keystrokes
|
// bring the main window to the front so it accepts keystrokes
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
for vWindow in NSApp.windows where vWindow.canBecomeKey {
|
for vWindow in NSApp.windows where vWindow.canBecomeKey {
|
||||||
@@ -136,6 +147,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// called on clean Cmd+Q quit; wipes the elevated-access staging dir
|
||||||
|
// so the user-readable copies of privileged files don't linger
|
||||||
|
func applicationWillTerminate(_ notification: Notification) {
|
||||||
|
ElevatedAccess.cleanup()
|
||||||
|
}
|
||||||
|
|
||||||
// keep the process alive when the user closes the last window: the index
|
// keep the process alive when the user closes the last window: the index
|
||||||
// stays in RAM and clicking the dock icon snaps a new window up instantly.
|
// stays in RAM and clicking the dock icon snaps a new window up instantly.
|
||||||
// Cmd+Q still quits via the standard Quit menu item.
|
// Cmd+Q still quits via the standard Quit menu item.
|
||||||
|
|||||||
@@ -2,6 +2,27 @@ import Foundation
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import CoreServices
|
import CoreServices
|
||||||
|
|
||||||
|
// Background-thread-safe last-seen-mtime cell for the cache-file poll.
|
||||||
|
// Lets the DispatchSource timer compare a new stat() result against the
|
||||||
|
// previously seen value without touching any @MainActor state, so the
|
||||||
|
// poll only hops to main when the cache has actually changed on disk.
|
||||||
|
private final class BackgroundMtime: @unchecked Sendable {
|
||||||
|
private var mtime: Date?
|
||||||
|
private let lock = NSLock()
|
||||||
|
|
||||||
|
// returns true if the supplied mtime differs from the stored value
|
||||||
|
// (and updates the stored value), false otherwise
|
||||||
|
func updateIfChanged(_ inMtime: Date) -> Bool {
|
||||||
|
lock.lock()
|
||||||
|
defer { lock.unlock() }
|
||||||
|
if mtime != inMtime {
|
||||||
|
mtime = inMtime
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// AppModel is the central observable state for the application.
|
// AppModel is the central observable state for the application.
|
||||||
// It owns the in-memory file index, drives the background indexer and the
|
// It owns the in-memory file index, drives the background indexer and the
|
||||||
// FSEvents watcher, debounces the search query and exposes a filtered/sorted
|
// FSEvents watcher, debounces the search query and exposes a filtered/sorted
|
||||||
@@ -80,8 +101,11 @@ final class AppModel: ObservableObject {
|
|||||||
// last user-facing status string for the Settings buttons
|
// last user-facing status string for the Settings buttons
|
||||||
@Published private(set) var workMessage: String = ""
|
@Published private(set) var workMessage: String = ""
|
||||||
// polling backup for reader-mode cache changes; FSEvents alone can miss
|
// polling backup for reader-mode cache changes; FSEvents alone can miss
|
||||||
// updates if the watched directory didn't exist when the stream started
|
// updates if the watched directory didn't exist when the stream started.
|
||||||
private var cachePollTimer: Timer?
|
// Uses DispatchSourceTimer on a background queue (not Timer on the main
|
||||||
|
// runloop) so the periodic stat() doesn't compete with NSTableView click
|
||||||
|
// handling - main-runloop timers were the source of dropped clicks.
|
||||||
|
private var cachePollSource: DispatchSourceTimer?
|
||||||
// last mtime we observed on the cache file - skips needless reloads
|
// last mtime we observed on the cache file - skips needless reloads
|
||||||
private var lastSeenCacheMtime: Date?
|
private var lastSeenCacheMtime: Date?
|
||||||
// minimum gap between two reader-mode reloads. Prevents the Table from
|
// minimum gap between two reader-mode reloads. Prevents the Table from
|
||||||
@@ -124,8 +148,8 @@ final class AppModel: ObservableObject {
|
|||||||
cacheWatcher.stop()
|
cacheWatcher.stop()
|
||||||
autosaveTimer?.invalidate()
|
autosaveTimer?.invalidate()
|
||||||
autosaveTimer = nil
|
autosaveTimer = nil
|
||||||
cachePollTimer?.invalidate()
|
cachePollSource?.cancel()
|
||||||
cachePollTimer = nil
|
cachePollSource = nil
|
||||||
indexerLock?.unlock()
|
indexerLock?.unlock()
|
||||||
indexerLock = nil
|
indexerLock = nil
|
||||||
filterTask?.cancel()
|
filterTask?.cancel()
|
||||||
@@ -482,29 +506,41 @@ final class AppModel: ObservableObject {
|
|||||||
let vDir = vUrl.deletingLastPathComponent().path
|
let vDir = vUrl.deletingLastPathComponent().path
|
||||||
let vTarget = vUrl.path
|
let vTarget = vUrl.path
|
||||||
NSLog("[Allofit GUI] reader mode: watching cache at %@", vTarget)
|
NSLog("[Allofit GUI] reader mode: watching cache at %@", vTarget)
|
||||||
// FSEvents-based watcher for low-latency updates
|
// FSEvents-based watcher for low-latency updates. We watch the
|
||||||
|
// parent dir (FSEvents needs a real path) but only fire the reload
|
||||||
|
// when the cache file itself changed - other files in the dir
|
||||||
|
// (indexer.lock, .tmp atomic-rename leftovers, etc.) used to also
|
||||||
|
// trigger main.async hops, which contributed to dropped clicks.
|
||||||
cacheWatcher.start(inRoots: [vDir]) { vChanges in
|
cacheWatcher.start(inRoots: [vDir]) { vChanges in
|
||||||
if vChanges.contains(where: { $0.path == vTarget || $0.path == vDir }) {
|
let vCacheChanged = vChanges.contains(where: { $0.path == vTarget })
|
||||||
|
guard vCacheChanged else { return }
|
||||||
NSLog("[Allofit GUI] cache file changed (FSEvents), reloading")
|
NSLog("[Allofit GUI] cache file changed (FSEvents), reloading")
|
||||||
DispatchQueue.main.async { [weak self] in
|
DispatchQueue.main.async { [weak self] in
|
||||||
self?.reloadFromCache()
|
self?.reloadFromCache()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Background-queue polling backup at 2s. The stat() runs off main,
|
||||||
|
// and a lock-guarded background-side mtime tracker means we ONLY
|
||||||
|
// hop to main when the cache actually changed - the steady state
|
||||||
|
// puts zero work on the main runloop, leaving NSTableView's click
|
||||||
|
// handling uninterrupted.
|
||||||
|
cachePollSource?.cancel()
|
||||||
|
let vPolledPath = vUrl.path
|
||||||
|
let vBgMtime = BackgroundMtime() // captured by the closure
|
||||||
|
let vSource = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .utility))
|
||||||
|
vSource.schedule(deadline: .now() + 2.0, repeating: 2.0)
|
||||||
|
vSource.setEventHandler { [weak self] in
|
||||||
|
guard let vAttrs = try? FileManager.default.attributesOfItem(atPath: vPolledPath),
|
||||||
|
let vMtime = vAttrs[.modificationDate] as? Date
|
||||||
|
else { return }
|
||||||
|
// Background-side change detection; only proceeds when mtime moved
|
||||||
|
guard vBgMtime.updateIfChanged(vMtime) else { return }
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self?.reloadFromCache()
|
||||||
}
|
}
|
||||||
// Polling backup at 2s intervals. FSEvents can silently no-op when
|
|
||||||
// the watched dir didn't exist at stream creation, or under sandbox
|
|
||||||
// restrictions. The stat() is cheap; reload only fires on mtime change.
|
|
||||||
// Register on .common runloop mode so the timer keeps firing even
|
|
||||||
// when SwiftUI is mid-update or the user is interacting with the
|
|
||||||
// Table - the previous .default mode paused during those windows.
|
|
||||||
cachePollTimer?.invalidate()
|
|
||||||
let vTimer = Timer(timeInterval: 2.0, repeats: true) { [weak self] _ in
|
|
||||||
// Timer closures aren't statically @MainActor; the runtime
|
|
||||||
// invokes them on whatever runloop hosts the timer (here, main)
|
|
||||||
Task { @MainActor in self?.pollCacheForChanges() }
|
|
||||||
}
|
}
|
||||||
RunLoop.main.add(vTimer, forMode: .common)
|
vSource.resume()
|
||||||
cachePollTimer = vTimer
|
cachePollSource = vSource
|
||||||
}
|
}
|
||||||
|
|
||||||
// stat()'s the cache file and triggers a reload when mtime changes
|
// stat()'s the cache file and triggers a reload when mtime changes
|
||||||
@@ -626,7 +662,14 @@ final class AppModel: ObservableObject {
|
|||||||
// on the next runloop tick, avoiding NSTableView reentrance when
|
// on the next runloop tick, avoiding NSTableView reentrance when
|
||||||
// the search field is mid-edit
|
// the search field is mid-edit
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self?.visibleRecords = vCapped
|
guard let vSelf = self else { return }
|
||||||
|
// Skip the @Published fire when the resulting list is byte-
|
||||||
|
// for-byte identical to what the Table is already showing.
|
||||||
|
// Full FileRecord equality catches mtime / size updates, so
|
||||||
|
// we only skip true no-op reassignments. Clicks landing on
|
||||||
|
// the Table during a no-op reload no longer get dropped.
|
||||||
|
if vSelf.visibleRecords == vCapped { return }
|
||||||
|
vSelf.visibleRecords = vCapped
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+237
-127
@@ -1,47 +1,133 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import AppKit
|
import AppKit
|
||||||
import UniformTypeIdentifiers
|
|
||||||
|
|
||||||
// ContentView is the main window layout: search bar at the top, a results
|
// ContentView is the main window layout: a search bar bonded to the title
|
||||||
// table that mirrors the look of Everything, and a status bar at the bottom.
|
// bar via `.background(.bar)` (Liquid Glass on macOS 26, vibrant material
|
||||||
|
// on macOS 15), a results table on the left, a Quick Look preview pane on
|
||||||
|
// the right (toggleable via the toolbar), and a status bar at the bottom.
|
||||||
struct ContentView: View {
|
struct ContentView: View {
|
||||||
|
|
||||||
@EnvironmentObject var model: AppModel
|
@EnvironmentObject var model: AppModel
|
||||||
@EnvironmentObject var prefs: Preferences
|
@EnvironmentObject var prefs: Preferences
|
||||||
|
@EnvironmentObject var access: AccessManager
|
||||||
@State private var selection: Set<FileRecord.ID> = []
|
@State private var selection: Set<FileRecord.ID> = []
|
||||||
// SwiftUI Table sort order - clicking a column header updates this
|
// drives the Table's drag-to-reorder and column-visibility customization.
|
||||||
@State private var sortOrder: [KeyPathComparator<FileRecord>] = [
|
// Initial value is hydrated from UserDefaults so the user's column order
|
||||||
KeyPathComparator(\FileRecord.name, order: .forward)
|
// survives app launches; subsequent changes flow back via .onChange.
|
||||||
]
|
@State private var columnCustomization: TableColumnCustomization<FileRecord> = ContentView.loadColumnCustomization()
|
||||||
|
// debounced background save task for columnCustomization changes.
|
||||||
|
// Cancelled+rescheduled per change so a drag (which fires onChange on
|
||||||
|
// every micro-update) only runs JSONEncoder once, off-main.
|
||||||
|
@State private var columnSaveTask: Task<Void, Never>?
|
||||||
|
// whether the right-hand preview pane is currently visible. Persisted
|
||||||
|
// across launches so the user's pane-visibility preference sticks.
|
||||||
|
@AppStorage("Allofit.showPreviewPane") private var showPreviewPane: Bool = true
|
||||||
|
|
||||||
|
private nonisolated static let kColumnCustomizationKey = "Allofit.columnCustomization"
|
||||||
|
private nonisolated static let kColumnSaveDebounceNanos: UInt64 = 300_000_000
|
||||||
|
|
||||||
|
// Computed binding for the Table's sortOrder: reads/writes
|
||||||
|
// model.sortDescriptor directly so the sort state survives any number
|
||||||
|
// of window closes / reopens.
|
||||||
|
private var sortOrderBinding: Binding<[KeyPathComparator<FileRecord>]> {
|
||||||
|
Binding(
|
||||||
|
get: { [Self.comparatorFor(inDescriptor: model.sortDescriptor)] },
|
||||||
|
set: { vNewOrder in
|
||||||
|
guard let vFirst = vNewOrder.first else { return }
|
||||||
|
let vDescriptor = Self.mapSortOrder(inComparator: vFirst)
|
||||||
|
// defer one runloop tick so we don't write back into the
|
||||||
|
// model while NSTableView is still in its sort delegate
|
||||||
|
// callback (avoids the reentrant-operation AppKit warning)
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
model.sortDescriptor = vDescriptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 0) {
|
Group {
|
||||||
searchBar
|
if showPreviewPane {
|
||||||
Divider()
|
HSplitView {
|
||||||
resultsTable
|
mainColumn
|
||||||
Divider()
|
.layoutPriority(1)
|
||||||
statusBar
|
.frame(minWidth: 460)
|
||||||
|
PreviewPane(selection: selection)
|
||||||
|
.frame(minWidth: 200, idealWidth: 360)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mainColumn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .primaryAction) {
|
||||||
|
Button {
|
||||||
|
showPreviewPane.toggle()
|
||||||
|
} label: {
|
||||||
|
Image(systemName: showPreviewPane
|
||||||
|
? "sidebar.right"
|
||||||
|
: "sidebar.squares.right")
|
||||||
|
}
|
||||||
|
.help(showPreviewPane ? "Hide preview" : "Show preview")
|
||||||
|
}
|
||||||
|
ToolbarItem(placement: .primaryAction) {
|
||||||
|
SettingsLink {
|
||||||
|
Image(systemName: "gearshape")
|
||||||
|
}
|
||||||
|
.help("Preferences (⌘,)")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.onAppear {
|
.onAppear {
|
||||||
// align Table sort order with the persisted sort descriptor
|
|
||||||
sortOrder = [Self.comparatorFor(inDescriptor: model.sortDescriptor)]
|
|
||||||
model.start()
|
model.start()
|
||||||
}
|
}
|
||||||
.onDisappear {
|
.onDisappear {
|
||||||
model.saveCache()
|
model.saveCache()
|
||||||
}
|
}
|
||||||
.onChange(of: sortOrder) { _, vNew in
|
.onChange(of: columnCustomization) { _, vNew in
|
||||||
if let vFirst = vNew.first {
|
// Debounced + off-main save. SwiftUI fires onChange on every
|
||||||
// defer to the next runloop tick so we don't write back into
|
// micro-update during a column drag - encoding synchronously
|
||||||
// the model while NSTableView is still in its sort delegate
|
// on main here would freeze the drag delegate. Cancel any
|
||||||
// callback - that triggers the "reentrant operation in its
|
// pending task and reschedule so we encode at most once per
|
||||||
// NSTableView delegate" warning from AppKit
|
// drag (300 ms after the user lets go).
|
||||||
let vDescriptor = Self.mapSortOrder(inComparator: vFirst)
|
columnSaveTask?.cancel()
|
||||||
DispatchQueue.main.async {
|
columnSaveTask = Task.detached(priority: .utility) {
|
||||||
model.sortDescriptor = vDescriptor
|
try? await Task.sleep(nanoseconds: Self.kColumnSaveDebounceNanos)
|
||||||
|
if Task.isCancelled { return }
|
||||||
|
ContentView.saveColumnCustomization(vNew)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// search bar + table + status bar - everything except the preview pane
|
||||||
|
private var mainColumn: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
searchBar
|
||||||
|
resultsTable
|
||||||
|
Divider()
|
||||||
|
StatusBarView() // isolated so its @Published refresh
|
||||||
|
// doesn't re-evaluate the Table closure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===========================
|
||||||
|
// MARK: Column customization persistence
|
||||||
|
// ===========================
|
||||||
|
|
||||||
|
private static func loadColumnCustomization() -> TableColumnCustomization<FileRecord> {
|
||||||
|
guard let vData = UserDefaults.standard.data(forKey: kColumnCustomizationKey),
|
||||||
|
let vCustom = try? JSONDecoder().decode(
|
||||||
|
TableColumnCustomization<FileRecord>.self,
|
||||||
|
from: vData
|
||||||
|
)
|
||||||
|
else {
|
||||||
|
return TableColumnCustomization<FileRecord>()
|
||||||
|
}
|
||||||
|
return vCustom
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated static func saveColumnCustomization(_ inValue: TableColumnCustomization<FileRecord>) {
|
||||||
|
guard let vData = try? JSONEncoder().encode(inValue) else { return }
|
||||||
|
UserDefaults.standard.set(vData, forKey: kColumnCustomizationKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===========================
|
// ===========================
|
||||||
@@ -49,21 +135,15 @@ struct ContentView: View {
|
|||||||
// ===========================
|
// ===========================
|
||||||
|
|
||||||
private var searchBar: some View {
|
private var searchBar: some View {
|
||||||
HStack(spacing: 8) {
|
|
||||||
SearchField(
|
SearchField(
|
||||||
text: $model.query,
|
text: $model.query,
|
||||||
placeholder: "Search files… e.g. Start*.pdf · *.png | *.jpg",
|
placeholder: "Search files… e.g. Start*.pdf · *.png | *.jpg",
|
||||||
initiallyFirstResponder: true
|
initiallyFirstResponder: true
|
||||||
)
|
)
|
||||||
.frame(minHeight: 28)
|
.frame(minHeight: 24)
|
||||||
|
|
||||||
SettingsLink {
|
|
||||||
Image(systemName: "gearshape")
|
|
||||||
}
|
|
||||||
.help("Preferences (⌘,)")
|
|
||||||
}
|
|
||||||
.padding(.horizontal, 12)
|
.padding(.horizontal, 12)
|
||||||
.padding(.vertical, 8)
|
.padding(.vertical, 8)
|
||||||
|
.background(.bar)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===========================
|
// ===========================
|
||||||
@@ -71,7 +151,15 @@ struct ContentView: View {
|
|||||||
// ===========================
|
// ===========================
|
||||||
|
|
||||||
private var resultsTable: some View {
|
private var resultsTable: some View {
|
||||||
Table(model.visibleRecords, selection: $selection, sortOrder: $sortOrder) {
|
// Uses the explicit `rows:` form of Table so `.draggable` lives on
|
||||||
|
// TableRow rather than embedded in cell content. Cell-content
|
||||||
|
// draggable installs a SwiftUI drag-gesture recognizer that races
|
||||||
|
// with NSTableView's mouseDown→selection event on macOS 26 and
|
||||||
|
// occasionally eats left-clicks; row-level draggable doesn't.
|
||||||
|
Table(of: FileRecord.self,
|
||||||
|
selection: $selection,
|
||||||
|
sortOrder: sortOrderBinding,
|
||||||
|
columnCustomization: $columnCustomization) {
|
||||||
TableColumn("Name", value: \FileRecord.name) { vRecord in
|
TableColumn("Name", value: \FileRecord.name) { vRecord in
|
||||||
HStack(spacing: 6) {
|
HStack(spacing: 6) {
|
||||||
Image(nsImage: IconCache.icon(
|
Image(nsImage: IconCache.icon(
|
||||||
@@ -82,10 +170,23 @@ struct ContentView: View {
|
|||||||
.frame(width: 16, height: 16)
|
.frame(width: 16, height: 16)
|
||||||
Text(vRecord.name)
|
Text(vRecord.name)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
|
// When the preview pane is closed, surface the
|
||||||
|
// elevate-permission affordance on the selected row
|
||||||
|
// itself so the user has a way to authorize without
|
||||||
|
// having to open the pane first. needsAuthorization
|
||||||
|
// is a stat() call so we only invoke it for the row
|
||||||
|
// that's actually selected.
|
||||||
|
if !showPreviewPane,
|
||||||
|
selection.count == 1,
|
||||||
|
selection.contains(vRecord.id),
|
||||||
|
access.needsAuthorization(for: vRecord) {
|
||||||
|
Spacer(minLength: 4)
|
||||||
|
AuthorizeBadge(record: vRecord)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.draggable(URL(fileURLWithPath: vRecord.fullPath))
|
|
||||||
}
|
}
|
||||||
.width(min: 200, ideal: 320)
|
.width(min: 200, ideal: 320)
|
||||||
|
.customizationID("name")
|
||||||
|
|
||||||
TableColumn("Path", value: \FileRecord.parentPath) { vRecord in
|
TableColumn("Path", value: \FileRecord.parentPath) { vRecord in
|
||||||
Text(vRecord.parentPath)
|
Text(vRecord.parentPath)
|
||||||
@@ -94,27 +195,36 @@ struct ContentView: View {
|
|||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
}
|
}
|
||||||
.width(min: 200, ideal: 380)
|
.width(min: 200, ideal: 380)
|
||||||
|
.customizationID("path")
|
||||||
|
|
||||||
TableColumn("Size", value: \FileRecord.size) { vRecord in
|
TableColumn("Size", value: \FileRecord.size) { vRecord in
|
||||||
Text(vRecord.isDirectory ? "—" : Self.formatSize(inBytes: vRecord.size))
|
Text(vRecord.isDirectory ? "—" : Formatters.size(bytes: vRecord.size))
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
.monospacedDigit()
|
.monospacedDigit()
|
||||||
}
|
}
|
||||||
.width(90)
|
.width(90)
|
||||||
|
.customizationID("size")
|
||||||
|
|
||||||
TableColumn("Created", value: \FileRecord.dateCreated) { vRecord in
|
TableColumn("Created", value: \FileRecord.dateCreated) { vRecord in
|
||||||
Text(Self.formatDate(inDate: vRecord.dateCreated))
|
Text(Formatters.date(vRecord.dateCreated))
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
.monospacedDigit()
|
.monospacedDigit()
|
||||||
}
|
}
|
||||||
.width(140)
|
.width(140)
|
||||||
|
.customizationID("created")
|
||||||
|
|
||||||
TableColumn("Modified", value: \FileRecord.dateModified) { vRecord in
|
TableColumn("Modified", value: \FileRecord.dateModified) { vRecord in
|
||||||
Text(Self.formatDate(inDate: vRecord.dateModified))
|
Text(Formatters.date(vRecord.dateModified))
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
.monospacedDigit()
|
.monospacedDigit()
|
||||||
}
|
}
|
||||||
.width(140)
|
.width(140)
|
||||||
|
.customizationID("modified")
|
||||||
|
} rows: {
|
||||||
|
ForEach(model.visibleRecords) { vRecord in
|
||||||
|
TableRow(vRecord)
|
||||||
|
.draggable(URL(fileURLWithPath: vRecord.fullPath))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
.contextMenu(forSelectionType: FileRecord.ID.self) { vIds in
|
.contextMenu(forSelectionType: FileRecord.ID.self) { vIds in
|
||||||
Button("Open") { openSelection(inIds: vIds) }
|
Button("Open") { openSelection(inIds: vIds) }
|
||||||
@@ -125,13 +235,101 @@ struct ContentView: View {
|
|||||||
} primaryAction: { vIds in
|
} primaryAction: { vIds in
|
||||||
openSelection(inIds: vIds)
|
openSelection(inIds: vIds)
|
||||||
}
|
}
|
||||||
|
// Finder-style spacebar Quick Look. .onKeyPress only fires when the
|
||||||
|
// view (Table) has keyboard focus, so spaces typed into the search
|
||||||
|
// field still produce literal spaces in the query.
|
||||||
|
.onKeyPress(.space) {
|
||||||
|
guard !selection.isEmpty else { return .ignored }
|
||||||
|
let vUrls = recordsFor(inIds: selection)
|
||||||
|
.map { URL(fileURLWithPath: $0.fullPath) }
|
||||||
|
QuickLookCoordinator.shared.show(inUrls: vUrls)
|
||||||
|
return .handled
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===========================
|
// ===========================
|
||||||
// MARK: Status bar
|
// MARK: Selection actions
|
||||||
// ===========================
|
// ===========================
|
||||||
|
|
||||||
private var statusBar: some View {
|
private func revealSelection(inIds: Set<FileRecord.ID>) {
|
||||||
|
// reveal in Finder shows the *original* file (not the staged copy),
|
||||||
|
// since the user wants to navigate to the real location on disk
|
||||||
|
let vUrls = recordsFor(inIds: inIds).map { URL(fileURLWithPath: $0.fullPath) }
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting(vUrls)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func quickLookSelection(inIds: Set<FileRecord.ID>) {
|
||||||
|
// prefer the staged URL when one exists - QLPreviewPanel renders
|
||||||
|
// it without permission issues, whereas the original would fail
|
||||||
|
let vUrls = recordsFor(inIds: inIds).map { access.effectiveURL(for: $0) }
|
||||||
|
QuickLookCoordinator.shared.show(inUrls: vUrls)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func copyPaths(inIds: Set<FileRecord.ID>) {
|
||||||
|
// always copy the original path - the staged tmp path is an
|
||||||
|
// implementation detail that has no meaning outside this session
|
||||||
|
let vPaths = recordsFor(inIds: inIds).map { $0.fullPath }
|
||||||
|
NSPasteboard.general.clearContents()
|
||||||
|
NSPasteboard.general.setString(vPaths.joined(separator: "\n"), forType: .string)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func openSelection(inIds: Set<FileRecord.ID>) {
|
||||||
|
// open the staged copy when available so the default app can read
|
||||||
|
// it; falls back to the original path for files we can read directly
|
||||||
|
for vRecord in recordsFor(inIds: inIds) {
|
||||||
|
NSWorkspace.shared.open(access.effectiveURL(for: vRecord))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func recordsFor(inIds: Set<FileRecord.ID>) -> [FileRecord] {
|
||||||
|
return model.visibleRecords.filter { inIds.contains($0.id) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===========================
|
||||||
|
// MARK: Sort mapping
|
||||||
|
// ===========================
|
||||||
|
|
||||||
|
private static func mapSortOrder(inComparator: KeyPathComparator<FileRecord>) -> FileSortDescriptor {
|
||||||
|
let vAsc = inComparator.order == .forward
|
||||||
|
let vKp = inComparator.keyPath
|
||||||
|
if vKp == \FileRecord.name { return vAsc ? .nameAscending : .nameDescending }
|
||||||
|
if vKp == \FileRecord.parentPath { return vAsc ? .pathAscending : .pathDescending }
|
||||||
|
if vKp == \FileRecord.size { return vAsc ? .sizeAscending : .sizeDescending }
|
||||||
|
if vKp == \FileRecord.dateCreated { return vAsc ? .createdAscending : .createdDescending }
|
||||||
|
if vKp == \FileRecord.dateModified { return vAsc ? .modifiedAscending : .modifiedDescending }
|
||||||
|
return .nameAscending
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func comparatorFor(inDescriptor: FileSortDescriptor) -> KeyPathComparator<FileRecord> {
|
||||||
|
switch inDescriptor {
|
||||||
|
case .nameAscending: return KeyPathComparator(\FileRecord.name, order: .forward)
|
||||||
|
case .nameDescending: return KeyPathComparator(\FileRecord.name, order: .reverse)
|
||||||
|
case .pathAscending: return KeyPathComparator(\FileRecord.parentPath, order: .forward)
|
||||||
|
case .pathDescending: return KeyPathComparator(\FileRecord.parentPath, order: .reverse)
|
||||||
|
case .sizeAscending: return KeyPathComparator(\FileRecord.size, order: .forward)
|
||||||
|
case .sizeDescending: return KeyPathComparator(\FileRecord.size, order: .reverse)
|
||||||
|
case .createdAscending: return KeyPathComparator(\FileRecord.dateCreated, order: .forward)
|
||||||
|
case .createdDescending: return KeyPathComparator(\FileRecord.dateCreated, order: .reverse)
|
||||||
|
case .modifiedAscending: return KeyPathComparator(\FileRecord.dateModified, order: .forward)
|
||||||
|
case .modifiedDescending: return KeyPathComparator(\FileRecord.dateModified, order: .reverse)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===========================
|
||||||
|
// MARK: Status bar
|
||||||
|
// ===========================
|
||||||
|
|
||||||
|
// Extracted into its own View so its @Published-driven refreshes (cache
|
||||||
|
// load progress, indexed count changes during a scan, service-mode flip)
|
||||||
|
// only re-evaluate this small leaf view rather than the ContentView body
|
||||||
|
// that contains the Table.
|
||||||
|
private struct StatusBarView: View {
|
||||||
|
|
||||||
|
@EnvironmentObject var model: AppModel
|
||||||
|
@EnvironmentObject var prefs: Preferences
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
HStack(spacing: 8) {
|
HStack(spacing: 8) {
|
||||||
if model.isIndexing {
|
if model.isIndexing {
|
||||||
ProgressView()
|
ProgressView()
|
||||||
@@ -157,92 +355,4 @@ struct ContentView: View {
|
|||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===========================
|
|
||||||
// MARK: Selection actions
|
|
||||||
// ===========================
|
|
||||||
|
|
||||||
private func revealSelection(inIds: Set<FileRecord.ID>) {
|
|
||||||
let vUrls = recordsFor(inIds: inIds).map { URL(fileURLWithPath: $0.fullPath) }
|
|
||||||
NSWorkspace.shared.activateFileViewerSelecting(vUrls)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func quickLookSelection(inIds: Set<FileRecord.ID>) {
|
|
||||||
let vUrls = recordsFor(inIds: inIds).map { URL(fileURLWithPath: $0.fullPath) }
|
|
||||||
QuickLookCoordinator.shared.show(inUrls: vUrls)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func copyPaths(inIds: Set<FileRecord.ID>) {
|
|
||||||
let vPaths = recordsFor(inIds: inIds).map { $0.fullPath }
|
|
||||||
NSPasteboard.general.clearContents()
|
|
||||||
NSPasteboard.general.setString(vPaths.joined(separator: "\n"), forType: .string)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func openSelection(inIds: Set<FileRecord.ID>) {
|
|
||||||
for vRecord in recordsFor(inIds: inIds) {
|
|
||||||
NSWorkspace.shared.open(URL(fileURLWithPath: vRecord.fullPath))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func recordsFor(inIds: Set<FileRecord.ID>) -> [FileRecord] {
|
|
||||||
return model.visibleRecords.filter { inIds.contains($0.id) }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===========================
|
|
||||||
// MARK: Sort mapping
|
|
||||||
// ===========================
|
|
||||||
|
|
||||||
// converts a Table sort comparator into the model's FileSortDescriptor
|
|
||||||
private static func mapSortOrder(inComparator: KeyPathComparator<FileRecord>) -> FileSortDescriptor {
|
|
||||||
let vAsc = inComparator.order == .forward
|
|
||||||
let vKp = inComparator.keyPath
|
|
||||||
if vKp == \FileRecord.name { return vAsc ? .nameAscending : .nameDescending }
|
|
||||||
if vKp == \FileRecord.parentPath { return vAsc ? .pathAscending : .pathDescending }
|
|
||||||
if vKp == \FileRecord.size { return vAsc ? .sizeAscending : .sizeDescending }
|
|
||||||
if vKp == \FileRecord.dateCreated { return vAsc ? .createdAscending : .createdDescending }
|
|
||||||
if vKp == \FileRecord.dateModified { return vAsc ? .modifiedAscending : .modifiedDescending }
|
|
||||||
return .nameAscending
|
|
||||||
}
|
|
||||||
|
|
||||||
// returns the matching comparator for a given persisted sort descriptor
|
|
||||||
private static func comparatorFor(inDescriptor: FileSortDescriptor) -> KeyPathComparator<FileRecord> {
|
|
||||||
switch inDescriptor {
|
|
||||||
case .nameAscending: return KeyPathComparator(\FileRecord.name, order: .forward)
|
|
||||||
case .nameDescending: return KeyPathComparator(\FileRecord.name, order: .reverse)
|
|
||||||
case .pathAscending: return KeyPathComparator(\FileRecord.parentPath, order: .forward)
|
|
||||||
case .pathDescending: return KeyPathComparator(\FileRecord.parentPath, order: .reverse)
|
|
||||||
case .sizeAscending: return KeyPathComparator(\FileRecord.size, order: .forward)
|
|
||||||
case .sizeDescending: return KeyPathComparator(\FileRecord.size, order: .reverse)
|
|
||||||
case .createdAscending: return KeyPathComparator(\FileRecord.dateCreated, order: .forward)
|
|
||||||
case .createdDescending: return KeyPathComparator(\FileRecord.dateCreated, order: .reverse)
|
|
||||||
case .modifiedAscending: return KeyPathComparator(\FileRecord.dateModified, order: .forward)
|
|
||||||
case .modifiedDescending: return KeyPathComparator(\FileRecord.dateModified, order: .reverse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===========================
|
|
||||||
// MARK: Formatting helpers
|
|
||||||
// ===========================
|
|
||||||
|
|
||||||
private static let kSizeFormatter: ByteCountFormatter = {
|
|
||||||
let vF = ByteCountFormatter()
|
|
||||||
vF.countStyle = .file
|
|
||||||
return vF
|
|
||||||
}()
|
|
||||||
|
|
||||||
private static func formatSize(inBytes: Int64) -> String {
|
|
||||||
return kSizeFormatter.string(fromByteCount: inBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
private static let kDateFormatter: DateFormatter = {
|
|
||||||
let vF = DateFormatter()
|
|
||||||
vF.dateStyle = .short
|
|
||||||
vF.timeStyle = .short
|
|
||||||
return vF
|
|
||||||
}()
|
|
||||||
|
|
||||||
private static func formatDate(inDate: Date) -> String {
|
|
||||||
if inDate.timeIntervalSince1970 < 1 { return "—" }
|
|
||||||
return kDateFormatter.string(from: inDate)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
// ElevatedAccess provides on-demand sudo-backed access to files the GUI
|
||||||
|
// user can't read directly. Common case: the root LaunchDaemon indexed
|
||||||
|
// `/Users/<otheruser>/...` (it has Full Disk Access), the GUI runs as
|
||||||
|
// the current user, and trying to render an inline preview hits a
|
||||||
|
// permission denial. The user clicks "Authorize" in the preview pane,
|
||||||
|
// AdminShell prompts for the password once, sudo copies the file to
|
||||||
|
// the per-user staging directory and chowns it to the GUI user.
|
||||||
|
//
|
||||||
|
// The staged copy is owned by the GUI user, lives in
|
||||||
|
// ~/Library/Caches/Allofit/elevated/
|
||||||
|
// and is wiped at app launch and at app quit so privileged copies don't
|
||||||
|
// linger on disk across sessions.
|
||||||
|
enum ElevatedAccess {
|
||||||
|
|
||||||
|
// per-user staging directory; lives under Library/Caches so macOS
|
||||||
|
// itself may purge it under disk-pressure, and our own cleanup() at
|
||||||
|
// launch + terminate keeps it from accumulating
|
||||||
|
static var stagingDirectory: URL {
|
||||||
|
let vCaches = FileManager.default.urls(
|
||||||
|
for: .cachesDirectory,
|
||||||
|
in: .userDomainMask
|
||||||
|
).first!
|
||||||
|
return vCaches.appendingPathComponent("Allofit/elevated", isDirectory: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// true if the current user can read the file at inPath without elevation
|
||||||
|
static func canRead(path inPath: String) -> Bool {
|
||||||
|
return FileManager.default.isReadableFile(atPath: inPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// wipes anything in the staging directory. Called on app launch (so a
|
||||||
|
// previous session's elevated copies don't survive a relaunch) and on
|
||||||
|
// app terminate (so they don't survive a clean quit either). Failure
|
||||||
|
// is silent - if cleanup fails the next launch's cleanup will retry.
|
||||||
|
static func cleanup() {
|
||||||
|
try? FileManager.default.removeItem(at: stagingDirectory)
|
||||||
|
}
|
||||||
|
|
||||||
|
// copies inUrl into the staging directory via sudo, chowns it to the
|
||||||
|
// current user, and returns the staged URL. Caller is responsible for
|
||||||
|
// catching AdminShell.Error.scriptFailed (cancelled prompt etc).
|
||||||
|
//
|
||||||
|
// Throws if the parent staging directory can't be created or the
|
||||||
|
// admin script fails. Side effect: the system prompts for password
|
||||||
|
// the first time within the auth-cache window.
|
||||||
|
static func stage(_ inUrl: URL) throws -> URL {
|
||||||
|
let vDir = stagingDirectory
|
||||||
|
// create as the current user so the dir is owned by us; sudo
|
||||||
|
// only handles the file copy itself
|
||||||
|
try FileManager.default.createDirectory(
|
||||||
|
at: vDir,
|
||||||
|
withIntermediateDirectories: true,
|
||||||
|
attributes: [.posixPermissions: 0o700]
|
||||||
|
)
|
||||||
|
|
||||||
|
// unique destination file, keeping the original extension so the
|
||||||
|
// QLPreviewView / Launch Services can pick the right renderer
|
||||||
|
var vDst = vDir.appendingPathComponent(UUID().uuidString)
|
||||||
|
let vExt = inUrl.pathExtension
|
||||||
|
if !vExt.isEmpty {
|
||||||
|
vDst.appendPathExtension(vExt)
|
||||||
|
}
|
||||||
|
|
||||||
|
// cp + chown to the current user. The chmod restores plain user
|
||||||
|
// rw / group+other r so the file is treated normally by QL etc.
|
||||||
|
let vScript = """
|
||||||
|
cp \(AdminShell.quote(inUrl.path)) \(AdminShell.quote(vDst.path)) && \
|
||||||
|
chown \(AdminShell.quote(NSUserName())) \(AdminShell.quote(vDst.path)) && \
|
||||||
|
chmod 0644 \(AdminShell.quote(vDst.path))
|
||||||
|
"""
|
||||||
|
_ = try AdminShell.run(vScript)
|
||||||
|
return vDst
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -96,9 +96,14 @@ enum FileIndexer {
|
|||||||
return vRecords
|
return vRecords
|
||||||
}
|
}
|
||||||
|
|
||||||
// builds a FileRecord from a URL's pre-fetched resource values
|
// builds a FileRecord from a URL's pre-fetched resource values.
|
||||||
|
// Clears the URL's resource-value cache first so we always re-stat the
|
||||||
|
// file - a file modified between two FSEvents batches would otherwise
|
||||||
|
// silently return the cached pre-edit mtime.
|
||||||
static func makeRecord(inURL: URL) -> FileRecord? {
|
static func makeRecord(inURL: URL) -> FileRecord? {
|
||||||
guard let vValues = try? inURL.resourceValues(forKeys: Set(kPrefetchKeys)) else {
|
var vUrl = inURL
|
||||||
|
vUrl.removeAllCachedResourceValues()
|
||||||
|
guard let vValues = try? vUrl.resourceValues(forKeys: Set(kPrefetchKeys)) else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
let vName = vValues.name ?? inURL.lastPathComponent
|
let vName = vValues.name ?? inURL.lastPathComponent
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
// Formatters bundles the byte-count and date formatting used by both
|
||||||
|
// the Table's columns and the right-hand preview pane footer. Keeping
|
||||||
|
// the formatter instances cached at file scope avoids reconstructing
|
||||||
|
// them per row render, which would be expensive at 5 000 rows.
|
||||||
|
enum Formatters {
|
||||||
|
|
||||||
|
private static let kSizeFormatter: ByteCountFormatter = {
|
||||||
|
let vF = ByteCountFormatter()
|
||||||
|
vF.countStyle = .file
|
||||||
|
return vF
|
||||||
|
}()
|
||||||
|
|
||||||
|
// human-friendly byte count, e.g. "1.2 MB"
|
||||||
|
static func size(bytes inBytes: Int64) -> String {
|
||||||
|
return kSizeFormatter.string(fromByteCount: inBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let kDateFormatter: DateFormatter = {
|
||||||
|
let vF = DateFormatter()
|
||||||
|
vF.dateStyle = .short
|
||||||
|
vF.timeStyle = .short
|
||||||
|
return vF
|
||||||
|
}()
|
||||||
|
|
||||||
|
// short date+time, with em-dash for sentinel "no date" values
|
||||||
|
static func date(_ inDate: Date) -> String {
|
||||||
|
if inDate.timeIntervalSince1970 < 1 { return "—" }
|
||||||
|
return kDateFormatter.string(from: inDate)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import AppKit
|
||||||
|
import Quartz
|
||||||
|
|
||||||
|
// QuickLookPreviewView wraps Quartz's QLPreviewView so an inline Quick
|
||||||
|
// Look preview can be embedded inside a SwiftUI hierarchy. The same
|
||||||
|
// renderer powers the floating QLPreviewPanel (spacebar), so file-type
|
||||||
|
// coverage (PDFs, images, video, source files, plists, etc.) is
|
||||||
|
// identical between the inline pane and the floating panel.
|
||||||
|
struct QuickLookPreviewView: NSViewRepresentable {
|
||||||
|
|
||||||
|
// the file to preview; nil clears the view
|
||||||
|
let url: URL?
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> NSView {
|
||||||
|
guard let vView = QLPreviewView(frame: .zero, style: .normal) else {
|
||||||
|
return NSView()
|
||||||
|
}
|
||||||
|
// keep the view alive when the parent window closes - we own its
|
||||||
|
// lifetime via SwiftUI, not via QLPreviewPanel's modal behaviour
|
||||||
|
vView.shouldCloseWithWindow = false
|
||||||
|
vView.autostarts = true
|
||||||
|
return vView
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ nsView: NSView, context: Context) {
|
||||||
|
guard let vQlView = nsView as? QLPreviewView else { return }
|
||||||
|
vQlView.previewItem = (url as NSURL?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthorizeBadge is the small lock icon that appears either inside the
|
||||||
|
// preview pane (when the selected file isn't user-readable) or at the
|
||||||
|
// right of the selected row when the preview pane is closed. Clicking
|
||||||
|
// it kicks off the sudo cp + chown via AdminShell - the system prompts
|
||||||
|
// for the password the first time inside the admin-auth-cache window.
|
||||||
|
struct AuthorizeBadge: View {
|
||||||
|
|
||||||
|
@EnvironmentObject var access: AccessManager
|
||||||
|
let record: FileRecord
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button {
|
||||||
|
Task { await access.authorize(record) }
|
||||||
|
} label: {
|
||||||
|
if access.isAuthorizing(record.id) {
|
||||||
|
ProgressView()
|
||||||
|
.controlSize(.small)
|
||||||
|
.frame(width: 16, height: 16)
|
||||||
|
} else {
|
||||||
|
Image(systemName: "lock.shield.fill")
|
||||||
|
.foregroundStyle(.orange)
|
||||||
|
.font(.system(size: 14, weight: .semibold))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.disabled(access.isAuthorizing(record.id))
|
||||||
|
.help(access.isAuthorizing(record.id)
|
||||||
|
? "Authorizing…"
|
||||||
|
: "Authorize to read this file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PreviewPane is the right-hand side panel in the main window. When
|
||||||
|
// exactly one row is selected it renders a Quick Look preview plus a
|
||||||
|
// small metadata footer. If the file isn't user-readable the preview
|
||||||
|
// area becomes a single big tap-target showing a lock icon - clicking
|
||||||
|
// it (or the badge that appears on the selected row when the pane is
|
||||||
|
// closed) triggers the sudo-elevation flow.
|
||||||
|
struct PreviewPane: View {
|
||||||
|
|
||||||
|
@EnvironmentObject var model: AppModel
|
||||||
|
@EnvironmentObject var access: AccessManager
|
||||||
|
// passed in from ContentView (its @State) so this view re-renders
|
||||||
|
// whenever the user's selection changes
|
||||||
|
let selection: Set<FileRecord.ID>
|
||||||
|
|
||||||
|
private var selectedRecord: FileRecord? {
|
||||||
|
guard selection.count == 1, let vId = selection.first else { return nil }
|
||||||
|
return model.visibleRecords.first(where: { $0.id == vId })
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
if let vRecord = selectedRecord {
|
||||||
|
content(for: vRecord)
|
||||||
|
} else {
|
||||||
|
emptyState
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.background(Color(NSColor.controlBackgroundColor))
|
||||||
|
}
|
||||||
|
|
||||||
|
// preview + metadata footer for one selected record
|
||||||
|
private func content(for inRecord: FileRecord) -> some View {
|
||||||
|
let vEffectiveUrl = access.effectiveURL(for: inRecord)
|
||||||
|
let vReadable = ElevatedAccess.canRead(path: vEffectiveUrl.path)
|
||||||
|
return VStack(spacing: 0) {
|
||||||
|
Group {
|
||||||
|
if vReadable {
|
||||||
|
QuickLookPreviewView(url: vEffectiveUrl)
|
||||||
|
} else {
|
||||||
|
authorizePrompt(for: inRecord)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
|
||||||
|
Divider()
|
||||||
|
metadata(for: inRecord)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// full-area authorize hint shown when the selected file isn't
|
||||||
|
// user-readable. The whole area is the button target so users
|
||||||
|
// can click anywhere over the locked preview to authorize.
|
||||||
|
private func authorizePrompt(for inRecord: FileRecord) -> some View {
|
||||||
|
Button {
|
||||||
|
Task { await access.authorize(inRecord) }
|
||||||
|
} label: {
|
||||||
|
VStack(spacing: 10) {
|
||||||
|
if access.isAuthorizing(inRecord.id) {
|
||||||
|
ProgressView()
|
||||||
|
.controlSize(.regular)
|
||||||
|
} else {
|
||||||
|
Image(systemName: "lock.shield.fill")
|
||||||
|
.font(.system(size: 40))
|
||||||
|
.foregroundStyle(.orange)
|
||||||
|
}
|
||||||
|
Text(access.isAuthorizing(inRecord.id)
|
||||||
|
? "Authorizing…"
|
||||||
|
: "Click to authorize preview")
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
if let vErr = access.lastError, !access.isAuthorizing(inRecord.id) {
|
||||||
|
Text(vErr)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.red)
|
||||||
|
.multilineTextAlignment(.center)
|
||||||
|
.padding(.horizontal, 20)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
.contentShape(Rectangle())
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.disabled(access.isAuthorizing(inRecord.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// thin metadata bar at the bottom of the preview pane
|
||||||
|
private func metadata(for inRecord: FileRecord) -> some View {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text(inRecord.name)
|
||||||
|
.font(.headline)
|
||||||
|
.lineLimit(2)
|
||||||
|
.truncationMode(.middle)
|
||||||
|
Text(inRecord.parentPath)
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
.truncationMode(.middle)
|
||||||
|
.lineLimit(1)
|
||||||
|
.textSelection(.enabled)
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
if !inRecord.isDirectory {
|
||||||
|
Text(Formatters.size(bytes: inRecord.size))
|
||||||
|
.monospacedDigit()
|
||||||
|
Text("·")
|
||||||
|
}
|
||||||
|
Text("Modified \(Formatters.date(inRecord.dateModified))")
|
||||||
|
.monospacedDigit()
|
||||||
|
}
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
.padding(12)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.background(.bar)
|
||||||
|
}
|
||||||
|
|
||||||
|
// placeholder shown when nothing or multiple rows are selected
|
||||||
|
private var emptyState: some View {
|
||||||
|
VStack(spacing: 10) {
|
||||||
|
Image(systemName: "eye.slash")
|
||||||
|
.font(.system(size: 32))
|
||||||
|
.foregroundColor(.secondary.opacity(0.6))
|
||||||
|
Text(placeholderText)
|
||||||
|
.font(.callout)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
.multilineTextAlignment(.center)
|
||||||
|
.padding(.horizontal, 16)
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var placeholderText: String {
|
||||||
|
if selection.isEmpty {
|
||||||
|
return "Select a file to preview"
|
||||||
|
}
|
||||||
|
return "\(selection.count) items selected"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -188,24 +188,20 @@ enum ServiceInstaller {
|
|||||||
return (vProcess.terminationStatus, vOutStr, vErrStr)
|
return (vProcess.terminationStatus, vOutStr, vErrStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// runs a shell script with administrator privileges through AppleScript;
|
// runs a shell script with administrator privileges. Bridges
|
||||||
// the system shows the standard password prompt the first time
|
// AdminShell.Error into ServiceInstaller.InstallError so the calling
|
||||||
|
// SettingsView UI gets a single error type to surface.
|
||||||
private static func runWithAdminPrivileges(inScript: String) throws {
|
private static func runWithAdminPrivileges(inScript: String) throws {
|
||||||
let vEscaped = inScript
|
do {
|
||||||
.replacingOccurrences(of: "\\", with: "\\\\")
|
_ = try AdminShell.run(inScript)
|
||||||
.replacingOccurrences(of: "\"", with: "\\\"")
|
} catch let vErr as AdminShell.Error {
|
||||||
let vAppleScriptSource = "do shell script \"\(vEscaped)\" with administrator privileges"
|
throw InstallError.authorizationFailed(vErr.errorDescription ?? "\(vErr)")
|
||||||
let vScript = NSAppleScript(source: vAppleScriptSource)
|
|
||||||
var vErr: NSDictionary?
|
|
||||||
let vResult = vScript?.executeAndReturnError(&vErr)
|
|
||||||
if vResult == nil {
|
|
||||||
let vMessage = vErr?[NSAppleScript.errorMessage] as? String ?? "unknown AppleScript error"
|
|
||||||
throw InstallError.authorizationFailed(vMessage)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// minimal POSIX-style single-quote escape
|
// shell-quote helper, delegating to the shared AdminShell quoter so
|
||||||
|
// both call sites use the same escaping rules
|
||||||
private static func shellQuote(inString: String) -> String {
|
private static func shellQuote(inString: String) -> String {
|
||||||
return "'" + inString.replacingOccurrences(of: "'", with: "'\\''") + "'"
|
return AdminShell.quote(inString)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+53
-5
@@ -3,7 +3,12 @@
|
|||||||
# launched like any other macOS app (double-click in Finder, dragged into
|
# launched like any other macOS app (double-click in Finder, dragged into
|
||||||
# /Applications, etc.). Run from the project root:
|
# /Applications, etc.). Run from the project root:
|
||||||
# ./build-app.sh
|
# ./build-app.sh
|
||||||
# The produced bundle ends up at ./Allofit.app
|
# ./build-app.sh --version 1.0.0 # explicit version stamp
|
||||||
|
# ./build-app.sh -v 1.0.0 -b 42 # version + build number
|
||||||
|
# ALLOFIT_VERSION=1.0.0 ./build-app.sh # env var still works
|
||||||
|
#
|
||||||
|
# Version precedence: --version arg > ALLOFIT_VERSION env > default 0.0.0.
|
||||||
|
# The produced bundle ends up at ./Allofit.app.
|
||||||
#
|
#
|
||||||
# Icon support (optional, first match wins):
|
# Icon support (optional, first match wins):
|
||||||
# icons/Allofit.icns - pre-built .icns, copied straight in
|
# icons/Allofit.icns - pre-built .icns, copied straight in
|
||||||
@@ -16,10 +21,53 @@ set -euo pipefail
|
|||||||
|
|
||||||
kAppName="Allofit"
|
kAppName="Allofit"
|
||||||
kBundleId="com.bitsycore.allofit"
|
kBundleId="com.bitsycore.allofit"
|
||||||
# version + build can be overridden from CI so the release tag flows into
|
|
||||||
# the .app's Info.plist. Default to "0.0.0" / "0" for local dev builds.
|
# ==================
|
||||||
kVersion="${ALLOFIT_VERSION:-0.0.0}"
|
# MARK: Args
|
||||||
kBuildNumber="${ALLOFIT_BUILD:-0}"
|
# ==================
|
||||||
|
|
||||||
|
vVersionArg=""
|
||||||
|
vBuildArg=""
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--version|-v)
|
||||||
|
if [[ $# -lt 2 ]]; then
|
||||||
|
echo "$1 requires a value" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
vVersionArg="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--build|-b)
|
||||||
|
if [[ $# -lt 2 ]]; then
|
||||||
|
echo "$1 requires a value" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
vBuildArg="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
-h|--help)
|
||||||
|
sed -n '2,/^set /p' "$0" | sed -E 's/^#( |$)//;/^set /d'
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown argument: $1" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# version / build precedence: --flag arg > env var > default
|
||||||
|
if [[ -n "$vVersionArg" ]]; then
|
||||||
|
kVersion="$vVersionArg"
|
||||||
|
else
|
||||||
|
kVersion="${ALLOFIT_VERSION:-0.0.0}"
|
||||||
|
fi
|
||||||
|
if [[ -n "$vBuildArg" ]]; then
|
||||||
|
kBuildNumber="$vBuildArg"
|
||||||
|
else
|
||||||
|
kBuildNumber="${ALLOFIT_BUILD:-0}"
|
||||||
|
fi
|
||||||
|
|
||||||
vProjectRoot="$(cd "$(dirname "$0")" && pwd)"
|
vProjectRoot="$(cd "$(dirname "$0")" && pwd)"
|
||||||
vAppBundle="${vProjectRoot}/${kAppName}.app"
|
vAppBundle="${vProjectRoot}/${kAppName}.app"
|
||||||
|
|||||||
+44
-10
@@ -4,39 +4,69 @@
|
|||||||
# with the .app and an /Applications symlink so the user can drag-install.
|
# with the .app and an /Applications symlink so the user can drag-install.
|
||||||
#
|
#
|
||||||
# Usage:
|
# Usage:
|
||||||
# ./build-dmg.sh # rebuilds the .app first, then DMGs it
|
# ./build-dmg.sh # default version (0.0.0)
|
||||||
# ./build-dmg.sh --skip-build # assumes Allofit.app already exists
|
# ./build-dmg.sh --version 1.0.0 # explicit version
|
||||||
# ALLOFIT_VERSION=1.0.0 ./build-dmg.sh
|
# ./build-dmg.sh -v 1.0.0 --skip-build # version + skip rebuild
|
||||||
|
# ALLOFIT_VERSION=1.0.0 ./build-dmg.sh # env var still works
|
||||||
#
|
#
|
||||||
|
# Version precedence: --version arg > ALLOFIT_VERSION env > default 0.0.0.
|
||||||
# Output: Allofit-<version>.dmg in the project root.
|
# Output: Allofit-<version>.dmg in the project root.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
kAppName="Allofit"
|
kAppName="Allofit"
|
||||||
kVersion="${ALLOFIT_VERSION:-0.0.0}"
|
|
||||||
|
|
||||||
vProjectRoot="$(cd "$(dirname "$0")" && pwd)"
|
vProjectRoot="$(cd "$(dirname "$0")" && pwd)"
|
||||||
vAppBundle="${vProjectRoot}/${kAppName}.app"
|
vAppBundle="${vProjectRoot}/${kAppName}.app"
|
||||||
vDmgPath="${vProjectRoot}/${kAppName}-${kVersion}.dmg"
|
|
||||||
vStagingDir="${vProjectRoot}/.build/dmg-staging"
|
vStagingDir="${vProjectRoot}/.build/dmg-staging"
|
||||||
|
|
||||||
|
# ==================
|
||||||
|
# MARK: Args
|
||||||
|
# ==================
|
||||||
|
|
||||||
vSkipBuild=0
|
vSkipBuild=0
|
||||||
for vArg in "$@"; do
|
vVersionArg=""
|
||||||
case "$vArg" in
|
while [[ $# -gt 0 ]]; do
|
||||||
--skip-build) vSkipBuild=1 ;;
|
case "$1" in
|
||||||
|
--version|-v)
|
||||||
|
if [[ $# -lt 2 ]]; then
|
||||||
|
echo "$1 requires a value" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
vVersionArg="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--skip-build)
|
||||||
|
vSkipBuild=1
|
||||||
|
shift
|
||||||
|
;;
|
||||||
-h|--help)
|
-h|--help)
|
||||||
sed -n '2,/^set /p' "$0" | sed -E 's/^#( |$)//;/^set /d'
|
sed -n '2,/^set /p' "$0" | sed -E 's/^#( |$)//;/^set /d'
|
||||||
exit 0
|
exit 0
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown argument: $vArg" >&2
|
echo "Unknown argument: $1" >&2
|
||||||
exit 1
|
exit 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# version precedence: --version arg > env var > default
|
||||||
|
if [[ -n "$vVersionArg" ]]; then
|
||||||
|
kVersion="$vVersionArg"
|
||||||
|
else
|
||||||
|
kVersion="${ALLOFIT_VERSION:-0.0.0}"
|
||||||
|
fi
|
||||||
|
vDmgPath="${vProjectRoot}/${kAppName}-${kVersion}.dmg"
|
||||||
|
|
||||||
|
# ==================
|
||||||
|
# MARK: Build .app
|
||||||
|
# ==================
|
||||||
|
|
||||||
if [[ "$vSkipBuild" -eq 0 ]]; then
|
if [[ "$vSkipBuild" -eq 0 ]]; then
|
||||||
echo "==> Rebuilding ${kAppName}.app first"
|
echo "==> Rebuilding ${kAppName}.app first"
|
||||||
"${vProjectRoot}/build-app.sh"
|
# Propagate the resolved version into build-app.sh so the bundled
|
||||||
|
# Info.plist matches what we're naming the DMG.
|
||||||
|
ALLOFIT_VERSION="${kVersion}" "${vProjectRoot}/build-app.sh"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ ! -d "${vAppBundle}" ]]; then
|
if [[ ! -d "${vAppBundle}" ]]; then
|
||||||
@@ -44,6 +74,10 @@ if [[ ! -d "${vAppBundle}" ]]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ==================
|
||||||
|
# MARK: Stage + create DMG
|
||||||
|
# ==================
|
||||||
|
|
||||||
echo "==> Staging DMG contents"
|
echo "==> Staging DMG contents"
|
||||||
rm -rf "${vStagingDir}"
|
rm -rf "${vStagingDir}"
|
||||||
mkdir -p "${vStagingDir}"
|
mkdir -p "${vStagingDir}"
|
||||||
|
|||||||
@@ -147,7 +147,20 @@ fi
|
|||||||
|
|
||||||
if [[ -f "$kServiceLogStdout" || -f "$kServiceLogStderr" ]]; then
|
if [[ -f "$kServiceLogStdout" || -f "$kServiceLogStderr" ]]; then
|
||||||
echo "==> Removing service log files"
|
echo "==> Removing service log files"
|
||||||
vRun rm -f "$kServiceLogStdout" "$kServiceLogStderr"
|
# /tmp has the sticky bit, so only the file's owner can rm it. Logs
|
||||||
|
# left over from a previous *root* daemon run are owned by root - we
|
||||||
|
# need sudo to delete them. Plain rm for user-owned logs (user agent
|
||||||
|
# mode), sudo rm for root-owned ones.
|
||||||
|
for vLog in "$kServiceLogStdout" "$kServiceLogStderr"; do
|
||||||
|
if [[ -f "$vLog" ]]; then
|
||||||
|
if [[ -O "$vLog" ]]; then
|
||||||
|
vRun rm -f "$vLog"
|
||||||
|
else
|
||||||
|
vNeedsSudo
|
||||||
|
vRun sudo rm -f "$vLog"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ==================
|
# ==================
|
||||||
|
|||||||
Reference in New Issue
Block a user