AppleScript and battery items

This commit is contained in:
Serg
2018-04-09 17:32:27 +07:00
parent b3f461db45
commit d48d590462
3 changed files with 46 additions and 12 deletions
+37
View File
@@ -0,0 +1,37 @@
import Foundation
class AppleScriptTouchBarItem: NSCustomTouchBarItem {
let script: NSAppleScript
private var timer: Timer!
private let button = NSButton(title: "", target: nil, action: nil)
init?(identifier: NSTouchBarItem.Identifier, appleScript: String, interval: TimeInterval) {
guard let script = NSAppleScript(source: appleScript) else {
return nil
}
self.script = script
super.init(identifier: identifier)
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(refresh), userInfo: nil, repeats: true)
self.view = button
button.bezelColor = .clear
refresh()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func refresh() {
self.button.title = self.execute()
}
func execute() -> String {
var error: NSDictionary?
let output = script.executeAndReturnError(&error)
if let error = error {
print(error)
return "error"
}
return output.stringValue ?? "empty value"
}
}
+4 -12
View File
@@ -87,6 +87,10 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
case .next:
return CustomButtonTouchBarItem(identifier: identifier, title: "⏩", HIDKeycode: NX_KEYTYPE_NEXT)
case .battery:
let url = Bundle.main.url(forResource: "battery", withExtension: "scpt")!
let script = try! String.init(contentsOf: url)
return AppleScriptTouchBarItem(identifier: identifier, appleScript: script, interval: 60)
case .time:
return TimeTouchBarItem(identifier: identifier, formatTemplate: "HH:mm")
@@ -94,18 +98,6 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
return nil
}
}
// func getBattery() {
// var error: NSDictionary?
// if let scriptObject = NSAppleScript(source: <#T##String#>) {
// if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(
// &error) {
// print(output.stringValue)
// } else if (error != nil) {
// print("error: \(error)")
// }
// }
// }
}