1
0
mirror of https://github.com/Toxblh/MTMR.git synced 2026-01-10 17:08:39 +00:00

Added Native Battery

This commit is contained in:
Toxblh 2018-04-21 00:22:45 +01:00
parent d4108d848e
commit 7874433d9b
5 changed files with 55 additions and 78 deletions

View File

@ -18,7 +18,9 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
DispatchQueue.main.async {
var error: NSDictionary?
guard script.compileAndReturnError(&error) else {
// print(error?.description ?? "unknown error")
#if DEBUG
print(error?.description ?? "unknown error")
#endif
DispatchQueue.main.async {
self.button.title = "error"
}
@ -33,7 +35,9 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
}
func refreshAndSchedule() {
// print("refresh happened")
#if DEBUG
print("refresh happened")
#endif
let scriptResult = self.execute()
DispatchQueue.main.async {
self.button.title = scriptResult

View File

@ -15,35 +15,17 @@ class BatteryBarItem: NSCustomTouchBarItem {
override init(identifier: NSTouchBarItem.Identifier) {
super.init(identifier: identifier)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateInfo), userInfo: nil, repeats: true)
self.view = button
button.bezelColor = .clear
// updateInfo()
BatteryMonitor(button: button)
let batteryInfo = BatteryInfo(button: button)
batteryInfo.start()
batteryInfo.updateInfo()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func updateInfo() {
var title = ""
let info = BatteryInfo().getInfo()
let timeRemainig = info["timeRemainig"] as! String
let percentage = info["percentage"] as! Int
let isCharging = info["isCharging"] as! Bool
let isCharged = info["isCharged"] as! Bool
if isCharged {
title += "⚡️"
}
title += String(percentage) + "%" + timeRemainig
button.title = title
}
}
class BatteryInfo: NSObject {
@ -52,11 +34,13 @@ class BatteryInfo: NSObject {
var timeToFull: Int = 0
var isCharged: Bool = false
var isCharging: Bool = false
var ACPower: String = ""
var timeRemaining: String = ""
var button: NSButton?
var loop:CFRunLoopSource?
override convenience init(button: NSButton) {
init(button: NSButton) {
super.init()
self.button = button
@ -72,13 +56,11 @@ class BatteryInfo: NSObject {
}
let watcher = Unmanaged<BatteryInfo>.fromOpaque(ctx).takeUnretainedValue()
watcher.getInfo()
watcher.updateInfo()
}, context).takeRetainedValue() as CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
}
func stop() {
if !(self.loop != nil) {
return
@ -87,18 +69,6 @@ class BatteryInfo: NSObject {
self.loop = nil
}
func getFormattedTime(time: Int) -> String {
if (time > 0) {
let timeFormatted = NSString(format: " (%d:%02d)", time / 60, time % 60) as String
print(timeFormatted)
return timeFormatted
} else if (time == 0) {
return ""
}
return "(?)"
}
func getPSInfo() {
let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef]
@ -129,32 +99,39 @@ class BatteryInfo: NSObject {
if (isCharging != nil) {
self.isCharging = isCharging as! Bool
}
let ACPower = psDesc[kIOPSPowerSourceStateKey]
if (ACPower != nil) {
self.ACPower = ACPower as! String
}
}
}
}
public func getInfo() -> [String: Any] {
var result: [String: Any] = [:]
var timeRemaining = ""
self.getPSInfo()
// print(self.current)
// print(self.timeToEmpty)
// print(self.timeToFull)
// print(self.isCharged)
// print(self.isCharging)
if isCharged {
timeRemaining = getFormattedTime(time: self.timeToFull)
} else {
timeRemaining = getFormattedTime(time: self.timeToEmpty)
func getFormattedTime(time: Int) -> String {
if (time > 0) {
let timeFormatted = NSString(format: " (%d:%02d)", time / 60, time % 60) as String
return timeFormatted
} else if (time == 0) {
return ""
}
result["timeRemainig"] = timeRemaining
result["percentage"] = self.current
result["isCharging"] = self.isCharging
result["isCharged"] = self.isCharged
return result
return " (?)"
}
public func updateInfo() {
var title = ""
self.getPSInfo()
if ACPower == "AC Power" {
title += "⚡️"
timeRemaining = getFormattedTime(time: timeToFull)
} else {
timeRemaining = getFormattedTime(time: timeToEmpty)
}
title += String(current) + "%" + timeRemaining
button?.title = title
}
}

View File

@ -31,7 +31,10 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
"IDR": "Rp",
"MXN": "$",
"SGD": "$",
"CHF": "Fr."
"CHF": "Fr.",
"BTC": "฿",
"LTC": "Ł",
"ETH": "Ξ",
]
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval, from: String, to: String, onTap: @escaping () -> ()) {

View File

@ -117,15 +117,6 @@ class SupportedTypesHolder {
return (item: .brightness(refreshInterval: interval ?? 0.5), action: .none, parameters: [:])
}
},
"battery": { decoder in
enum CodingKeys: String, CodingKey { case refreshInterval }
let container = try decoder.container(keyedBy: CodingKeys.self)
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
let scriptPath = Bundle.main.path(forResource: "Battery", ofType: "scpt")!
let item = ItemType.appleScriptTitledButton(source: Source(filePath: scriptPath), refreshInterval: interval ?? 1800.0)
let action = try ActionType(from: decoder)
return (item: item, action: action, parameters: [:])
},
"sleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["sleepnow"]), parameters: [:]) },
"displaySleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["displaysleepnow"]), parameters: [:]) },
]
@ -153,7 +144,7 @@ enum ItemType: Decodable {
case staticButton(title: String)
case appleScriptTitledButton(source: SourceProtocol, refreshInterval: Double)
case timeButton(formatTemplate: String)
case batteryButton()
case battery()
case dock()
case volume()
case brightness(refreshInterval: Double)
@ -179,7 +170,7 @@ enum ItemType: Decodable {
case staticButton
case appleScriptTitledButton
case timeButton
case batteryButton
case battery
case dock
case volume
case brightness
@ -201,8 +192,8 @@ enum ItemType: Decodable {
case .timeButton:
let template = try container.decodeIfPresent(String.self, forKey: .formatTemplate) ?? "HH:mm"
self = .timeButton(formatTemplate: template)
case .batteryButton:
self = .batteryButton()
case .battery:
self = .battery()
case .dock:
self = .dock()
case .volume:

View File

@ -23,8 +23,8 @@ extension ItemType {
return "com.toxblh.mtmr.appleScriptButton."
case .timeButton(formatTemplate: _):
return "com.toxblh.mtmr.timeButton."
case .batteryButton():
return "com.toxblh.mtmr.batteryButton."
case .battery():
return "com.toxblh.mtmr.battery."
case .dock():
return "com.toxblh.mtmr.dock"
case .volume():
@ -166,7 +166,7 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
barItem = AppleScriptTouchBarItem(identifier: identifier, source: source, interval: interval, onTap: action)
case .timeButton(formatTemplate: let template):
barItem = TimeTouchBarItem(identifier: identifier, formatTemplate: template)
case .batteryButton():
case .battery():
barItem = BatteryBarItem(identifier: identifier)
case .dock:
barItem = AppScrubberTouchBarItem(identifier: identifier)
@ -229,7 +229,9 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
case .openUrl(url: let url):
return {
if let url = URL(string: url), NSWorkspace.shared.open(url) {
// print("URL was successfully opened")
#if DEBUG
print("URL was successfully opened")
#endif
} else {
print("error", url)
}