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

another try to fix button titles and images

This commit is contained in:
Serg 2018-05-11 00:24:32 +07:00
parent 9e10b2d3d1
commit d46827832e
7 changed files with 80 additions and 54 deletions

View File

@ -10,7 +10,7 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
super.init(identifier: identifier, title: "", onTap: onTap, onLongTap: onLongTap) super.init(identifier: identifier, title: "", onTap: onTap, onLongTap: onLongTap)
self.forceHideConstraint = self.view.widthAnchor.constraint(equalToConstant: 0) self.forceHideConstraint = self.view.widthAnchor.constraint(equalToConstant: 0)
guard let script = source.appleScript else { guard let script = source.appleScript else {
button.title = "no script" self.title = "no script"
return return
} }
self.script = script self.script = script
@ -22,7 +22,7 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
print(error?.description ?? "unknown error") print(error?.description ?? "unknown error")
#endif #endif
DispatchQueue.main.async { DispatchQueue.main.async {
self.button.title = "error" self.title = "error"
} }
return return
} }
@ -40,7 +40,7 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
#endif #endif
let scriptResult = self.execute() let scriptResult = self.execute()
DispatchQueue.main.async { DispatchQueue.main.async {
self.button.title = scriptResult self.title = scriptResult
self.forceHideConstraint.isActive = scriptResult == "" self.forceHideConstraint.isActive = scriptResult == ""
} }
DispatchQueue.main.asyncAfter(deadline: .now() + self.interval) { [weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + self.interval) { [weak self] in

View File

@ -19,8 +19,10 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
init(identifier: NSTouchBarItem.Identifier, title: String, onTap callback: @escaping () -> (), onLongTap callbackLong: @escaping () -> (), bezelColor: NSColor? = .clear) { init(identifier: NSTouchBarItem.Identifier, title: String, onTap callback: @escaping () -> (), onLongTap callbackLong: @escaping () -> (), bezelColor: NSColor? = .clear) {
self.tapClosure = callback self.tapClosure = callback
self.longTapClosure = callbackLong self.longTapClosure = callbackLong
self.attributedTitle = title.defaultTouchbarAttributedString
super.init(identifier: identifier) super.init(identifier: identifier)
button = CustomHeightButton(title: title, target: nil, action: nil)
longClick = NSPressGestureRecognizer(target: self, action: #selector(handleGestureLong)) longClick = NSPressGestureRecognizer(target: self, action: #selector(handleGestureLong))
longClick.allowedTouchTypes = .direct longClick.allowedTouchTypes = .direct
@ -30,7 +32,8 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
singleClick.allowedTouchTypes = .direct singleClick.allowedTouchTypes = .direct
singleClick.delegate = self singleClick.delegate = self
installButton(titled: title, bordered: true, backgroundColor: nil) reinstallButton()
button.attributedTitle = attributedTitle
} }
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
@ -39,29 +42,46 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
var isBordered: Bool = true { var isBordered: Bool = true {
didSet { didSet {
installButton(titled: self.button.title, bordered: isBordered, backgroundColor: backgroundColor) reinstallButton()
} }
} }
var backgroundColor: NSColor? { var backgroundColor: NSColor? {
didSet { didSet {
installButton(titled: self.button.title, bordered: isBordered, backgroundColor: backgroundColor) reinstallButton()
} }
} }
private func installButton(titled title: String, bordered: Bool, backgroundColor: NSColor?) { var title: String {
button = CustomHeightButton(title: title, target: nil, action: nil) get {
let cell = CustomButtonCell() return self.attributedTitle.string
}
set {
self.attributedTitle = newValue.defaultTouchbarAttributedString
}
}
var attributedTitle: NSAttributedString {
didSet {
self.button?.attributedTitle = attributedTitle
}
}
private func reinstallButton() {
let title = button.attributedTitle
let image = button.image
let cell = CustomButtonCell(parentItem: self)
button.cell = cell button.cell = cell
if let color = backgroundColor { if let color = backgroundColor {
cell.isBordered = true cell.isBordered = true
button.bezelColor = color button.bezelColor = color
cell.backgroundColor = color cell.backgroundColor = color
} else { } else {
button.isBordered = bordered button.isBordered = isBordered
button.bezelStyle = bordered ? .rounded : .inline button.bezelStyle = isBordered ? .rounded : .inline
} }
button.title = title button.attributedTitle = title
button.image = image
self.view = button self.view = button
self.view.addGestureRecognizer(longClick) self.view.addGestureRecognizer(longClick)
@ -118,15 +138,21 @@ class CustomHeightButton : NSButton {
} }
class CustomButtonCell: NSButtonCell { class CustomButtonCell: NSButtonCell {
weak var parentItem: CustomButtonTouchBarItem?
init() { init(parentItem: CustomButtonTouchBarItem) {
super.init(textCell: "") super.init(textCell: "")
self.parentItem = parentItem
} }
override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) { override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) {
super.highlight(flag, withFrame: cellFrame, in: controlView) super.highlight(flag, withFrame: cellFrame, in: controlView)
if !self.isBordered { if !self.isBordered {
self.setTitle(self.title, withColor: flag ? .lightGray : .white) if flag {
self.setAttributedTitle(self.attributedTitle, withColor: .lightGray)
} else if let parentItem = self.parentItem {
self.attributedTitle = parentItem.attributedTitle
}
} }
} }
@ -134,22 +160,19 @@ class CustomButtonCell: NSButtonCell {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
override var title: String! { func setAttributedTitle(_ title: NSAttributedString, withColor color: NSColor) {
get { let attrTitle = NSMutableAttributedString(attributedString: title)
return self.attributedTitle.string attrTitle.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attrTitle.length))
}
set (newTitle) {
setTitle(newTitle, withColor: .white)
}
}
func setTitle(_ title: String, withColor color: NSColor) {
let attrTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: NSFont.systemFont(ofSize: 15, weight: .regular), .baselineOffset: 1])
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
self.attributedTitle = attrTitle self.attributedTitle = attrTitle
} }
} }
extension String {
var defaultTouchbarAttributedString: NSAttributedString {
let attrTitle = NSMutableAttributedString(string: self, attributes: [.foregroundColor: NSColor.white, .font: NSFont.systemFont(ofSize: 15, weight: .regular), .baselineOffset: 1])
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: self.count))
return attrTitle
}
}

View File

@ -222,7 +222,7 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
button.imageScaling = .scaleProportionallyDown button.imageScaling = .scaleProportionallyDown
button.imagePosition = .imageLeading button.imagePosition = .imageLeading
if (button.title == "") { if (item.title == "") {
button.imagePosition = .imageOnly button.imagePosition = .imageOnly
} }

View File

@ -10,20 +10,28 @@ import IOKit.ps
import Foundation import Foundation
class BatteryBarItem: CustomButtonTouchBarItem { class BatteryBarItem: CustomButtonTouchBarItem {
private var timer: Timer! private let batteryInfo = BatteryInfo()
init(identifier: NSTouchBarItem.Identifier, onTap: @escaping () -> (), onLongTap: @escaping () -> ()) { init(identifier: NSTouchBarItem.Identifier, onTap: @escaping () -> (), onLongTap: @escaping () -> ()) {
super.init(identifier: identifier, title: " ", onTap: onTap, onLongTap: onLongTap) super.init(identifier: identifier, title: " ", onTap: onTap, onLongTap: onLongTap)
self.view = button
let batteryInfo = BatteryInfo(button: button) batteryInfo.start { [weak self] in
batteryInfo.start() self?.refresh()
batteryInfo.updateInfo() }
self.refresh()
} }
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
func refresh() {
self.attributedTitle = self.batteryInfo.formattedInfo()
}
deinit {
batteryInfo.stop()
}
} }
class BatteryInfo: NSObject { class BatteryInfo: NSObject {
@ -34,17 +42,11 @@ class BatteryInfo: NSObject {
var isCharging: Bool = false var isCharging: Bool = false
var ACPower: String = "" var ACPower: String = ""
var timeRemaining: String = "" var timeRemaining: String = ""
var notifyBlock: ()->() = {}
var button: NSButton
var loop:CFRunLoopSource? var loop:CFRunLoopSource?
init(button: NSButton) { func start(notifyBlock: @escaping ()->()) {
self.button = button self.notifyBlock = notifyBlock
super.init()
self.start()
}
func start() {
let opaque = Unmanaged.passRetained(self).toOpaque() let opaque = Unmanaged.passRetained(self).toOpaque()
let context = UnsafeMutableRawPointer(opaque) let context = UnsafeMutableRawPointer(opaque)
loop = IOPSNotificationCreateRunLoopSource({ (context) in loop = IOPSNotificationCreateRunLoopSource({ (context) in
@ -53,16 +55,17 @@ class BatteryInfo: NSObject {
} }
let watcher = Unmanaged<BatteryInfo>.fromOpaque(ctx).takeUnretainedValue() let watcher = Unmanaged<BatteryInfo>.fromOpaque(ctx).takeUnretainedValue()
watcher.updateInfo() watcher.notifyBlock()
}, context).takeRetainedValue() as CFRunLoopSource }, context).takeRetainedValue() as CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode) CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
} }
func stop() { func stop() {
if !(self.loop != nil) { self.notifyBlock = {}
guard let loop = self.loop else {
return return
} }
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), self.loop, CFRunLoopMode.defaultMode) CFRunLoopRemoveSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
self.loop = nil self.loop = nil
} }
@ -114,7 +117,7 @@ class BatteryInfo: NSObject {
return "" return ""
} }
public func updateInfo() { public func formattedInfo() -> NSAttributedString {
var title = "" var title = ""
self.getPSInfo() self.getPSInfo()
@ -134,12 +137,11 @@ class BatteryInfo: NSObject {
color = NSColor.red color = NSColor.red
} }
let regularFont = button.attributedTitle.attribute(.font, at: 0, effectiveRange: nil) as? NSFont ?? NSFont.systemFont(ofSize: 15) let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: NSFont.systemFont(ofSize: 15), .baselineOffset: 1])
let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: regularFont, .baselineOffset: 1])
let newTitleSecond = NSMutableAttributedString(string: timeRemaining as String, attributes: [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 8, weight: .regular), NSAttributedStringKey.baselineOffset: 7]) let newTitleSecond = NSMutableAttributedString(string: timeRemaining as String, attributes: [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 8, weight: .regular), NSAttributedStringKey.baselineOffset: 7])
newTitle.append(newTitleSecond) newTitle.append(newTitleSecond)
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count)) newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
button.attributedTitle = newTitle return newTitle
} }
} }

View File

@ -58,8 +58,9 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
if (iconImage != nil) { if (iconImage != nil) {
self.button.cell?.image = iconImage self.button.cell?.image = iconImage
self.button.cell?.image?.size = buttonSize self.button.cell?.image?.size = buttonSize
self.title = ""
} else { } else {
self.button.title = currentSource.name self.title = currentSource.name
} }
} }

View File

@ -19,7 +19,7 @@ class TimeTouchBarItem: CustomButtonTouchBarItem {
} }
@objc func updateTime() { @objc func updateTime() {
button.title = self.dateFormatter.string(from: Date()) self.title = self.dateFormatter.string(from: Date())
} }
} }

View File

@ -117,7 +117,7 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
} }
func setWeather(text: String) { func setWeather(text: String) {
button.title = text self.title = text
} }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {