mirror of
https://github.com/Toxblh/MTMR.git
synced 2026-01-11 17:38:38 +00:00
code format
This commit is contained in:
parent
8554dfeb5e
commit
86954a7981
@ -16,13 +16,13 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
|
|
||||||
private var fileSystemSource: DispatchSourceFileSystemObject?
|
private var fileSystemSource: DispatchSourceFileSystemObject?
|
||||||
|
|
||||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
func applicationDidFinishLaunching(_: Notification) {
|
||||||
// Configure Sparkle
|
// Configure Sparkle
|
||||||
SUUpdater.shared().automaticallyDownloadsUpdates = false
|
SUUpdater.shared().automaticallyDownloadsUpdates = false
|
||||||
SUUpdater.shared().automaticallyChecksForUpdates = true
|
SUUpdater.shared().automaticallyChecksForUpdates = true
|
||||||
SUUpdater.shared().checkForUpdatesInBackground()
|
SUUpdater.shared().checkForUpdatesInBackground()
|
||||||
|
|
||||||
let _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary)
|
AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary)
|
||||||
|
|
||||||
TouchBarController.shared.setupControlStripPresence()
|
TouchBarController.shared.setupControlStripPresence()
|
||||||
|
|
||||||
@ -38,27 +38,23 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func applicationWillTerminate(_ aNotification: Notification) {
|
func applicationWillTerminate(_: Notification) {}
|
||||||
|
|
||||||
}
|
@objc func updateIsBlockedApp() {
|
||||||
|
|
||||||
@objc func updateIsBlockedApp() -> Void {
|
|
||||||
var blacklistAppIdentifiers: [String] = []
|
var blacklistAppIdentifiers: [String] = []
|
||||||
if let blackListed = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.blackListedApps") {
|
if let blackListed = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.blackListedApps") {
|
||||||
blacklistAppIdentifiers = blackListed
|
blacklistAppIdentifiers = blackListed
|
||||||
}
|
}
|
||||||
var frontmostApplicationIdentifier: String? {
|
var frontmostApplicationIdentifier: String? {
|
||||||
get {
|
|
||||||
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
||||||
return frontmostId
|
return frontmostId
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
self.isBlockedApp = blacklistAppIdentifiers.index(of: frontmostApplicationIdentifier!) != nil
|
isBlockedApp = blacklistAppIdentifiers.index(of: frontmostApplicationIdentifier!) != nil
|
||||||
createMenu()
|
createMenu()
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func openPreferences(_ sender: Any?) {
|
@objc func openPreferences(_: Any?) {
|
||||||
let task = Process()
|
let task = Process()
|
||||||
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
|
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
|
||||||
let presetPath = appSupportDirectory.appending("/items.json")
|
let presetPath = appSupportDirectory.appending("/items.json")
|
||||||
@ -67,13 +63,13 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
task.launch()
|
task.launch()
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func toggleControlStrip(_ sender: Any?) {
|
@objc func toggleControlStrip(_: Any?) {
|
||||||
TouchBarController.shared.showControlStripState = !TouchBarController.shared.showControlStripState
|
TouchBarController.shared.showControlStripState = !TouchBarController.shared.showControlStripState
|
||||||
TouchBarController.shared.resetControlStrip()
|
TouchBarController.shared.resetControlStrip()
|
||||||
createMenu()
|
createMenu()
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func toggleBlackListedApp(_ sender: Any?) {
|
@objc func toggleBlackListedApp(_: Any?) {
|
||||||
let appIdentifier = TouchBarController.shared.frontmostApplicationIdentifier
|
let appIdentifier = TouchBarController.shared.frontmostApplicationIdentifier
|
||||||
if appIdentifier != nil {
|
if appIdentifier != nil {
|
||||||
if let index = TouchBarController.shared.blacklistAppIdentifiers.index(of: appIdentifier!) {
|
if let index = TouchBarController.shared.blacklistAppIdentifiers.index(of: appIdentifier!) {
|
||||||
@ -90,8 +86,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func openPreset(_ sender: Any?) {
|
@objc func openPreset(_: Any?) {
|
||||||
let dialog = NSOpenPanel();
|
let dialog = NSOpenPanel()
|
||||||
|
|
||||||
dialog.title = "Choose a items.json file"
|
dialog.title = "Choose a items.json file"
|
||||||
dialog.showsResizeIndicator = true
|
dialog.showsResizeIndicator = true
|
||||||
@ -107,7 +103,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func toggleStartAtLogin(_ sender: Any?) {
|
@objc func toggleStartAtLogin(_: Any?) {
|
||||||
LaunchAtLoginController().setLaunchAtLogin(!LaunchAtLoginController().launchAtLogin, for: NSURL.fileURL(withPath: Bundle.main.bundlePath))
|
LaunchAtLoginController().setLaunchAtLogin(!LaunchAtLoginController().launchAtLogin, for: NSURL.fileURL(withPath: Bundle.main.bundlePath))
|
||||||
createMenu()
|
createMenu()
|
||||||
}
|
}
|
||||||
@ -119,7 +115,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
startAtLogin.state = LaunchAtLoginController().launchAtLogin ? .on : .off
|
startAtLogin.state = LaunchAtLoginController().launchAtLogin ? .on : .off
|
||||||
|
|
||||||
let toggleBlackList = NSMenuItem(title: "Toggle current app in blacklist", action: #selector(toggleBlackListedApp(_:)), keyEquivalent: "B")
|
let toggleBlackList = NSMenuItem(title: "Toggle current app in blacklist", action: #selector(toggleBlackListedApp(_:)), keyEquivalent: "B")
|
||||||
toggleBlackList.state = self.isBlockedApp ? .on : .off
|
toggleBlackList.state = isBlockedApp ? .on : .off
|
||||||
|
|
||||||
let hideControlStrip = NSMenuItem(title: "Hide Control Strip", action: #selector(toggleControlStrip(_:)), keyEquivalent: "T")
|
let hideControlStrip = NSMenuItem(title: "Hide Control Strip", action: #selector(toggleControlStrip(_:)), keyEquivalent: "T")
|
||||||
hideControlStrip.state = TouchBarController.shared.showControlStripState ? .off : .on
|
hideControlStrip.state = TouchBarController.shared.showControlStripState ? .off : .on
|
||||||
@ -146,20 +142,19 @@ class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
|
|
||||||
let fd = open(file.path, O_EVTONLY)
|
let fd = open(file.path, O_EVTONLY)
|
||||||
|
|
||||||
self.fileSystemSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: DispatchQueue(label: "DefaultConfigChanged"))
|
fileSystemSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: DispatchQueue(label: "DefaultConfigChanged"))
|
||||||
|
|
||||||
self.fileSystemSource?.setEventHandler(handler: {
|
fileSystemSource?.setEventHandler(handler: {
|
||||||
print("Config changed, reloading...")
|
print("Config changed, reloading...")
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
TouchBarController.shared.reloadPreset(path: file.path)
|
TouchBarController.shared.reloadPreset(path: file.path)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
self.fileSystemSource?.setCancelHandler(handler: {
|
fileSystemSource?.setCancelHandler(handler: {
|
||||||
close(fd)
|
close(fd)
|
||||||
})
|
})
|
||||||
|
|
||||||
self.fileSystemSource?.resume()
|
fileSystemSource?.resume()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -8,13 +8,13 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
|||||||
init?(identifier: NSTouchBarItem.Identifier, source: SourceProtocol, interval: TimeInterval) {
|
init?(identifier: NSTouchBarItem.Identifier, source: SourceProtocol, interval: TimeInterval) {
|
||||||
self.interval = interval
|
self.interval = interval
|
||||||
super.init(identifier: identifier, title: "⏳")
|
super.init(identifier: identifier, title: "⏳")
|
||||||
self.forceHideConstraint = self.view.widthAnchor.constraint(equalToConstant: 0)
|
forceHideConstraint = view.widthAnchor.constraint(equalToConstant: 0)
|
||||||
guard let script = source.appleScript else {
|
guard let script = source.appleScript else {
|
||||||
self.title = "no script"
|
title = "no script"
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
self.script = script
|
self.script = script
|
||||||
self.isBordered = false
|
isBordered = false
|
||||||
DispatchQueue.appleScriptQueue.async {
|
DispatchQueue.appleScriptQueue.async {
|
||||||
var error: NSDictionary?
|
var error: NSDictionary?
|
||||||
guard script.compileAndReturnError(&error) else {
|
guard script.compileAndReturnError(&error) else {
|
||||||
@ -30,15 +30,15 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func refreshAndSchedule() {
|
func refreshAndSchedule() {
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
print("refresh happened (interval \(self.interval)), self \(self.identifier.rawValue))")
|
print("refresh happened (interval \(interval)), self \(identifier.rawValue))")
|
||||||
#endif
|
#endif
|
||||||
let scriptResult = self.execute()
|
let scriptResult = execute()
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.title = scriptResult
|
self.title = scriptResult
|
||||||
self.forceHideConstraint.isActive = scriptResult == ""
|
self.forceHideConstraint.isActive = scriptResult == ""
|
||||||
@ -46,7 +46,7 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
|||||||
print("did set new script result title \(scriptResult)")
|
print("did set new script result title \(scriptResult)")
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
DispatchQueue.appleScriptQueue.asyncAfter(deadline: .now() + self.interval) { [weak self] in
|
DispatchQueue.appleScriptQueue.asyncAfter(deadline: .now() + interval) { [weak self] in
|
||||||
self?.refreshAndSchedule()
|
self?.refreshAndSchedule()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -60,7 +60,6 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
return output.stringValue ?? ""
|
return output.stringValue ?? ""
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension DispatchQueue {
|
extension DispatchQueue {
|
||||||
|
|||||||
@ -9,15 +9,15 @@
|
|||||||
import Cocoa
|
import Cocoa
|
||||||
|
|
||||||
class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
||||||
var tapClosure: (() -> ())?
|
var tapClosure: (() -> Void)?
|
||||||
var longTapClosure: (() -> ())?
|
var longTapClosure: (() -> Void)?
|
||||||
private var button: NSButton!
|
private var button: NSButton!
|
||||||
|
|
||||||
private var singleClick: NSClickGestureRecognizer!
|
private var singleClick: NSClickGestureRecognizer!
|
||||||
private var longClick: NSPressGestureRecognizer!
|
private var longClick: NSPressGestureRecognizer!
|
||||||
|
|
||||||
init(identifier: NSTouchBarItem.Identifier, title: String) {
|
init(identifier: NSTouchBarItem.Identifier, title: String) {
|
||||||
self.attributedTitle = title.defaultTouchbarAttributedString
|
attributedTitle = title.defaultTouchbarAttributedString
|
||||||
|
|
||||||
super.init(identifier: identifier)
|
super.init(identifier: identifier)
|
||||||
button = CustomHeightButton(title: title, target: nil, action: nil)
|
button = CustomHeightButton(title: title, target: nil, action: nil)
|
||||||
@ -34,7 +34,7 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
|
|||||||
button.attributedTitle = attributedTitle
|
button.attributedTitle = attributedTitle
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,17 +52,17 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
|
|||||||
|
|
||||||
var title: String {
|
var title: String {
|
||||||
get {
|
get {
|
||||||
return self.attributedTitle.string
|
return attributedTitle.string
|
||||||
}
|
}
|
||||||
set {
|
set {
|
||||||
self.attributedTitle = newValue.defaultTouchbarAttributedString
|
attributedTitle = newValue.defaultTouchbarAttributedString
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var attributedTitle: NSAttributedString {
|
var attributedTitle: NSAttributedString {
|
||||||
didSet {
|
didSet {
|
||||||
self.button?.imagePosition = attributedTitle.length > 0 ? .imageLeading : .imageOnly
|
button?.imagePosition = attributedTitle.length > 0 ? .imageLeading : .imageOnly
|
||||||
self.button?.attributedTitle = attributedTitle
|
button?.attributedTitle = attributedTitle
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -88,12 +88,12 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
|
|||||||
button.imageScaling = .scaleProportionallyDown
|
button.imageScaling = .scaleProportionallyDown
|
||||||
button.imageHugsTitle = true
|
button.imageHugsTitle = true
|
||||||
button.attributedTitle = title
|
button.attributedTitle = title
|
||||||
self.button?.imagePosition = title.length > 0 ? .imageLeading : .imageOnly
|
button?.imagePosition = title.length > 0 ? .imageLeading : .imageOnly
|
||||||
button.image = image
|
button.image = image
|
||||||
self.view = button
|
view = button
|
||||||
|
|
||||||
self.view.addGestureRecognizer(longClick)
|
view.addGestureRecognizer(longClick)
|
||||||
self.view.addGestureRecognizer(singleClick)
|
view.addGestureRecognizer(singleClick)
|
||||||
}
|
}
|
||||||
|
|
||||||
func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: NSGestureRecognizer) -> Bool {
|
func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: NSGestureRecognizer) -> Bool {
|
||||||
@ -108,7 +108,7 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
|
|||||||
switch gr.state {
|
switch gr.state {
|
||||||
case .ended:
|
case .ended:
|
||||||
hf.tap(strong: 2)
|
hf.tap(strong: 2)
|
||||||
self.tapClosure?()
|
tapClosure?()
|
||||||
break
|
break
|
||||||
default:
|
default:
|
||||||
break
|
break
|
||||||
@ -130,19 +130,16 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
|
|||||||
break
|
break
|
||||||
default:
|
default:
|
||||||
break
|
break
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class CustomHeightButton: NSButton {
|
class CustomHeightButton: NSButton {
|
||||||
|
|
||||||
override var intrinsicContentSize: NSSize {
|
override var intrinsicContentSize: NSSize {
|
||||||
var size = super.intrinsicContentSize
|
var size = super.intrinsicContentSize
|
||||||
size.height = 30
|
size.height = 30
|
||||||
return size
|
return size
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class CustomButtonCell: NSButtonCell {
|
class CustomButtonCell: NSButtonCell {
|
||||||
@ -155,32 +152,30 @@ class CustomButtonCell: NSButtonCell {
|
|||||||
|
|
||||||
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 !isBordered {
|
||||||
if flag {
|
if flag {
|
||||||
self.setAttributedTitle(self.attributedTitle, withColor: .lightGray)
|
setAttributedTitle(attributedTitle, withColor: .lightGray)
|
||||||
} else if let parentItem = self.parentItem {
|
} else if let parentItem = self.parentItem {
|
||||||
self.attributedTitle = parentItem.attributedTitle
|
attributedTitle = parentItem.attributedTitle
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
required init(coder: NSCoder) {
|
required init(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func setAttributedTitle(_ title: NSAttributedString, withColor color: NSColor) {
|
func setAttributedTitle(_ title: NSAttributedString, withColor color: NSColor) {
|
||||||
let attrTitle = NSMutableAttributedString(attributedString: title)
|
let attrTitle = NSMutableAttributedString(attributedString: title)
|
||||||
attrTitle.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attrTitle.length))
|
attrTitle.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attrTitle.length))
|
||||||
self.attributedTitle = attrTitle
|
attributedTitle = attrTitle
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension String {
|
extension String {
|
||||||
var defaultTouchbarAttributedString: NSAttributedString {
|
var defaultTouchbarAttributedString: NSAttributedString {
|
||||||
let attrTitle = NSMutableAttributedString(string: self, attributes: [.foregroundColor: NSColor.white, .font: NSFont.systemFont(ofSize: 15, weight: .regular), .baselineOffset: 1])
|
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))
|
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: count))
|
||||||
return attrTitle
|
return attrTitle
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -22,20 +22,20 @@ class CustomSliderCell: NSSliderCell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
init(knob: NSImage?) {
|
init(knob: NSImage?) {
|
||||||
knobImage = knob;
|
knobImage = knob
|
||||||
super.init()
|
super.init()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func drawKnob(_ knobRect: NSRect) {
|
override func drawKnob(_ knobRect: NSRect) {
|
||||||
if (knobImage == nil) {
|
if knobImage == nil {
|
||||||
super.drawKnob(knobRect)
|
super.drawKnob(knobRect)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_currentKnobRect = knobRect;
|
_currentKnobRect = knobRect
|
||||||
drawBar(inside: _barRect, flipped: true)
|
drawBar(inside: _barRect, flipped: true)
|
||||||
|
|
||||||
let x = (knobRect.origin.x * (_barRect.size.width - (knobImage.size.width - knobRect.size.width)) / _barRect.size.width)+1;
|
let x = (knobRect.origin.x * (_barRect.size.width - (knobImage.size.width - knobRect.size.width)) / _barRect.size.width) + 1
|
||||||
let y = knobRect.origin.y + 3
|
let y = knobRect.origin.y + 3
|
||||||
|
|
||||||
knobImage.draw(
|
knobImage.draw(
|
||||||
@ -46,7 +46,7 @@ class CustomSliderCell: NSSliderCell {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override func drawBar(inside aRect: NSRect, flipped: Bool) {
|
override func drawBar(inside aRect: NSRect, flipped _: Bool) {
|
||||||
_barRect = aRect
|
_barRect = aRect
|
||||||
|
|
||||||
let barRadius = CGFloat(2)
|
let barRadius = CGFloat(2)
|
||||||
@ -60,7 +60,7 @@ class CustomSliderCell: NSSliderCell {
|
|||||||
|
|
||||||
var activeRect = bgRect
|
var activeRect = bgRect
|
||||||
|
|
||||||
activeRect.size.width = CGFloat((Double(bgRect.size.width) / (self.maxValue - self.minValue)) * self.doubleValue)
|
activeRect.size.width = CGFloat((Double(bgRect.size.width) / (maxValue - minValue)) * doubleValue)
|
||||||
let active = NSBezierPath(roundedRect: activeRect, xRadius: barRadius, yRadius: barRadius)
|
let active = NSBezierPath(roundedRect: activeRect, xRadius: barRadius, yRadius: barRadius)
|
||||||
NSColor.darkGray.setFill()
|
NSColor.darkGray.setFill()
|
||||||
active.fill()
|
active.fill()
|
||||||
@ -68,7 +68,6 @@ class CustomSliderCell: NSSliderCell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class CustomSlider: NSSlider {
|
class CustomSlider: NSSlider {
|
||||||
|
|
||||||
var currentValue: CGFloat = 0
|
var currentValue: CGFloat = 0
|
||||||
|
|
||||||
override func setNeedsDisplay(_ invalidRect: NSRect) {
|
override func setNeedsDisplay(_ invalidRect: NSRect) {
|
||||||
@ -77,7 +76,7 @@ class CustomSlider:NSSlider {
|
|||||||
|
|
||||||
override func awakeFromNib() {
|
override func awakeFromNib() {
|
||||||
super.awakeFromNib()
|
super.awakeFromNib()
|
||||||
if ((self.cell?.isKind(of: CustomSliderCell.self)) == false) {
|
if (cell?.isKind(of: CustomSliderCell.self)) == false {
|
||||||
let cell: CustomSliderCell = CustomSliderCell()
|
let cell: CustomSliderCell = CustomSliderCell()
|
||||||
self.cell = cell
|
self.cell = cell
|
||||||
}
|
}
|
||||||
@ -85,7 +84,7 @@ class CustomSlider:NSSlider {
|
|||||||
|
|
||||||
convenience init(knob: NSImage) {
|
convenience init(knob: NSImage) {
|
||||||
self.init()
|
self.init()
|
||||||
self.cell = CustomSliderCell(knob: knob)
|
cell = CustomSliderCell(knob: knob)
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder: NSCoder) {
|
||||||
|
|||||||
@ -11,9 +11,7 @@ import Foundation
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
extension String {
|
extension String {
|
||||||
|
|
||||||
var ifNotEmpty: String? {
|
var ifNotEmpty: String? {
|
||||||
return self.count > 0 ? self : nil
|
return count > 0 ? self : nil
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,7 +10,7 @@ import IOKit
|
|||||||
|
|
||||||
class HapticFeedback {
|
class HapticFeedback {
|
||||||
private var actuatorRef: CFTypeRef?
|
private var actuatorRef: CFTypeRef?
|
||||||
private var deviceID: UInt64 = 0x200000001000000
|
private var deviceID: UInt64 = 0x200_0000_0100_0000
|
||||||
private var error: IOReturn = 0
|
private var error: IOReturn = 0
|
||||||
|
|
||||||
// Don't know how to do strong is enum one of
|
// Don't know how to do strong is enum one of
|
||||||
@ -24,7 +24,7 @@ class HapticFeedback {
|
|||||||
// 16 nothing
|
// 16 nothing
|
||||||
// you can get a plist `otool -s __TEXT __tpad_act_plist /System/Library/PrivateFrameworks/MultitouchSupport.framework/Versions/Current/MultitouchSupport|tail -n +3|awk -F'\t' '{print $2}'|xxd -r -p`
|
// you can get a plist `otool -s __TEXT __tpad_act_plist /System/Library/PrivateFrameworks/MultitouchSupport.framework/Versions/Current/MultitouchSupport|tail -n +3|awk -F'\t' '{print $2}'|xxd -r -p`
|
||||||
|
|
||||||
func tap(strong:Int32) -> Void {
|
func tap(strong: Int32) {
|
||||||
actuatorRef = MTActuatorCreateFromDeviceID(deviceID).takeRetainedValue()
|
actuatorRef = MTActuatorCreateFromDeviceID(deviceID).takeRetainedValue()
|
||||||
|
|
||||||
guard actuatorRef != nil else {
|
guard actuatorRef != nil else {
|
||||||
@ -53,5 +53,3 @@ class HapticFeedback {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -19,7 +19,7 @@
|
|||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>0.18.5</string>
|
<string>0.18.5</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>79</string>
|
<string>82</string>
|
||||||
<key>LSApplicationCategoryType</key>
|
<key>LSApplicationCategoryType</key>
|
||||||
<string>public.app-category.utilities</string>
|
<string>public.app-category.utilities</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
import Foundation
|
|
||||||
import AppKit
|
import AppKit
|
||||||
|
import Foundation
|
||||||
|
|
||||||
extension Data {
|
extension Data {
|
||||||
func barItemDefinitions() -> [BarItemDefinition]? {
|
func barItemDefinitions() -> [BarItemDefinition]? {
|
||||||
return try? JSONDecoder().decode([BarItemDefinition].self, from: self.utf8string!.stripComments().data(using: .utf8)!)
|
return try? JSONDecoder().decode([BarItemDefinition].self, from: utf8string!.stripComments().data(using: .utf8)!)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,64 +38,123 @@ struct BarItemDefinition: Decodable {
|
|||||||
self.init(type: .staticButton(title: "unknown"), action: .none, longAction: .none, additionalParameters: additionalParameters)
|
self.init(type: .staticButton(title: "unknown"), action: .none, longAction: .none, additionalParameters: additionalParameters)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class SupportedTypesHolder {
|
class SupportedTypesHolder {
|
||||||
typealias ParametersDecoder = (Decoder) throws -> (item: ItemType, action: ActionType, longAction: LongActionType, parameters: [GeneralParameters.CodingKeys: GeneralParameter])
|
typealias ParametersDecoder = (Decoder) throws -> (item: ItemType, action: ActionType, longAction: LongActionType, parameters: [GeneralParameters.CodingKeys: GeneralParameter])
|
||||||
private var supportedTypes: [String: ParametersDecoder] = [
|
private var supportedTypes: [String: ParametersDecoder] = [
|
||||||
"escape": { _ in return (item: .staticButton(title: "esc"), action: .keyPress(keycode: 53), longAction: .none, parameters: [.align: .align(.left)]) },
|
"escape": { _ in (
|
||||||
|
item: .staticButton(title: "esc"),
|
||||||
|
action: .keyPress(keycode: 53),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.align: .align(.left)]
|
||||||
|
) },
|
||||||
|
|
||||||
"delete": { _ in return (item: .staticButton(title: "del"), action: .keyPress(keycode: 117), longAction: .none, parameters: [:])},
|
"delete": { _ in (
|
||||||
|
item: .staticButton(title: "del"),
|
||||||
|
action: .keyPress(keycode: 117),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
) },
|
||||||
|
|
||||||
"brightnessUp": { _ in
|
"brightnessUp": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessUp"))
|
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessUp"))
|
||||||
return (item: .staticButton(title: ""), action: .keyPress(keycode: 144), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .keyPress(keycode: 144),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"brightnessDown": { _ in
|
"brightnessDown": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessDown"))
|
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessDown"))
|
||||||
return (item: .staticButton(title: ""), action: .keyPress(keycode: 145), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .keyPress(keycode: 145),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"illuminationUp": { _ in
|
"illuminationUp": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "ill_up"))
|
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "ill_up"))
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_ILLUMINATION_UP), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_ILLUMINATION_UP),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"illuminationDown": { _ in
|
"illuminationDown": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "ill_down"))
|
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "ill_down"))
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_ILLUMINATION_DOWN), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_ILLUMINATION_DOWN),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"volumeDown": { _ in
|
"volumeDown": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarVolumeDownTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarVolumeDownTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_SOUND_DOWN), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_SOUND_DOWN),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"volumeUp": { _ in
|
"volumeUp": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarVolumeUpTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarVolumeUpTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_SOUND_UP), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_SOUND_UP),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"mute": { _ in
|
"mute": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarAudioOutputMuteTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarAudioOutputMuteTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_MUTE), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_MUTE),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"previous": { _ in
|
"previous": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarRewindTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarRewindTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_PREVIOUS), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_PREVIOUS),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"play": { _ in
|
"play": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarPlayPauseTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarPlayPauseTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_PLAY), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_PLAY),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"next": { _ in
|
"next": { _ in
|
||||||
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarFastForwardTemplateName)!)
|
let imageParameter = GeneralParameter.image(source: NSImage(named: NSImage.touchBarFastForwardTemplateName)!)
|
||||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_NEXT), longAction: .none, parameters: [.image: imageParameter])
|
return (
|
||||||
|
item: .staticButton(title: ""),
|
||||||
|
action: .hidKey(keycode: NX_KEYTYPE_NEXT),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: imageParameter]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"weather": { decoder in
|
"weather": { decoder in
|
||||||
@ -107,7 +166,12 @@ class SupportedTypesHolder {
|
|||||||
let icon_type = try container.decodeIfPresent(String.self, forKey: .icon_type)
|
let icon_type = try container.decodeIfPresent(String.self, forKey: .icon_type)
|
||||||
let action = try ActionType(from: decoder)
|
let action = try ActionType(from: decoder)
|
||||||
let longAction = try LongActionType(from: decoder)
|
let longAction = try LongActionType(from: decoder)
|
||||||
return (item: .weather(interval: interval ?? 1800.00, units: units ?? "metric", api_key: api_key ?? "32c4256d09a4c52b38aecddba7a078f6", icon_type: icon_type ?? "text"), action: action, longAction: longAction, parameters: [:])
|
return (
|
||||||
|
item: .weather(interval: interval ?? 1800.00, units: units ?? "metric", api_key: api_key ?? "32c4256d09a4c52b38aecddba7a078f6", icon_type: icon_type ?? "text"),
|
||||||
|
action,
|
||||||
|
longAction,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"currency": { decoder in
|
"currency": { decoder in
|
||||||
@ -118,24 +182,49 @@ class SupportedTypesHolder {
|
|||||||
let to = try container.decodeIfPresent(String.self, forKey: .to)
|
let to = try container.decodeIfPresent(String.self, forKey: .to)
|
||||||
let action = try ActionType(from: decoder)
|
let action = try ActionType(from: decoder)
|
||||||
let longAction = try LongActionType(from: decoder)
|
let longAction = try LongActionType(from: decoder)
|
||||||
return (item: .currency(interval: interval ?? 600.00, from: from ?? "RUB", to: to ?? "USD"), action: action, longAction: longAction, parameters: [:])
|
return (
|
||||||
|
item: .currency(interval: interval ?? 600.00, from: from ?? "RUB", to: to ?? "USD"),
|
||||||
|
action,
|
||||||
|
longAction,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"dock": { decoder in
|
"dock": { _ in
|
||||||
return (item: .dock(), action: .none, longAction: .none, parameters: [:])
|
(
|
||||||
|
item: .dock(),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"inputsource": { decoder in
|
"inputsource": { _ in
|
||||||
return (item: .inputsource(), action: .none, longAction: .none, parameters: [:])
|
(
|
||||||
|
item: .inputsource(),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
"volume": { decoder in
|
"volume": { decoder in
|
||||||
enum CodingKeys: String, CodingKey { case image }
|
enum CodingKeys: String, CodingKey { case image }
|
||||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
||||||
return (item: .volume(), action: .none, longAction: .none, parameters: [.image: .image(source: img)])
|
return (
|
||||||
|
item: .volume(),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: .image(source: img)]
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
return (item: .volume(), action: .none, longAction: .none, parameters: [:])
|
return (
|
||||||
|
item: .volume(),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -144,15 +233,35 @@ class SupportedTypesHolder {
|
|||||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||||
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
||||||
return (item: .brightness(refreshInterval: interval ?? 0.5), action: .none, longAction: .none, parameters: [.image: .image(source: img)])
|
return (
|
||||||
|
item: .brightness(refreshInterval: interval ?? 0.5),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [.image: .image(source: img)]
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
return (item: .brightness(refreshInterval: interval ?? 0.5), action: .none, longAction: .none, parameters: [:])
|
return (
|
||||||
|
item: .brightness(refreshInterval: interval ?? 0.5),
|
||||||
|
action: .none,
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
"sleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["sleepnow"]), longAction: .none, parameters: [:]) },
|
"sleep": { _ in (
|
||||||
|
item: .staticButton(title: "☕️"),
|
||||||
|
action: .shellScript(executable: "/usr/bin/pmset", parameters: ["sleepnow"]),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
) },
|
||||||
|
|
||||||
"displaySleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["displaysleepnow"]), longAction: .none, parameters: [:])},
|
"displaySleep": { _ in (
|
||||||
|
item: .staticButton(title: "☕️"),
|
||||||
|
action: .shellScript(executable: "/usr/bin/pmset", parameters: ["displaysleepnow"]),
|
||||||
|
longAction: .none,
|
||||||
|
parameters: [:]
|
||||||
|
) },
|
||||||
|
|
||||||
"music": { decoder in
|
"music": { decoder in
|
||||||
enum CodingKeys: String, CodingKey { case refreshInterval }
|
enum CodingKeys: String, CodingKey { case refreshInterval }
|
||||||
@ -179,7 +288,7 @@ class SupportedTypesHolder {
|
|||||||
},
|
},
|
||||||
|
|
||||||
"nightShift": { _ in
|
"nightShift": { _ in
|
||||||
return (
|
(
|
||||||
item: .nightShift(),
|
item: .nightShift(),
|
||||||
action: .none,
|
action: .none,
|
||||||
longAction: .none,
|
longAction: .none,
|
||||||
@ -188,21 +297,20 @@ class SupportedTypesHolder {
|
|||||||
},
|
},
|
||||||
|
|
||||||
"dnd": { _ in
|
"dnd": { _ in
|
||||||
return (
|
(
|
||||||
item: .dnd(),
|
item: .dnd(),
|
||||||
action: .none,
|
action: .none,
|
||||||
longAction: .none,
|
longAction: .none,
|
||||||
parameters: [:]
|
parameters: [:]
|
||||||
)
|
)
|
||||||
|
},
|
||||||
}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
static let sharedInstance = SupportedTypesHolder()
|
static let sharedInstance = SupportedTypesHolder()
|
||||||
|
|
||||||
func lookup(by type: String) -> ParametersDecoder {
|
func lookup(by type: String) -> ParametersDecoder {
|
||||||
return supportedTypes[type] ?? { decoder in
|
return supportedTypes[type] ?? { decoder in
|
||||||
return (item: try ItemType(from: decoder), action: try ActionType(from: decoder), longAction: try LongActionType(from: decoder), parameters: [:])
|
(item: try ItemType(from: decoder), action: try ActionType(from: decoder), longAction: try LongActionType(from: decoder), parameters: [:])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -212,7 +320,12 @@ class SupportedTypesHolder {
|
|||||||
|
|
||||||
func register(typename: String, item: ItemType, action: ActionType, longAction: LongActionType) {
|
func register(typename: String, item: ItemType, action: ActionType, longAction: LongActionType) {
|
||||||
register(typename: typename) { _ in
|
register(typename: typename) { _ in
|
||||||
return (item: item, action: action, longAction: longAction, parameters: [:])
|
(
|
||||||
|
item: item,
|
||||||
|
action,
|
||||||
|
longAction,
|
||||||
|
parameters: [:]
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -271,7 +384,6 @@ enum ItemType: Decodable {
|
|||||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
let type = try container.decode(ItemTypeRaw.self, forKey: .type)
|
let type = try container.decode(ItemTypeRaw.self, forKey: .type)
|
||||||
switch type {
|
switch type {
|
||||||
|
|
||||||
case .appleScriptTitledButton:
|
case .appleScriptTitledButton:
|
||||||
let source = try container.decode(Source.self, forKey: .source)
|
let source = try container.decode(Source.self, forKey: .source)
|
||||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
|
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
|
||||||
@ -337,7 +449,7 @@ enum ActionType: Decodable {
|
|||||||
case keyPress(keycode: Int)
|
case keyPress(keycode: Int)
|
||||||
case appleScript(source: SourceProtocol)
|
case appleScript(source: SourceProtocol)
|
||||||
case shellScript(executable: String, parameters: [String])
|
case shellScript(executable: String, parameters: [String])
|
||||||
case custom(closure: ()->())
|
case custom(closure: () -> Void)
|
||||||
case openUrl(url: String)
|
case openUrl(url: String)
|
||||||
|
|
||||||
private enum CodingKeys: String, CodingKey {
|
private enum CodingKeys: String, CodingKey {
|
||||||
@ -389,14 +501,13 @@ enum ActionType: Decodable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
enum LongActionType: Decodable {
|
enum LongActionType: Decodable {
|
||||||
case none
|
case none
|
||||||
case hidKey(keycode: Int32)
|
case hidKey(keycode: Int32)
|
||||||
case keyPress(keycode: Int)
|
case keyPress(keycode: Int)
|
||||||
case appleScript(source: SourceProtocol)
|
case appleScript(source: SourceProtocol)
|
||||||
case shellScript(executable: String, parameters: [String])
|
case shellScript(executable: String, parameters: [String])
|
||||||
case custom(closure: ()->())
|
case custom(closure: () -> Void)
|
||||||
case openUrl(url: String)
|
case openUrl(url: String)
|
||||||
|
|
||||||
private enum CodingKeys: String, CodingKey {
|
private enum CodingKeys: String, CodingKey {
|
||||||
@ -448,7 +559,6 @@ enum LongActionType: Decodable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
enum GeneralParameter {
|
enum GeneralParameter {
|
||||||
case width(_: CGFloat)
|
case width(_: CGFloat)
|
||||||
case image(source: SourceProtocol)
|
case image(source: SourceProtocol)
|
||||||
@ -532,7 +642,7 @@ struct Source: Decodable, SourceProtocol {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var appleScript: NSAppleScript? {
|
var appleScript: NSAppleScript? {
|
||||||
return filePath?.fileURL.appleScript ?? self.string?.appleScript
|
return filePath?.fileURL.appleScript ?? string?.appleScript
|
||||||
}
|
}
|
||||||
|
|
||||||
private init(filePath: String?, base64: String?, inline: String?) {
|
private init(filePath: String?, base64: String?, inline: String?) {
|
||||||
@ -577,7 +687,6 @@ extension String {
|
|||||||
var encoding: String.Encoding = .utf8
|
var encoding: String.Encoding = .utf8
|
||||||
return try? String(contentsOfFile: self, usedEncoding: &encoding)
|
return try? String(contentsOfFile: self, usedEncoding: &encoding)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension Data {
|
extension Data {
|
||||||
@ -608,7 +717,7 @@ extension String {
|
|||||||
|
|
||||||
extension URL {
|
extension URL {
|
||||||
var appleScript: NSAppleScript? {
|
var appleScript: NSAppleScript? {
|
||||||
guard FileManager.default.fileExists(atPath: self.path) else { return nil }
|
guard FileManager.default.fileExists(atPath: path) else { return nil }
|
||||||
return NSAppleScript(contentsOf: self, error: nil)
|
return NSAppleScript(contentsOf: self, error: nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,20 +12,20 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
|||||||
stackView.orientation = .horizontal
|
stackView.orientation = .horizontal
|
||||||
let scrollView = NSScrollView(frame: CGRect(origin: .zero, size: stackView.fittingSize))
|
let scrollView = NSScrollView(frame: CGRect(origin: .zero, size: stackView.fittingSize))
|
||||||
scrollView.documentView = stackView
|
scrollView.documentView = stackView
|
||||||
self.view = scrollView
|
view = scrollView
|
||||||
|
|
||||||
let twofingers = NSPanGestureRecognizer(target: self, action: #selector(twofingersHandler(_:)))
|
let twofingers = NSPanGestureRecognizer(target: self, action: #selector(twofingersHandler(_:)))
|
||||||
twofingers.allowedTouchTypes = .direct
|
twofingers.allowedTouchTypes = .direct
|
||||||
twofingers.numberOfTouchesRequired = 2
|
twofingers.numberOfTouchesRequired = 2
|
||||||
self.view.addGestureRecognizer(twofingers)
|
view.addGestureRecognizer(twofingers)
|
||||||
|
|
||||||
let threefingers = NSPanGestureRecognizer(target: self, action: #selector(threefingersHandler(_:)))
|
let threefingers = NSPanGestureRecognizer(target: self, action: #selector(threefingersHandler(_:)))
|
||||||
threefingers.allowedTouchTypes = .direct
|
threefingers.allowedTouchTypes = .direct
|
||||||
threefingers.numberOfTouchesRequired = 3
|
threefingers.numberOfTouchesRequired = 3
|
||||||
self.view.addGestureRecognizer(threefingers)
|
view.addGestureRecognizer(threefingers)
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,7 +36,7 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
|||||||
case .began:
|
case .began:
|
||||||
twofingersPrev = position
|
twofingersPrev = position
|
||||||
case .changed:
|
case .changed:
|
||||||
if (((position-twofingersPrev) > 10) || ((twofingersPrev-position) > 10)) {
|
if ((position - twofingersPrev) > 10) || ((twofingersPrev - position) > 10) {
|
||||||
if position > twofingersPrev {
|
if position > twofingersPrev {
|
||||||
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
|
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
|
||||||
} else if position < twofingersPrev {
|
} else if position < twofingersPrev {
|
||||||
@ -58,7 +58,7 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
|||||||
case .began:
|
case .began:
|
||||||
threefingersPrev = position
|
threefingersPrev = position
|
||||||
case .changed:
|
case .changed:
|
||||||
if (((position-threefingersPrev) > 15) || ((threefingersPrev-position) > 15)) {
|
if ((position - threefingersPrev) > 15) || ((threefingersPrev - position) > 15) {
|
||||||
if position > threefingersPrev {
|
if position > threefingersPrev {
|
||||||
GenericKeyPress(keyCode: CGKeyCode(144)).send()
|
GenericKeyPress(keyCode: CGKeyCode(144)).send()
|
||||||
} else if position < threefingersPrev {
|
} else if position < threefingersPrev {
|
||||||
|
|||||||
@ -6,7 +6,7 @@
|
|||||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||||
//
|
//
|
||||||
|
|
||||||
func presentSystemModal(_ touchBar: NSTouchBar!, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) -> Void {
|
func presentSystemModal(_ touchBar: NSTouchBar!, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) {
|
||||||
if #available(OSX 10.14, *) {
|
if #available(OSX 10.14, *) {
|
||||||
NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
|
NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
|
||||||
} else {
|
} else {
|
||||||
@ -14,7 +14,7 @@ func presentSystemModal(_ touchBar: NSTouchBar!, systemTrayItemIdentifier identi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func presentSystemModal(_ touchBar: NSTouchBar!, placement: Int64, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) -> Void {
|
func presentSystemModal(_ touchBar: NSTouchBar!, placement: Int64, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) {
|
||||||
if #available(OSX 10.14, *) {
|
if #available(OSX 10.14, *) {
|
||||||
NSTouchBar.presentSystemModalTouchBar(touchBar, placement: placement, systemTrayItemIdentifier: identifier)
|
NSTouchBar.presentSystemModalTouchBar(touchBar, placement: placement, systemTrayItemIdentifier: identifier)
|
||||||
} else {
|
} else {
|
||||||
@ -22,7 +22,7 @@ func presentSystemModal(_ touchBar: NSTouchBar!, placement: Int64, systemTrayIte
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func minimizeSystemModal(_ touchBar: NSTouchBar!) -> Void {
|
func minimizeSystemModal(_ touchBar: NSTouchBar!) {
|
||||||
if #available(OSX 10.14, *) {
|
if #available(OSX 10.14, *) {
|
||||||
NSTouchBar.minimizeSystemModalTouchBar(touchBar)
|
NSTouchBar.minimizeSystemModalTouchBar(touchBar)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@ -8,7 +8,6 @@
|
|||||||
import Cocoa
|
import Cocoa
|
||||||
|
|
||||||
class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource {
|
class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource {
|
||||||
|
|
||||||
private var scrubber: NSScrubber!
|
private var scrubber: NSScrubber!
|
||||||
|
|
||||||
private let hf: HapticFeedback = HapticFeedback()
|
private let hf: HapticFeedback = HapticFeedback()
|
||||||
@ -23,22 +22,20 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
private var runningAppsIdentifiers: [String] = []
|
private var runningAppsIdentifiers: [String] = []
|
||||||
|
|
||||||
private var frontmostApplicationIdentifier: String? {
|
private var frontmostApplicationIdentifier: String? {
|
||||||
get {
|
|
||||||
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
||||||
return frontmostId
|
return frontmostId
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private var applications: [DockItem] = []
|
private var applications: [DockItem] = []
|
||||||
|
|
||||||
override init(identifier: NSTouchBarItem.Identifier) {
|
override init(identifier: NSTouchBarItem.Identifier) {
|
||||||
super.init(identifier: identifier)
|
super.init(identifier: identifier)
|
||||||
|
|
||||||
scrubber = NSScrubber();
|
scrubber = NSScrubber()
|
||||||
scrubber.delegate = self
|
scrubber.delegate = self
|
||||||
scrubber.dataSource = self
|
scrubber.dataSource = self
|
||||||
scrubber.mode = .free // .fixed
|
scrubber.mode = .free // .fixed
|
||||||
let layout = NSScrubberFlowLayout();
|
let layout = NSScrubberFlowLayout()
|
||||||
layout.itemSize = NSSize(width: 36, height: 32)
|
layout.itemSize = NSSize(width: 36, height: 32)
|
||||||
layout.itemSpacing = 2
|
layout.itemSpacing = 2
|
||||||
scrubber.scrubberLayout = layout
|
scrubber.scrubberLayout = layout
|
||||||
@ -54,21 +51,21 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
||||||
|
|
||||||
if let persistent = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.dock.persistent") {
|
if let persistent = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.dock.persistent") {
|
||||||
self.persistentAppIdentifiers = persistent
|
persistentAppIdentifiers = persistent
|
||||||
}
|
}
|
||||||
|
|
||||||
updateRunningApplication()
|
updateRunningApplication()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func activeApplicationChanged(n: Notification) {
|
@objc func activeApplicationChanged(n _: Notification) {
|
||||||
updateRunningApplication()
|
updateRunningApplication()
|
||||||
}
|
}
|
||||||
|
|
||||||
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
|
override func observeValue(forKeyPath _: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?) {
|
||||||
updateRunningApplication()
|
updateRunningApplication()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,7 +83,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
scrubber.selectedIndex = index ?? 0
|
scrubber.selectedIndex = index ?? 0
|
||||||
}
|
}
|
||||||
|
|
||||||
public func numberOfItems(for scrubber: NSScrubber) -> Int {
|
public func numberOfItems(for _: NSScrubber) -> Int {
|
||||||
return applications.count
|
return applications.count
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,7 +102,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
|
|
||||||
let dotView = NSView(frame: .zero)
|
let dotView = NSView(frame: .zero)
|
||||||
dotView.wantsLayer = true
|
dotView.wantsLayer = true
|
||||||
if self.runningAppsIdentifiers.contains(app.bundleIdentifier!) {
|
if runningAppsIdentifiers.contains(app.bundleIdentifier!) {
|
||||||
dotView.layer?.backgroundColor = NSColor.white.cgColor
|
dotView.layer?.backgroundColor = NSColor.white.cgColor
|
||||||
} else {
|
} else {
|
||||||
dotView.layer?.backgroundColor = NSColor.black.cgColor
|
dotView.layer?.backgroundColor = NSColor.black.cgColor
|
||||||
@ -118,44 +115,44 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
public func didBeginInteracting(with scrubber: NSScrubber) {
|
public func didBeginInteracting(with _: NSScrubber) {
|
||||||
stopTimer()
|
stopTimer()
|
||||||
self.ticks = 0
|
ticks = 0
|
||||||
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(checkTimer), userInfo: nil, repeats: true)
|
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(checkTimer), userInfo: nil, repeats: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc private func checkTimer() {
|
@objc private func checkTimer() {
|
||||||
self.ticks += 1
|
ticks += 1
|
||||||
|
|
||||||
if (self.ticks == minTicks) {
|
if ticks == minTicks {
|
||||||
hf.tap(strong: 2)
|
hf.tap(strong: 2)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self.ticks > maxTicks) {
|
if ticks > maxTicks {
|
||||||
stopTimer()
|
stopTimer()
|
||||||
hf.tap(strong: 6)
|
hf.tap(strong: 6)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func stopTimer() {
|
private func stopTimer() {
|
||||||
self.timer?.invalidate()
|
timer?.invalidate()
|
||||||
self.timer = nil
|
timer = nil
|
||||||
self.lastSelected = 0
|
lastSelected = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
public func didCancelInteracting(with scrubber: NSScrubber) {
|
public func didCancelInteracting(with _: NSScrubber) {
|
||||||
stopTimer()
|
stopTimer()
|
||||||
}
|
}
|
||||||
|
|
||||||
public func didFinishInteracting(with scrubber: NSScrubber) {
|
public func didFinishInteracting(with scrubber: NSScrubber) {
|
||||||
stopTimer()
|
stopTimer()
|
||||||
|
|
||||||
if (ticks == 0) {
|
if ticks == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self.ticks >= minTicks && scrubber.selectedIndex > 0) {
|
if ticks >= minTicks && scrubber.selectedIndex > 0 {
|
||||||
self.longPress(selected: scrubber.selectedIndex)
|
longPress(selected: scrubber.selectedIndex)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -176,7 +173,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
private func longPress(selected: Int) {
|
private func longPress(selected: Int) {
|
||||||
let bundleIdentifier = applications[selected].bundleIdentifier
|
let bundleIdentifier = applications[selected].bundleIdentifier
|
||||||
|
|
||||||
if (self.ticks > maxTicks) {
|
if ticks > maxTicks {
|
||||||
if let processIdentifier = applications[selected].pid {
|
if let processIdentifier = applications[selected].pid {
|
||||||
if !(NSRunningApplication(processIdentifier: processIdentifier)?.terminate())! {
|
if !(NSRunningApplication(processIdentifier: processIdentifier)?.terminate())! {
|
||||||
NSRunningApplication(processIdentifier: processIdentifier)?.forceTerminate()
|
NSRunningApplication(processIdentifier: processIdentifier)?.forceTerminate()
|
||||||
@ -185,26 +182,26 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
} else {
|
} else {
|
||||||
hf.tap(strong: 6)
|
hf.tap(strong: 6)
|
||||||
if let index = self.persistentAppIdentifiers.index(of: bundleIdentifier!) {
|
if let index = self.persistentAppIdentifiers.index(of: bundleIdentifier!) {
|
||||||
self.persistentAppIdentifiers.remove(at: index)
|
persistentAppIdentifiers.remove(at: index)
|
||||||
} else {
|
} else {
|
||||||
self.persistentAppIdentifiers.append(bundleIdentifier!)
|
persistentAppIdentifiers.append(bundleIdentifier!)
|
||||||
}
|
}
|
||||||
|
|
||||||
UserDefaults.standard.set(self.persistentAppIdentifiers, forKey: "com.toxblh.mtmr.dock.persistent")
|
UserDefaults.standard.set(persistentAppIdentifiers, forKey: "com.toxblh.mtmr.dock.persistent")
|
||||||
UserDefaults.standard.synchronize()
|
UserDefaults.standard.synchronize()
|
||||||
}
|
}
|
||||||
self.ticks = 0
|
ticks = 0
|
||||||
updateRunningApplication()
|
updateRunningApplication()
|
||||||
}
|
}
|
||||||
|
|
||||||
private func launchedApplications() -> [DockItem] {
|
private func launchedApplications() -> [DockItem] {
|
||||||
self.runningAppsIdentifiers = []
|
runningAppsIdentifiers = []
|
||||||
var returnable: [DockItem] = []
|
var returnable: [DockItem] = []
|
||||||
for app in NSWorkspace.shared.runningApplications {
|
for app in NSWorkspace.shared.runningApplications {
|
||||||
guard app.activationPolicy == NSApplication.ActivationPolicy.regular else { continue }
|
guard app.activationPolicy == NSApplication.ActivationPolicy.regular else { continue }
|
||||||
guard let bundleIdentifier = app.bundleIdentifier else { continue }
|
guard let bundleIdentifier = app.bundleIdentifier else { continue }
|
||||||
|
|
||||||
self.runningAppsIdentifiers.append(bundleIdentifier)
|
runningAppsIdentifiers.append(bundleIdentifier)
|
||||||
|
|
||||||
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier), pid: app.processIdentifier)
|
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier), pid: app.processIdentifier)
|
||||||
returnable.append(dockItem)
|
returnable.append(dockItem)
|
||||||
@ -212,7 +209,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
return returnable
|
return returnable
|
||||||
}
|
}
|
||||||
|
|
||||||
public func getIcon(forBundleIdentifier bundleIdentifier: String? = nil, orPath path: String? = nil, orType type: String? = nil) -> NSImage {
|
public func getIcon(forBundleIdentifier bundleIdentifier: String? = nil, orPath path: String? = nil, orType _: String? = nil) -> NSImage {
|
||||||
if bundleIdentifier != nil {
|
if bundleIdentifier != nil {
|
||||||
if let appPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier!) {
|
if let appPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier!) {
|
||||||
return NSWorkspace.shared.icon(forFile: appPath)
|
return NSWorkspace.shared.icon(forFile: appPath)
|
||||||
@ -227,12 +224,11 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
|
|||||||
return genericIcon ?? NSImage(size: .zero)
|
return genericIcon ?? NSImage(size: .zero)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public func getDockPersistentAppsList() -> [DockItem] {
|
public func getDockPersistentAppsList() -> [DockItem] {
|
||||||
var returnable: [DockItem] = []
|
var returnable: [DockItem] = []
|
||||||
|
|
||||||
for bundleIdentifier in persistentAppIdentifiers {
|
for bundleIdentifier in persistentAppIdentifiers {
|
||||||
if !self.runningAppsIdentifiers.contains(bundleIdentifier) {
|
if !runningAppsIdentifiers.contains(bundleIdentifier) {
|
||||||
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier))
|
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier))
|
||||||
returnable.append(dockItem)
|
returnable.append(dockItem)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,8 +6,8 @@
|
|||||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||||
//
|
//
|
||||||
|
|
||||||
import IOKit.ps
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import IOKit.ps
|
||||||
|
|
||||||
class BatteryBarItem: CustomButtonTouchBarItem {
|
class BatteryBarItem: CustomButtonTouchBarItem {
|
||||||
private let batteryInfo = BatteryInfo()
|
private let batteryInfo = BatteryInfo()
|
||||||
@ -18,15 +18,15 @@ class BatteryBarItem: CustomButtonTouchBarItem {
|
|||||||
batteryInfo.start { [weak self] in
|
batteryInfo.start { [weak self] in
|
||||||
self?.refresh()
|
self?.refresh()
|
||||||
}
|
}
|
||||||
self.refresh()
|
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() {
|
func refresh() {
|
||||||
self.attributedTitle = self.batteryInfo.formattedInfo()
|
attributedTitle = batteryInfo.formattedInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
deinit {
|
deinit {
|
||||||
@ -42,14 +42,14 @@ 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 notifyBlock: () -> Void = {}
|
||||||
var loop: CFRunLoopSource?
|
var loop: CFRunLoopSource?
|
||||||
|
|
||||||
func start(notifyBlock: @escaping ()->()) {
|
func start(notifyBlock: @escaping () -> Void) {
|
||||||
self.notifyBlock = notifyBlock
|
self.notifyBlock = notifyBlock
|
||||||
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
|
||||||
guard let ctx = context else {
|
guard let ctx = context else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -61,7 +61,7 @@ class BatteryInfo: NSObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func stop() {
|
func stop() {
|
||||||
self.notifyBlock = {}
|
notifyBlock = {}
|
||||||
guard let loop = self.loop else {
|
guard let loop = self.loop else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -76,32 +76,32 @@ class BatteryInfo: NSObject {
|
|||||||
for ps in psList {
|
for ps in psList {
|
||||||
if let psDesc = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
|
if let psDesc = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
|
||||||
let current = psDesc[kIOPSCurrentCapacityKey]
|
let current = psDesc[kIOPSCurrentCapacityKey]
|
||||||
if (current != nil) {
|
if current != nil {
|
||||||
self.current = current as! Int
|
self.current = current as! Int
|
||||||
}
|
}
|
||||||
|
|
||||||
let timeToEmpty = psDesc[kIOPSTimeToEmptyKey]
|
let timeToEmpty = psDesc[kIOPSTimeToEmptyKey]
|
||||||
if (timeToEmpty != nil) {
|
if timeToEmpty != nil {
|
||||||
self.timeToEmpty = timeToEmpty as! Int
|
self.timeToEmpty = timeToEmpty as! Int
|
||||||
}
|
}
|
||||||
|
|
||||||
let timeToFull = psDesc[kIOPSTimeToFullChargeKey]
|
let timeToFull = psDesc[kIOPSTimeToFullChargeKey]
|
||||||
if (timeToFull != nil) {
|
if timeToFull != nil {
|
||||||
self.timeToFull = timeToFull as! Int
|
self.timeToFull = timeToFull as! Int
|
||||||
}
|
}
|
||||||
|
|
||||||
let isCharged = psDesc[kIOPSIsChargedKey]
|
let isCharged = psDesc[kIOPSIsChargedKey]
|
||||||
if (isCharged != nil) {
|
if isCharged != nil {
|
||||||
self.isCharged = isCharged as! Bool
|
self.isCharged = isCharged as! Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
let isCharging = psDesc[kIOPSIsChargingKey]
|
let isCharging = psDesc[kIOPSIsChargingKey]
|
||||||
if (isCharging != nil) {
|
if isCharging != nil {
|
||||||
self.isCharging = isCharging as! Bool
|
self.isCharging = isCharging as! Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
let ACPower = psDesc[kIOPSPowerSourceStateKey]
|
let ACPower = psDesc[kIOPSPowerSourceStateKey]
|
||||||
if (ACPower != nil) {
|
if ACPower != nil {
|
||||||
self.ACPower = ACPower as! String
|
self.ACPower = ACPower as! String
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -109,7 +109,7 @@ class BatteryInfo: NSObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getFormattedTime(time: Int) -> String {
|
func getFormattedTime(time: Int) -> String {
|
||||||
if (time > 0) {
|
if time > 0 {
|
||||||
let timeFormatted = NSString(format: " %d:%02d", time / 60, time % 60) as String
|
let timeFormatted = NSString(format: " %d:%02d", time / 60, time % 60) as String
|
||||||
return timeFormatted
|
return timeFormatted
|
||||||
}
|
}
|
||||||
@ -119,7 +119,7 @@ class BatteryInfo: NSObject {
|
|||||||
|
|
||||||
public func formattedInfo() -> NSAttributedString {
|
public func formattedInfo() -> NSAttributedString {
|
||||||
var title = ""
|
var title = ""
|
||||||
self.getPSInfo()
|
getPSInfo()
|
||||||
|
|
||||||
if ACPower == "AC Power" {
|
if ACPower == "AC Power" {
|
||||||
if current < 100 {
|
if current < 100 {
|
||||||
@ -143,5 +143,4 @@ class BatteryInfo: NSObject {
|
|||||||
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
||||||
return newTitle
|
return newTitle
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import Cocoa
|
|
||||||
import AppKit
|
import AppKit
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
|
import Cocoa
|
||||||
import CoreAudio
|
import CoreAudio
|
||||||
|
|
||||||
class BrightnessViewController: NSCustomTouchBarItem {
|
class BrightnessViewController: NSCustomTouchBarItem {
|
||||||
@ -9,7 +9,7 @@ class BrightnessViewController: NSCustomTouchBarItem {
|
|||||||
init(identifier: NSTouchBarItem.Identifier, refreshInterval: Double, image: NSImage? = nil) {
|
init(identifier: NSTouchBarItem.Identifier, refreshInterval: Double, image: NSImage? = nil) {
|
||||||
super.init(identifier: identifier)
|
super.init(identifier: identifier)
|
||||||
|
|
||||||
if (image == nil) {
|
if image == nil {
|
||||||
sliderItem = CustomSlider()
|
sliderItem = CustomSlider()
|
||||||
} else {
|
} else {
|
||||||
sliderItem = CustomSlider(knob: image!)
|
sliderItem = CustomSlider(knob: image!)
|
||||||
@ -20,13 +20,13 @@ class BrightnessViewController: NSCustomTouchBarItem {
|
|||||||
sliderItem.maxValue = 100.0
|
sliderItem.maxValue = 100.0
|
||||||
sliderItem.floatValue = getBrightness() * 100
|
sliderItem.floatValue = getBrightness() * 100
|
||||||
|
|
||||||
self.view = sliderItem
|
view = sliderItem
|
||||||
|
|
||||||
let timer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(BrightnessViewController.updateBrightnessSlider), userInfo: nil, repeats: true)
|
let timer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(BrightnessViewController.updateBrightnessSlider), userInfo: nil, repeats: true)
|
||||||
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
|
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -48,7 +48,7 @@ class BrightnessViewController: NSCustomTouchBarItem {
|
|||||||
|
|
||||||
private func getBrightness() -> Float32 {
|
private func getBrightness() -> Float32 {
|
||||||
if #available(OSX 10.13, *) {
|
if #available(OSX 10.13, *) {
|
||||||
return Float32(CoreDisplay_Display_GetUserBrightness(0));
|
return Float32(CoreDisplay_Display_GetUserBrightness(0))
|
||||||
} else {
|
} else {
|
||||||
var level: Float32 = 0.5
|
var level: Float32 = 0.5
|
||||||
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
||||||
@ -60,13 +60,12 @@ class BrightnessViewController: NSCustomTouchBarItem {
|
|||||||
|
|
||||||
private func setBrightness(level: Float) {
|
private func setBrightness(level: Float) {
|
||||||
if #available(OSX 10.13, *) {
|
if #available(OSX 10.13, *) {
|
||||||
CoreDisplay_Display_SetUserBrightness(0, Double(level));
|
CoreDisplay_Display_SetUserBrightness(0, Double(level))
|
||||||
} else {
|
} else {
|
||||||
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
||||||
|
|
||||||
IODisplaySetFloatParameter(service, 1, kIODisplayBrightnessKey as CFString, level)
|
IODisplaySetFloatParameter(service, 1, kIODisplayBrightnessKey as CFString, level)
|
||||||
IOObjectRelease(service)
|
IOObjectRelease(service)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -45,7 +45,7 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
|
|||||||
if let prefix = currencies[from] {
|
if let prefix = currencies[from] {
|
||||||
self.prefix = prefix
|
self.prefix = prefix
|
||||||
} else {
|
} else {
|
||||||
self.prefix = from
|
prefix = from
|
||||||
}
|
}
|
||||||
|
|
||||||
super.init(identifier: identifier, title: "⏳")
|
super.init(identifier: identifier, title: "⏳")
|
||||||
@ -59,14 +59,14 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
|
|||||||
updateCurrency()
|
updateCurrency()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func updateCurrency() {
|
@objc func updateCurrency() {
|
||||||
let urlRequest = URLRequest(url: URL(string: "https://api.coinbase.com/v2/exchange-rates?currency=\(from)")!)
|
let urlRequest = URLRequest(url: URL(string: "https://api.coinbase.com/v2/exchange-rates?currency=\(from)")!)
|
||||||
|
|
||||||
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
|
let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in
|
||||||
if error == nil {
|
if error == nil {
|
||||||
do {
|
do {
|
||||||
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
|
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
|
||||||
@ -103,13 +103,13 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
|
|||||||
color = NSColor.red
|
color = NSColor.red
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.oldValue = value
|
oldValue = value
|
||||||
|
|
||||||
let title = String(format: "%@%.2f", self.prefix, value)
|
let title = String(format: "%@%.2f", prefix, value)
|
||||||
|
|
||||||
let regularFont = self.attributedTitle.attribute(.font, at: 0, effectiveRange: nil) as? NSFont ?? NSFont.systemFont(ofSize: 15)
|
let regularFont = attributedTitle.attribute(.font, at: 0, effectiveRange: nil) as? NSFont ?? NSFont.systemFont(ofSize: 15)
|
||||||
let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: regularFont])
|
let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: regularFont])
|
||||||
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
||||||
self.attributedTitle = newTitle
|
attributedTitle = newTitle
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,17 +13,17 @@ class DnDBarItem : CustomButtonTouchBarItem {
|
|||||||
|
|
||||||
init(identifier: NSTouchBarItem.Identifier) {
|
init(identifier: NSTouchBarItem.Identifier) {
|
||||||
super.init(identifier: identifier, title: "")
|
super.init(identifier: identifier, title: "")
|
||||||
self.isBordered = false
|
isBordered = false
|
||||||
self.setWidth(value: 32)
|
setWidth(value: 32)
|
||||||
|
|
||||||
self.tapClosure = { [weak self] in self?.DnDToggle() }
|
tapClosure = { [weak self] in self?.DnDToggle() }
|
||||||
|
|
||||||
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refresh), userInfo: nil, repeats: true)
|
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refresh), userInfo: nil, repeats: true)
|
||||||
|
|
||||||
self.refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,7 +33,7 @@ class DnDBarItem : CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc func refresh() {
|
@objc func refresh() {
|
||||||
self.image = DoNotDisturb.isEnabled ? #imageLiteral(resourceName: "dnd-on") : #imageLiteral(resourceName: "dnd-off")
|
image = DoNotDisturb.isEnabled ? #imageLiteral(resourceName: "dnd-on") : #imageLiteral(resourceName: "dnd-off")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -8,7 +8,6 @@
|
|||||||
import Cocoa
|
import Cocoa
|
||||||
|
|
||||||
class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
||||||
|
|
||||||
var jsonItems: [BarItemDefinition]
|
var jsonItems: [BarItemDefinition]
|
||||||
|
|
||||||
var itemDefinitions: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
|
var itemDefinitions: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
|
||||||
@ -23,37 +22,35 @@ class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
|||||||
init(identifier: NSTouchBarItem.Identifier, items: [BarItemDefinition]) {
|
init(identifier: NSTouchBarItem.Identifier, items: [BarItemDefinition]) {
|
||||||
jsonItems = items
|
jsonItems = items
|
||||||
super.init(identifier: identifier)
|
super.init(identifier: identifier)
|
||||||
self.popoverTouchBar.delegate = self
|
popoverTouchBar.delegate = self
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
deinit {
|
deinit {}
|
||||||
|
|
||||||
}
|
@objc override func showPopover(_: Any?) {
|
||||||
|
itemDefinitions = [:]
|
||||||
|
items = [:]
|
||||||
|
leftIdentifiers = []
|
||||||
|
centerItems = []
|
||||||
|
rightIdentifiers = []
|
||||||
|
|
||||||
@objc override func showPopover(_ sender: Any?) {
|
loadItemDefinitions(jsonItems: jsonItems)
|
||||||
self.itemDefinitions = [:]
|
createItems()
|
||||||
self.items = [:]
|
|
||||||
self.leftIdentifiers = []
|
|
||||||
self.centerItems = []
|
|
||||||
self.rightIdentifiers = []
|
|
||||||
|
|
||||||
self.loadItemDefinitions(jsonItems: jsonItems)
|
|
||||||
self.createItems()
|
|
||||||
|
|
||||||
centerItems = centerIdentifiers.compactMap({ (identifier) -> NSTouchBarItem? in
|
centerItems = centerIdentifiers.compactMap({ (identifier) -> NSTouchBarItem? in
|
||||||
return items[identifier]
|
items[identifier]
|
||||||
})
|
})
|
||||||
|
|
||||||
self.centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
||||||
self.scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
|
scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
|
||||||
|
|
||||||
TouchBarController.shared.touchBar.delegate = self
|
TouchBarController.shared.touchBar.delegate = self
|
||||||
TouchBarController.shared.touchBar.defaultItemIdentifiers = []
|
TouchBarController.shared.touchBar.defaultItemIdentifiers = []
|
||||||
TouchBarController.shared.touchBar.defaultItemIdentifiers = self.leftIdentifiers + [centerScrollArea] + self.rightIdentifiers
|
TouchBarController.shared.touchBar.defaultItemIdentifiers = leftIdentifiers + [centerScrollArea] + rightIdentifiers
|
||||||
|
|
||||||
if TouchBarController.shared.showControlStripState {
|
if TouchBarController.shared.showControlStripState {
|
||||||
presentSystemModal(TouchBarController.shared.touchBar, systemTrayItemIdentifier: .controlStripItem)
|
presentSystemModal(TouchBarController.shared.touchBar, systemTrayItemIdentifier: .controlStripItem)
|
||||||
@ -62,9 +59,9 @@ class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
|
func touchBar(_: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
|
||||||
if identifier == centerScrollArea {
|
if identifier == centerScrollArea {
|
||||||
return self.scrollArea
|
return scrollArea
|
||||||
}
|
}
|
||||||
|
|
||||||
guard let item = self.items[identifier],
|
guard let item = self.items[identifier],
|
||||||
@ -96,8 +93,8 @@ class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func createItems() {
|
func createItems() {
|
||||||
for (identifier, definition) in self.itemDefinitions {
|
for (identifier, definition) in itemDefinitions {
|
||||||
self.items[identifier] = TouchBarController.shared.createItem(forIdentifier: identifier, definition: definition)
|
items[identifier] = TouchBarController.shared.createItem(forIdentifier: identifier, definition: definition)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,33 +9,32 @@
|
|||||||
import Cocoa
|
import Cocoa
|
||||||
|
|
||||||
class InputSourceBarItem: CustomButtonTouchBarItem {
|
class InputSourceBarItem: CustomButtonTouchBarItem {
|
||||||
|
|
||||||
fileprivate var notificationCenter: CFNotificationCenter
|
fileprivate var notificationCenter: CFNotificationCenter
|
||||||
let buttonSize = NSSize(width: 21, height: 21)
|
let buttonSize = NSSize(width: 21, height: 21)
|
||||||
|
|
||||||
init(identifier: NSTouchBarItem.Identifier) {
|
init(identifier: NSTouchBarItem.Identifier) {
|
||||||
notificationCenter = CFNotificationCenterGetDistributedCenter();
|
notificationCenter = CFNotificationCenterGetDistributedCenter()
|
||||||
super.init(identifier: identifier, title: "⏳")
|
super.init(identifier: identifier, title: "⏳")
|
||||||
|
|
||||||
observeIputSourceChangedNotification();
|
observeIputSourceChangedNotification()
|
||||||
textInputSourceDidChange()
|
textInputSourceDidChange()
|
||||||
self.tapClosure = { [weak self] in
|
tapClosure = { [weak self] in
|
||||||
self?.switchInputSource()
|
self?.switchInputSource()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
deinit {
|
deinit {
|
||||||
CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()));
|
CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()))
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc public func textInputSourceDidChange() {
|
@objc public func textInputSourceDidChange() {
|
||||||
let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
|
let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
|
||||||
|
|
||||||
var iconImage: NSImage? = nil
|
var iconImage: NSImage?
|
||||||
|
|
||||||
if let imageURL = currentSource.iconImageURL,
|
if let imageURL = currentSource.iconImageURL,
|
||||||
let image = NSImage(contentsOf: imageURL) {
|
let image = NSImage(contentsOf: imageURL) {
|
||||||
@ -46,10 +45,10 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
|
|||||||
|
|
||||||
if let iconImage = iconImage {
|
if let iconImage = iconImage {
|
||||||
iconImage.size = buttonSize
|
iconImage.size = buttonSize
|
||||||
self.image = iconImage
|
image = iconImage
|
||||||
self.title = ""
|
title = ""
|
||||||
} else {
|
} else {
|
||||||
self.title = currentSource.name
|
title = currentSource.name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,7 +64,7 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
|
|||||||
})
|
})
|
||||||
|
|
||||||
for item in inputSources {
|
for item in inputSources {
|
||||||
if (item.id != currentSource.id) {
|
if item.id != currentSource.id {
|
||||||
TISSelectInputSource(item)
|
TISSelectInputSource(item)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -73,7 +72,7 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc public func observeIputSourceChangedNotification() {
|
@objc public func observeIputSourceChangedNotification() {
|
||||||
let callback: CFNotificationCallback = { center, observer, name, object, info in
|
let callback: CFNotificationCallback = { _, observer, _, _, _ in
|
||||||
let mySelf = Unmanaged<InputSourceBarItem>.fromOpaque(observer!).takeUnretainedValue()
|
let mySelf = Unmanaged<InputSourceBarItem>.fromOpaque(observer!).takeUnretainedValue()
|
||||||
mySelf.textInputSourceDidChange()
|
mySelf.textInputSourceDidChange()
|
||||||
}
|
}
|
||||||
@ -96,7 +95,7 @@ extension TISInputSource {
|
|||||||
|
|
||||||
private func getProperty(_ key: CFString) -> AnyObject? {
|
private func getProperty(_ key: CFString) -> AnyObject? {
|
||||||
let cfType = TISGetInputSourceProperty(self, key)
|
let cfType = TISGetInputSourceProperty(self, key)
|
||||||
if (cfType != nil) {
|
if cfType != nil {
|
||||||
return Unmanaged<AnyObject>.fromOpaque(cfType!).takeUnretainedValue()
|
return Unmanaged<AnyObject>.fromOpaque(cfType!).takeUnretainedValue()
|
||||||
} else {
|
} else {
|
||||||
return nil
|
return nil
|
||||||
@ -131,4 +130,3 @@ extension TISInputSource {
|
|||||||
return OpaquePointer(TISGetInputSourceProperty(self, kTISPropertyIconRef)) as IconRef?
|
return OpaquePointer(TISGetInputSourceProperty(self, kTISPropertyIconRef)) as IconRef?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -20,51 +20,51 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
"com.spotify.client",
|
"com.spotify.client",
|
||||||
"com.coppertino.Vox",
|
"com.coppertino.Vox",
|
||||||
"com.google.Chrome",
|
"com.google.Chrome",
|
||||||
"com.apple.Safari"
|
"com.apple.Safari",
|
||||||
]
|
]
|
||||||
|
|
||||||
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) {
|
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) {
|
||||||
self.interval = interval
|
self.interval = interval
|
||||||
|
|
||||||
super.init(identifier: identifier, title: "⏳")
|
super.init(identifier: identifier, title: "⏳")
|
||||||
self.isBordered = false
|
isBordered = false
|
||||||
|
|
||||||
self.tapClosure = { [weak self] in self?.playPause() }
|
tapClosure = { [weak self] in self?.playPause() }
|
||||||
self.longTapClosure = { [weak self] in self?.nextTrack() }
|
longTapClosure = { [weak self] in self?.nextTrack() }
|
||||||
|
|
||||||
self.refreshAndSchedule()
|
refreshAndSchedule()
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func marquee() {
|
@objc func marquee() {
|
||||||
let str = self.title
|
let str = title
|
||||||
if (str.count > 10) {
|
if str.count > 10 {
|
||||||
let indexFirst = str.index(str.startIndex, offsetBy: 0)
|
let indexFirst = str.index(str.startIndex, offsetBy: 0)
|
||||||
let indexSecond = str.index(str.startIndex, offsetBy: 1)
|
let indexSecond = str.index(str.startIndex, offsetBy: 1)
|
||||||
self.title = String(str.suffix(from: indexSecond)) + String(str[indexFirst])
|
title = String(str.suffix(from: indexSecond)) + String(str[indexFirst])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func playPause() {
|
@objc func playPause() {
|
||||||
for ident in playerBundleIdentifiers {
|
for ident in playerBundleIdentifiers {
|
||||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||||
if (musicPlayer.isRunning) {
|
if musicPlayer.isRunning {
|
||||||
if (musicPlayer.className == "SpotifyApplication") {
|
if musicPlayer.className == "SpotifyApplication" {
|
||||||
let mp = (musicPlayer as SpotifyApplication)
|
let mp = (musicPlayer as SpotifyApplication)
|
||||||
mp.playpause!()
|
mp.playpause!()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "ITunesApplication") {
|
} else if musicPlayer.className == "ITunesApplication" {
|
||||||
let mp = (musicPlayer as iTunesApplication)
|
let mp = (musicPlayer as iTunesApplication)
|
||||||
mp.playpause!()
|
mp.playpause!()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "VOXApplication") {
|
} else if musicPlayer.className == "VOXApplication" {
|
||||||
let mp = (musicPlayer as VoxApplication)
|
let mp = (musicPlayer as VoxApplication)
|
||||||
mp.playpause!()
|
mp.playpause!()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "SafariApplication") {
|
} else if musicPlayer.className == "SafariApplication" {
|
||||||
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
||||||
let safariApplication = musicPlayer as SafariApplication
|
let safariApplication = musicPlayer as SafariApplication
|
||||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||||
@ -74,7 +74,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_play')[0].click()", in: tab)
|
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_play')[0].click()", in: tab)
|
||||||
return
|
return
|
||||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
} else if (tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))! {
|
||||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_play')[0].click()", in: tab)
|
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_play')[0].click()", in: tab)
|
||||||
return
|
return
|
||||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||||
@ -112,23 +112,23 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
@objc func nextTrack() {
|
@objc func nextTrack() {
|
||||||
for ident in playerBundleIdentifiers {
|
for ident in playerBundleIdentifiers {
|
||||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||||
if (musicPlayer.isRunning) {
|
if musicPlayer.isRunning {
|
||||||
if (musicPlayer.className == "SpotifyApplication") {
|
if musicPlayer.className == "SpotifyApplication" {
|
||||||
let mp = (musicPlayer as SpotifyApplication)
|
let mp = (musicPlayer as SpotifyApplication)
|
||||||
mp.nextTrack!()
|
mp.nextTrack!()
|
||||||
updatePlayer()
|
updatePlayer()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "ITunesApplication") {
|
} else if musicPlayer.className == "ITunesApplication" {
|
||||||
let mp = (musicPlayer as iTunesApplication)
|
let mp = (musicPlayer as iTunesApplication)
|
||||||
mp.nextTrack!()
|
mp.nextTrack!()
|
||||||
updatePlayer()
|
updatePlayer()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "VOXApplication") {
|
} else if musicPlayer.className == "VOXApplication" {
|
||||||
let mp = (musicPlayer as VoxApplication)
|
let mp = (musicPlayer as VoxApplication)
|
||||||
mp.next!()
|
mp.next!()
|
||||||
updatePlayer()
|
updatePlayer()
|
||||||
return
|
return
|
||||||
} else if (musicPlayer.className == "SafariApplication") {
|
} else if musicPlayer.className == "SafariApplication" {
|
||||||
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
||||||
let safariApplication = musicPlayer as SafariApplication
|
let safariApplication = musicPlayer as SafariApplication
|
||||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||||
@ -139,7 +139,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_next')[0].click()", in: tab)
|
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_next')[0].click()", in: tab)
|
||||||
updatePlayer()
|
updatePlayer()
|
||||||
return
|
return
|
||||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
} else if (tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))! {
|
||||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_next')[0].click()", in: tab)
|
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_next')[0].click()", in: tab)
|
||||||
updatePlayer()
|
updatePlayer()
|
||||||
return
|
return
|
||||||
@ -171,15 +171,15 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
|
|
||||||
for var ident in playerBundleIdentifiers {
|
for var ident in playerBundleIdentifiers {
|
||||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||||
if (musicPlayer.isRunning) {
|
if musicPlayer.isRunning {
|
||||||
var tempTitle = ""
|
var tempTitle = ""
|
||||||
if (musicPlayer.className == "SpotifyApplication") {
|
if musicPlayer.className == "SpotifyApplication" {
|
||||||
tempTitle = (musicPlayer as SpotifyApplication).title
|
tempTitle = (musicPlayer as SpotifyApplication).title
|
||||||
} else if (musicPlayer.className == "ITunesApplication") {
|
} else if musicPlayer.className == "ITunesApplication" {
|
||||||
tempTitle = (musicPlayer as iTunesApplication).title
|
tempTitle = (musicPlayer as iTunesApplication).title
|
||||||
} else if (musicPlayer.className == "VOXApplication") {
|
} else if musicPlayer.className == "VOXApplication" {
|
||||||
tempTitle = (musicPlayer as VoxApplication).title
|
tempTitle = (musicPlayer as VoxApplication).title
|
||||||
} else if (musicPlayer.className == "SafariApplication") {
|
} else if musicPlayer.className == "SafariApplication" {
|
||||||
let safariApplication = musicPlayer as SafariApplication
|
let safariApplication = musicPlayer as SafariApplication
|
||||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||||
for window in safariWindows! {
|
for window in safariWindows! {
|
||||||
@ -190,7 +190,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
tempTitle = (tab.name)!
|
tempTitle = (tab.name)!
|
||||||
break
|
break
|
||||||
// }
|
// }
|
||||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
} else if (tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))! {
|
||||||
tempTitle = (tab.name)!
|
tempTitle = (tab.name)!
|
||||||
break
|
break
|
||||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||||
@ -202,18 +202,18 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
if tempTitle == "" {
|
if tempTitle == "" {
|
||||||
ident = ""
|
ident = ""
|
||||||
}
|
}
|
||||||
} else if (musicPlayer.className == "GoogleChromeApplication") {
|
} else if musicPlayer.className == "GoogleChromeApplication" {
|
||||||
let chromeApplication = musicPlayer as GoogleChromeApplication
|
let chromeApplication = musicPlayer as GoogleChromeApplication
|
||||||
let chromeWindows = chromeApplication.windows?().compactMap({ $0 as? GoogleChromeWindow })
|
let chromeWindows = chromeApplication.windows?().compactMap({ $0 as? GoogleChromeWindow })
|
||||||
for window in chromeWindows! {
|
for window in chromeWindows! {
|
||||||
for tab in window.tabs!() {
|
for tab in window.tabs!() {
|
||||||
let tab = tab as! GoogleChromeTab
|
let tab = tab as! GoogleChromeTab
|
||||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||||
if (!(tab.title?.hasSuffix("на Яндекс.Музыке"))!) {
|
if !(tab.title?.hasSuffix("на Яндекс.Музыке"))! {
|
||||||
tempTitle = tab.title!
|
tempTitle = tab.title!
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
} else if (tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))! {
|
||||||
tempTitle = tab.title!
|
tempTitle = tab.title!
|
||||||
break
|
break
|
||||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||||
@ -227,7 +227,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tempTitle == self.songTitle) {
|
if tempTitle == self.songTitle {
|
||||||
return
|
return
|
||||||
} else {
|
} else {
|
||||||
self.songTitle = tempTitle
|
self.songTitle = tempTitle
|
||||||
@ -270,12 +270,14 @@ class MusicBarItem: CustomButtonTouchBarItem {
|
|||||||
@objc optional func previousTrack()
|
@objc optional func previousTrack()
|
||||||
@objc optional func playpause()
|
@objc optional func playpause()
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBApplication: SpotifyApplication {}
|
extension SBApplication: SpotifyApplication {}
|
||||||
|
|
||||||
@objc protocol SpotifyTrack {
|
@objc protocol SpotifyTrack {
|
||||||
@objc optional var artist: String { get }
|
@objc optional var artist: String { get }
|
||||||
@objc optional var name: String { get }
|
@objc optional var name: String { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: SpotifyTrack {}
|
extension SBObject: SpotifyTrack {}
|
||||||
|
|
||||||
extension SpotifyApplication {
|
extension SpotifyApplication {
|
||||||
@ -285,19 +287,20 @@ extension SpotifyApplication {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@objc protocol iTunesApplication {
|
@objc protocol iTunesApplication {
|
||||||
@objc optional var currentTrack: iTunesTrack { get }
|
@objc optional var currentTrack: iTunesTrack { get }
|
||||||
@objc optional func playpause()
|
@objc optional func playpause()
|
||||||
@objc optional func nextTrack()
|
@objc optional func nextTrack()
|
||||||
@objc optional func previousTrack()
|
@objc optional func previousTrack()
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBApplication: iTunesApplication {}
|
extension SBApplication: iTunesApplication {}
|
||||||
|
|
||||||
@objc protocol iTunesTrack {
|
@objc protocol iTunesTrack {
|
||||||
@objc optional var artist: String { get }
|
@objc optional var artist: String { get }
|
||||||
@objc optional var name: String { get }
|
@objc optional var name: String { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: iTunesTrack {}
|
extension SBObject: iTunesTrack {}
|
||||||
|
|
||||||
extension iTunesApplication {
|
extension iTunesApplication {
|
||||||
@ -307,8 +310,6 @@ extension iTunesApplication {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@objc protocol VoxApplication {
|
@objc protocol VoxApplication {
|
||||||
@objc optional func playpause()
|
@objc optional func playpause()
|
||||||
@objc optional func next()
|
@objc optional func next()
|
||||||
@ -316,6 +317,7 @@ extension iTunesApplication {
|
|||||||
@objc optional var track: String { get }
|
@objc optional var track: String { get }
|
||||||
@objc optional var artist: String { get }
|
@objc optional var artist: String { get }
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBApplication: VoxApplication {}
|
extension SBApplication: VoxApplication {}
|
||||||
|
|
||||||
extension VoxApplication {
|
extension VoxApplication {
|
||||||
@ -324,7 +326,6 @@ extension VoxApplication {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@objc public protocol SBObjectProtocol: NSObjectProtocol {
|
@objc public protocol SBObjectProtocol: NSObjectProtocol {
|
||||||
func get() -> Any!
|
func get() -> Any!
|
||||||
}
|
}
|
||||||
@ -338,6 +339,7 @@ extension VoxApplication {
|
|||||||
@objc optional func windows() -> SBElementArray
|
@objc optional func windows() -> SBElementArray
|
||||||
@objc optional func doJavaScript(_ x: String!, in in_: Any!) -> Any // Applies a string of JavaScript code to a document.
|
@objc optional func doJavaScript(_ x: String!, in in_: Any!) -> Any // Applies a string of JavaScript code to a document.
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBApplication: SafariApplication {}
|
extension SBApplication: SafariApplication {}
|
||||||
|
|
||||||
@objc public protocol SafariWindow: SBObjectProtocol {
|
@objc public protocol SafariWindow: SBObjectProtocol {
|
||||||
@ -346,6 +348,7 @@ extension SBApplication: SafariApplication {}
|
|||||||
// @objc optional var document: SafariDocument { get } // The document whose contents are displayed in the window.
|
// @objc optional var document: SafariDocument { get } // The document whose contents are displayed in the window.
|
||||||
// @objc optional func setCurrentTab(_ currentTab: SafariTab!) // The current tab.
|
// @objc optional func setCurrentTab(_ currentTab: SafariTab!) // The current tab.
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: SafariWindow {}
|
extension SBObject: SafariWindow {}
|
||||||
|
|
||||||
// @objc public protocol SafariDocument: SBObjectProtocol {
|
// @objc public protocol SafariDocument: SBObjectProtocol {
|
||||||
@ -358,24 +361,26 @@ extension SBObject: SafariWindow {}
|
|||||||
@objc optional var URL: String { get } // The current URL of the tab.
|
@objc optional var URL: String { get } // The current URL of the tab.
|
||||||
@objc optional var name: String { get } // The name of the tab.
|
@objc optional var name: String { get } // The name of the tab.
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: SafariTab {}
|
extension SBObject: SafariTab {}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@objc public protocol GoogleChromeApplication: SBApplicationProtocol {
|
@objc public protocol GoogleChromeApplication: SBApplicationProtocol {
|
||||||
@objc optional func windows() -> SBElementArray
|
@objc optional func windows() -> SBElementArray
|
||||||
@objc optional func executeJavaScript(javascript: String!) -> Any // Applies a string of JavaScript code to a document. //, id: Any!
|
@objc optional func executeJavaScript(javascript: String!) -> Any // Applies a string of JavaScript code to a document. //, id: Any!
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBApplication: GoogleChromeApplication {}
|
extension SBApplication: GoogleChromeApplication {}
|
||||||
|
|
||||||
@objc public protocol GoogleChromeWindow: SBObjectProtocol {
|
@objc public protocol GoogleChromeWindow: SBObjectProtocol {
|
||||||
@objc optional var name: String { get } // The title of the window.
|
@objc optional var name: String { get } // The title of the window.
|
||||||
@objc optional func tabs() -> SBElementArray
|
@objc optional func tabs() -> SBElementArray
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: GoogleChromeWindow {}
|
extension SBObject: GoogleChromeWindow {}
|
||||||
|
|
||||||
@objc public protocol GoogleChromeTab: SBObjectProtocol {
|
@objc public protocol GoogleChromeTab: SBObjectProtocol {
|
||||||
@objc optional var URL: String { get } // The current URL of the tab.
|
@objc optional var URL: String { get } // The current URL of the tab.
|
||||||
@objc optional var title: String { get } // The name of the tab.
|
@objc optional var title: String { get } // The name of the tab.
|
||||||
}
|
}
|
||||||
|
|
||||||
extension SBObject: GoogleChromeTab {}
|
extension SBObject: GoogleChromeTab {}
|
||||||
|
|||||||
@ -19,35 +19,35 @@ class NightShiftBarItem: CustomButtonTouchBarItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var isNightShiftEnabled: Bool {
|
private var isNightShiftEnabled: Bool {
|
||||||
return self.blueLightStatus.enabled.boolValue
|
return blueLightStatus.enabled.boolValue
|
||||||
}
|
}
|
||||||
|
|
||||||
private func setNightShift(state: Bool) {
|
private func setNightShift(state: Bool) {
|
||||||
self.nsclient.setEnabled(state)
|
nsclient.setEnabled(state)
|
||||||
}
|
}
|
||||||
|
|
||||||
init(identifier: NSTouchBarItem.Identifier) {
|
init(identifier: NSTouchBarItem.Identifier) {
|
||||||
super.init(identifier: identifier, title: "")
|
super.init(identifier: identifier, title: "")
|
||||||
self.isBordered = false
|
isBordered = false
|
||||||
self.setWidth(value: 28)
|
setWidth(value: 28)
|
||||||
|
|
||||||
self.tapClosure = { [weak self] in self?.nightShiftAction() }
|
tapClosure = { [weak self] in self?.nightShiftAction() }
|
||||||
|
|
||||||
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refresh), userInfo: nil, repeats: true)
|
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refresh), userInfo: nil, repeats: true)
|
||||||
|
|
||||||
self.refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func nightShiftAction() {
|
func nightShiftAction() {
|
||||||
self.setNightShift(state: !self.isNightShiftEnabled)
|
setNightShift(state: !isNightShiftEnabled)
|
||||||
self.refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func refresh() {
|
@objc func refresh() {
|
||||||
self.image = isNightShiftEnabled ? #imageLiteral(resourceName: "nightShiftOn") : #imageLiteral(resourceName: "nightShiftOff")
|
image = isNightShiftEnabled ? #imageLiteral(resourceName: "nightShiftOn") : #imageLiteral(resourceName: "nightShiftOff")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,16 +8,15 @@ class TimeTouchBarItem: CustomButtonTouchBarItem {
|
|||||||
dateFormatter.setLocalizedDateFormatFromTemplate(formatTemplate)
|
dateFormatter.setLocalizedDateFormatFromTemplate(formatTemplate)
|
||||||
super.init(identifier: identifier, title: " ")
|
super.init(identifier: identifier, title: " ")
|
||||||
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
|
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
|
||||||
self.isBordered = false
|
isBordered = false
|
||||||
updateTime()
|
updateTime()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func updateTime() {
|
@objc func updateTime() {
|
||||||
self.title = self.dateFormatter.string(from: Date())
|
title = dateFormatter.string(from: Date())
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import Cocoa
|
|
||||||
import AppKit
|
import AppKit
|
||||||
import AVFoundation
|
import AVFoundation
|
||||||
|
import Cocoa
|
||||||
import CoreAudio
|
import CoreAudio
|
||||||
|
|
||||||
class VolumeViewController: NSCustomTouchBarItem {
|
class VolumeViewController: NSCustomTouchBarItem {
|
||||||
@ -12,11 +12,12 @@ class VolumeViewController: NSCustomTouchBarItem {
|
|||||||
var forPropertyAddress = AudioObjectPropertyAddress(
|
var forPropertyAddress = AudioObjectPropertyAddress(
|
||||||
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
|
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
|
||||||
mScope: kAudioDevicePropertyScopeOutput,
|
mScope: kAudioDevicePropertyScopeOutput,
|
||||||
mElement: kAudioObjectPropertyElementMaster)
|
mElement: kAudioObjectPropertyElementMaster
|
||||||
|
)
|
||||||
|
|
||||||
AudioObjectAddPropertyListenerBlock(defaultDeviceID, &forPropertyAddress, nil, audioObjectPropertyListenerBlock)
|
AudioObjectAddPropertyListenerBlock(defaultDeviceID, &forPropertyAddress, nil, audioObjectPropertyListenerBlock)
|
||||||
|
|
||||||
if (image == nil) {
|
if image == nil {
|
||||||
sliderItem = CustomSlider()
|
sliderItem = CustomSlider()
|
||||||
} else {
|
} else {
|
||||||
sliderItem = CustomSlider(knob: image!)
|
sliderItem = CustomSlider(knob: image!)
|
||||||
@ -27,16 +28,16 @@ class VolumeViewController: NSCustomTouchBarItem {
|
|||||||
sliderItem.maxValue = 100.0
|
sliderItem.maxValue = 100.0
|
||||||
sliderItem.floatValue = getInputGain() * 100
|
sliderItem.floatValue = getInputGain() * 100
|
||||||
|
|
||||||
self.view = sliderItem
|
view = sliderItem
|
||||||
}
|
}
|
||||||
|
|
||||||
func audioObjectPropertyListenerBlock (numberAddresses: UInt32, addresses: UnsafePointer<AudioObjectPropertyAddress>) {
|
func audioObjectPropertyListenerBlock(numberAddresses _: UInt32, addresses _: UnsafePointer<AudioObjectPropertyAddress>) {
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.sliderItem.floatValue = self.getInputGain() * 100
|
self.sliderItem.floatValue = self.getInputGain() * 100
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,4 +100,3 @@ class VolumeViewController: NSCustomTouchBarItem {
|
|||||||
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &muteVal)
|
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &muteVal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -51,7 +51,7 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !CLLocationManager.locationServicesEnabled() {
|
if !CLLocationManager.locationServicesEnabled() {
|
||||||
print("Location services not enabled");
|
print("Location services not enabled")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,15 +69,15 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
|
|||||||
manager.startUpdatingLocation()
|
manager.startUpdatingLocation()
|
||||||
}
|
}
|
||||||
|
|
||||||
required init?(coder: NSCoder) {
|
required init?(coder _: NSCoder) {
|
||||||
fatalError("init(coder:) has not been implemented")
|
fatalError("init(coder:) has not been implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc func updateWeather() {
|
@objc func updateWeather() {
|
||||||
if self.location != nil {
|
if location != nil {
|
||||||
let urlRequest = URLRequest(url: URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)&units=\(self.units)&appid=\(self.api_key)")!)
|
let urlRequest = URLRequest(url: URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)&units=\(units)&appid=\(api_key)")!)
|
||||||
|
|
||||||
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
|
let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in
|
||||||
|
|
||||||
if error == nil {
|
if error == nil {
|
||||||
do {
|
do {
|
||||||
@ -115,25 +115,24 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func setWeather(text: String) {
|
func setWeather(text: String) {
|
||||||
self.title = text
|
title = text
|
||||||
}
|
}
|
||||||
|
|
||||||
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
||||||
let lastLocation = locations.last!
|
let lastLocation = locations.last!
|
||||||
self.location = lastLocation
|
location = lastLocation
|
||||||
if prev_location == nil {
|
if prev_location == nil {
|
||||||
updateWeather()
|
updateWeather()
|
||||||
}
|
}
|
||||||
prev_location = lastLocation
|
prev_location = lastLocation
|
||||||
}
|
}
|
||||||
|
|
||||||
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
|
func locationManager(_: CLLocationManager, didFailWithError error: Error) {
|
||||||
print(error);
|
print(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
|
func locationManager(_: CLLocationManager, didChangeAuthorization _: CLAuthorizationStatus) {
|
||||||
// print("inside didChangeAuthorization ");
|
// print("inside didChangeAuthorization ");
|
||||||
updateWeather()
|
updateWeather()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user