Files
phbar/Sources/phbar/Models/Event/PHEventLoader.swift
T
2026-07-12 00:50:11 +02:00

94 lines
3.0 KiB
Swift

import Darwin
import Foundation
import phbarEvents
/// Loads external event recognizers (shared libraries) from the user's config
/// directory: `~/.config/phbar/events/<name>/event.toml` + the referenced
/// library.
///
/// Each event lives in its own folder. The manifest names the `.dylib` and,
/// optionally, the factory symbol (default `phbar_event_create`). Libraries are
/// `dlopen`'d once and cached for the lifetime of the process, so repeated
/// subscriptions reuse the same recognizer instance. A loaded library's handle
/// is intentionally never `dlclose`'d: the recognizer instance it vends lives in
/// it for as long as phbar runs.
@MainActor
final class PHEventLoader {
static let shared = PHEventLoader()
/// Root directory scanned for external events.
let directory: URL
private struct Loaded {
let handle: UnsafeMutableRawPointer?
let recognizer: any PHEventRecognizer
}
private var cache: [String: Loaded] = [:]
init(directory: URL? = nil) {
self.directory = directory ?? Self.defaultDirectory
}
static var defaultDirectory: URL {
FileManager.default.homeDirectoryForCurrentUser.appending(path: ".config/phbar/events")
}
/// Returns the recognizer for `name`, loading and caching it on first access.
/// `nil` (with a stderr diagnostic) if no valid library is found.
func recognizer(for name: String) -> (any PHEventRecognizer)? {
if let cached = cache[name] { return cached.recognizer }
switch load(name: name) {
case .success(let loaded):
cache[name] = loaded
return loaded.recognizer
case .failure(let message):
fputs("phbar: could not load event '\(name)': \(message)\n", stderr)
return nil
}
}
// MARK: - Loading
private enum Outcome {
case success(Loaded)
case failure(String)
}
private func load(name: String) -> Outcome {
let folder = directory.appending(path: name)
let manifest: PHEventManifest
do {
manifest = try PHEventManifest.load(at: folder)
} catch {
return .failure("no readable event.toml in \(folder.path)")
}
if let api = manifest.apiVersion, api != PHEventAPIVersion {
return .failure("incompatible API version (host \(PHEventAPIVersion), library \(api))")
}
let libraryPath = folder.appending(path: manifest.library).path
guard FileManager.default.fileExists(atPath: libraryPath) else {
return .failure("library '\(manifest.library)' not found")
}
let handle = libraryPath.withCString { dlopen($0, RTLD_NOW | RTLD_LOCAL) }
guard let handle else {
return .failure("dlopen failed: \(dlerror().map { String(cString: $0) } ?? "unknown")")
}
let symbol = manifest.symbol ?? PHEventCreateSymbol
guard let raw = symbol.withCString({ dlsym(handle, $0) }) else {
return .failure("symbol '\(symbol)' not found: \(dlerror().map { String(cString: $0) } ?? "unknown")")
}
let factory = unsafeBitCast(raw, to: PHEventCreate.self)
let instance = factory()
guard let recognizer = instance as? any PHEventRecognizer else {
return .failure("factory did not return a PHEventRecognizer")
}
return .success(Loaded(handle: handle, recognizer: recognizer))
}
}