45 lines
1.9 KiB
Swift
45 lines
1.9 KiB
Swift
import Darwin
|
|
import Foundation
|
|
import HelderServices
|
|
|
|
/// Renames the running app, which is what Mission Control, the Dock tooltip and ⌘Tab show.
|
|
/// Uses private LaunchServices calls looked up at runtime; when one is missing the name stays as it is.
|
|
@MainActor
|
|
enum AppName {
|
|
static let standard = "Helder"
|
|
private static var current: String?
|
|
|
|
static func set(_ name: String) {
|
|
guard name != current else { return }
|
|
current = name
|
|
guard let calls = LaunchServicesCalls.shared, let asn = calls.currentASN()?.takeUnretainedValue() else { return }
|
|
let status = calls.setItem(LaunchServicesCalls.defaultSession, asn, calls.displayNameKey, name as CFString, nil)
|
|
if status != noErr { Log.warn("app", "could not rename the app to \(name): \(status)") }
|
|
}
|
|
}
|
|
|
|
private struct LaunchServicesCalls {
|
|
typealias CurrentASN = @convention(c) () -> Unmanaged<CFTypeRef>?
|
|
typealias SetItem = @convention(c) (Int32, CFTypeRef, CFString, CFTypeRef, UnsafeMutableRawPointer?) -> OSStatus
|
|
|
|
/// `kLSDefaultSessionID`
|
|
static let defaultSession: Int32 = -2
|
|
|
|
let currentASN: CurrentASN
|
|
let setItem: SetItem
|
|
let displayNameKey: CFString
|
|
|
|
static let shared: LaunchServicesCalls? = {
|
|
guard let handle = dlopen("/System/Library/Frameworks/CoreServices.framework/CoreServices", RTLD_LAZY),
|
|
let asn = dlsym(handle, "_LSGetCurrentApplicationASN"),
|
|
let set = dlsym(handle, "_LSSetApplicationInformationItem"),
|
|
let key = dlsym(handle, "_kLSDisplayNameKey") else {
|
|
Log.warn("app", "LaunchServices rename calls not found; the app keeps its name")
|
|
return nil
|
|
}
|
|
return LaunchServicesCalls(currentASN: unsafeBitCast(asn, to: CurrentASN.self),
|
|
setItem: unsafeBitCast(set, to: SetItem.self),
|
|
displayNameKey: key.load(as: CFString.self))
|
|
}()
|
|
}
|