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

code format

This commit is contained in:
Toxblh 2018-10-20 17:53:49 +01:00
parent 8554dfeb5e
commit 86954a7981
24 changed files with 822 additions and 737 deletions

View File

@ -11,18 +11,18 @@ import Sparkle
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
var isBlockedApp: Bool = false
private var fileSystemSource: DispatchSourceFileSystemObject?
func applicationDidFinishLaunching(_ aNotification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
// Configure Sparkle
SUUpdater.shared().automaticallyDownloadsUpdates = false
SUUpdater.shared().automaticallyChecksForUpdates = true
SUUpdater.shared().checkForUpdatesInBackground()
let _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary)
AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary)
TouchBarController.shared.setupControlStripPresence()
@ -38,27 +38,23 @@ class AppDelegate: NSObject, NSApplicationDelegate {
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(updateIsBlockedApp), name: NSWorkspace.didActivateApplicationNotification, object: nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
func applicationWillTerminate(_: Notification) {}
}
@objc func updateIsBlockedApp() -> Void {
@objc func updateIsBlockedApp() {
var blacklistAppIdentifiers: [String] = []
if let blackListed = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.blackListedApps") {
blacklistAppIdentifiers = blackListed
}
var frontmostApplicationIdentifier: String? {
get {
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
return frontmostId
}
}
self.isBlockedApp = blacklistAppIdentifiers.index(of: frontmostApplicationIdentifier!) != nil
isBlockedApp = blacklistAppIdentifiers.index(of: frontmostApplicationIdentifier!) != nil
createMenu()
}
@objc func openPreferences(_ sender: Any?) {
@objc func openPreferences(_: Any?) {
let task = Process()
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
let presetPath = appSupportDirectory.appending("/items.json")
@ -67,13 +63,13 @@ class AppDelegate: NSObject, NSApplicationDelegate {
task.launch()
}
@objc func toggleControlStrip(_ sender: Any?) {
@objc func toggleControlStrip(_: Any?) {
TouchBarController.shared.showControlStripState = !TouchBarController.shared.showControlStripState
TouchBarController.shared.resetControlStrip()
createMenu()
}
@objc func toggleBlackListedApp(_ sender: Any?) {
@objc func toggleBlackListedApp(_: Any?) {
let appIdentifier = TouchBarController.shared.frontmostApplicationIdentifier
if appIdentifier != nil {
if let index = TouchBarController.shared.blacklistAppIdentifiers.index(of: appIdentifier!) {
@ -90,8 +86,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
}
@objc func openPreset(_ sender: Any?) {
let dialog = NSOpenPanel();
@objc func openPreset(_: Any?) {
let dialog = NSOpenPanel()
dialog.title = "Choose a items.json file"
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))
createMenu()
}
@ -119,7 +115,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
startAtLogin.state = LaunchAtLoginController().launchAtLogin ? .on : .off
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")
hideControlStrip.state = TouchBarController.shared.showControlStripState ? .off : .on
@ -146,20 +142,19 @@ class AppDelegate: NSObject, NSApplicationDelegate {
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...")
DispatchQueue.main.async {
TouchBarController.shared.reloadPreset(path: file.path)
}
})
self.fileSystemSource?.setCancelHandler(handler: {
fileSystemSource?.setCancelHandler(handler: {
close(fd)
})
self.fileSystemSource?.resume()
fileSystemSource?.resume()
}
}

View File

@ -8,13 +8,13 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
init?(identifier: NSTouchBarItem.Identifier, source: SourceProtocol, interval: TimeInterval) {
self.interval = interval
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 {
self.title = "no script"
title = "no script"
return
}
self.script = script
self.isBordered = false
isBordered = false
DispatchQueue.appleScriptQueue.async {
var error: NSDictionary?
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")
}
func refreshAndSchedule() {
#if DEBUG
print("refresh happened (interval \(self.interval)), self \(self.identifier.rawValue))")
print("refresh happened (interval \(interval)), self \(identifier.rawValue))")
#endif
let scriptResult = self.execute()
let scriptResult = execute()
DispatchQueue.main.async {
self.title = scriptResult
self.forceHideConstraint.isActive = scriptResult == ""
@ -46,7 +46,7 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
print("did set new script result title \(scriptResult)")
#endif
}
DispatchQueue.appleScriptQueue.asyncAfter(deadline: .now() + self.interval) { [weak self] in
DispatchQueue.appleScriptQueue.asyncAfter(deadline: .now() + interval) { [weak self] in
self?.refreshAndSchedule()
}
}
@ -60,7 +60,6 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
}
return output.stringValue ?? ""
}
}
extension DispatchQueue {

View File

@ -9,15 +9,15 @@
import Cocoa
class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
var tapClosure: (() -> ())?
var longTapClosure: (() -> ())?
var tapClosure: (() -> Void)?
var longTapClosure: (() -> Void)?
private var button: NSButton!
private var singleClick: NSClickGestureRecognizer!
private var longClick: NSPressGestureRecognizer!
init(identifier: NSTouchBarItem.Identifier, title: String) {
self.attributedTitle = title.defaultTouchbarAttributedString
attributedTitle = title.defaultTouchbarAttributedString
super.init(identifier: identifier)
button = CustomHeightButton(title: title, target: nil, action: nil)
@ -34,7 +34,7 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
button.attributedTitle = attributedTitle
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@ -52,17 +52,17 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
var title: String {
get {
return self.attributedTitle.string
return attributedTitle.string
}
set {
self.attributedTitle = newValue.defaultTouchbarAttributedString
attributedTitle = newValue.defaultTouchbarAttributedString
}
}
var attributedTitle: NSAttributedString {
didSet {
self.button?.imagePosition = attributedTitle.length > 0 ? .imageLeading : .imageOnly
self.button?.attributedTitle = attributedTitle
button?.imagePosition = attributedTitle.length > 0 ? .imageLeading : .imageOnly
button?.attributedTitle = attributedTitle
}
}
@ -88,12 +88,12 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
button.imageScaling = .scaleProportionallyDown
button.imageHugsTitle = true
button.attributedTitle = title
self.button?.imagePosition = title.length > 0 ? .imageLeading : .imageOnly
button?.imagePosition = title.length > 0 ? .imageLeading : .imageOnly
button.image = image
self.view = button
view = button
self.view.addGestureRecognizer(longClick)
self.view.addGestureRecognizer(singleClick)
view.addGestureRecognizer(longClick)
view.addGestureRecognizer(singleClick)
}
func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: NSGestureRecognizer) -> Bool {
@ -108,7 +108,7 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
switch gr.state {
case .ended:
hf.tap(strong: 2)
self.tapClosure?()
tapClosure?()
break
default:
break
@ -130,19 +130,16 @@ class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegat
break
default:
break
}
}
}
class CustomHeightButton : NSButton {
class CustomHeightButton: NSButton {
override var intrinsicContentSize: NSSize {
var size = super.intrinsicContentSize
size.height = 30
return size
}
}
class CustomButtonCell: NSButtonCell {
@ -155,32 +152,30 @@ class CustomButtonCell: NSButtonCell {
override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) {
super.highlight(flag, withFrame: cellFrame, in: controlView)
if !self.isBordered {
if !isBordered {
if flag {
self.setAttributedTitle(self.attributedTitle, withColor: .lightGray)
setAttributedTitle(attributedTitle, withColor: .lightGray)
} 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")
}
func setAttributedTitle(_ title: NSAttributedString, withColor color: NSColor) {
let attrTitle = NSMutableAttributedString(attributedString: title)
attrTitle.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attrTitle.length))
self.attributedTitle = attrTitle
attributedTitle = attrTitle
}
}
extension String {
var defaultTouchbarAttributedString: NSAttributedString {
let attrTitle = NSMutableAttributedString(string: self, attributes: [.foregroundColor: NSColor.white, .font: NSFont.systemFont(ofSize: 15, weight: .regular), .baselineOffset: 1])
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: self.count))
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: count))
return attrTitle
}
}

View File

@ -9,9 +9,9 @@
import Foundation
class CustomSliderCell: NSSliderCell {
var knobImage:NSImage!
private var _currentKnobRect:NSRect!
private var _barRect:NSRect!
var knobImage: NSImage!
private var _currentKnobRect: NSRect!
private var _barRect: NSRect!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
@ -21,22 +21,22 @@ class CustomSliderCell: NSSliderCell {
super.init()
}
init(knob:NSImage?) {
knobImage = knob;
init(knob: NSImage?) {
knobImage = knob
super.init()
}
override func drawKnob(_ knobRect: NSRect) {
if (knobImage == nil) {
if knobImage == nil {
super.drawKnob(knobRect)
return;
return
}
_currentKnobRect = knobRect;
_currentKnobRect = knobRect
drawBar(inside: _barRect, flipped: true)
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 x = (knobRect.origin.x * (_barRect.size.width - (knobImage.size.width - knobRect.size.width)) / _barRect.size.width) + 1
let y = knobRect.origin.y + 3
knobImage.draw(
at: NSPoint(x: x, y: y),
@ -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
let barRadius = CGFloat(2)
@ -60,16 +60,15 @@ class CustomSliderCell: NSSliderCell {
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)
NSColor.darkGray.setFill()
active.fill()
}
}
class CustomSlider:NSSlider {
var currentValue:CGFloat = 0
class CustomSlider: NSSlider {
var currentValue: CGFloat = 0
override func setNeedsDisplay(_ invalidRect: NSRect) {
super.setNeedsDisplay(invalidRect)
@ -77,15 +76,15 @@ class CustomSlider:NSSlider {
override func awakeFromNib() {
super.awakeFromNib()
if ((self.cell?.isKind(of: CustomSliderCell.self)) == false) {
let cell:CustomSliderCell = CustomSliderCell()
if (cell?.isKind(of: CustomSliderCell.self)) == false {
let cell: CustomSliderCell = CustomSliderCell()
self.cell = cell
}
}
convenience init(knob:NSImage) {
convenience init(knob: NSImage) {
self.init()
self.cell = CustomSliderCell(knob: knob)
cell = CustomSliderCell(knob: knob)
}
required init?(coder: NSCoder) {
@ -101,7 +100,7 @@ class CustomSlider:NSSlider {
return cell.knobImage
}
func setKnobImage(image:NSImage) {
func setKnobImage(image: NSImage) {
let cell = self.cell as! CustomSliderCell
cell.knobImage = image
}

View File

@ -11,9 +11,7 @@ import Foundation
#endif
extension String {
var ifNotEmpty: String? {
return self.count > 0 ? self : nil
return count > 0 ? self : nil
}
}

View File

@ -10,7 +10,7 @@ import IOKit
class HapticFeedback {
private var actuatorRef: CFTypeRef?
private var deviceID: UInt64 = 0x200000001000000
private var deviceID: UInt64 = 0x200_0000_0100_0000
private var error: IOReturn = 0
// Don't know how to do strong is enum one of
@ -24,7 +24,7 @@ class HapticFeedback {
// 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`
func tap(strong:Int32) -> Void {
func tap(strong: Int32) {
actuatorRef = MTActuatorCreateFromDeviceID(deviceID).takeRetainedValue()
guard actuatorRef != nil else {
@ -53,5 +53,3 @@ class HapticFeedback {
return
}
}

View File

@ -19,7 +19,7 @@
<key>CFBundleShortVersionString</key>
<string>0.18.5</string>
<key>CFBundleVersion</key>
<string>79</string>
<string>82</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.utilities</string>
<key>LSMinimumSystemVersion</key>

View File

@ -1,9 +1,9 @@
import Foundation
import AppKit
import Foundation
extension Data {
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)!)
}
}
@ -17,7 +17,7 @@ struct BarItemDefinition: Decodable {
case type
}
init(type: ItemType, action: ActionType, longAction: LongActionType, additionalParameters: [GeneralParameters.CodingKeys:GeneralParameter]) {
init(type: ItemType, action: ActionType, longAction: LongActionType, additionalParameters: [GeneralParameters.CodingKeys: GeneralParameter]) {
self.type = type
self.action = action
self.longAction = longAction
@ -38,68 +38,127 @@ struct BarItemDefinition: Decodable {
self.init(type: .staticButton(title: "unknown"), action: .none, longAction: .none, additionalParameters: additionalParameters)
}
}
}
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] = [
"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
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
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
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
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
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
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
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
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
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
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
enum CodingKeys: String, CodingKey { case refreshInterval; case units; case api_key ; case icon_type }
enum CodingKeys: String, CodingKey { case refreshInterval; case units; case api_key; case icon_type }
let container = try decoder.container(keyedBy: CodingKeys.self)
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
let units = try container.decodeIfPresent(String.self, forKey: .units)
@ -107,7 +166,12 @@ class SupportedTypesHolder {
let icon_type = try container.decodeIfPresent(String.self, forKey: .icon_type)
let action = try ActionType(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
@ -118,24 +182,49 @@ class SupportedTypesHolder {
let to = try container.decodeIfPresent(String.self, forKey: .to)
let action = try ActionType(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
return (item: .dock(), action: .none, longAction: .none, parameters: [:])
"dock": { _ in
(
item: .dock(),
action: .none,
longAction: .none,
parameters: [:]
)
},
"inputsource": { decoder in
return (item: .inputsource(), action: .none, longAction: .none, parameters: [:])
"inputsource": { _ in
(
item: .inputsource(),
action: .none,
longAction: .none,
parameters: [:]
)
},
"volume": { decoder in
enum CodingKeys: String, CodingKey { case image }
let container = try decoder.container(keyedBy: CodingKeys.self)
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 {
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 interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
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 {
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
enum CodingKeys: String, CodingKey { case refreshInterval }
@ -178,8 +287,8 @@ class SupportedTypesHolder {
)
},
"nightShift": {_ in
return (
"nightShift": { _ in
(
item: .nightShift(),
action: .none,
longAction: .none,
@ -188,21 +297,20 @@ class SupportedTypesHolder {
},
"dnd": { _ in
return (
(
item: .dnd(),
action: .none,
longAction: .none,
parameters: [:]
)
}
},
]
static let sharedInstance = SupportedTypesHolder()
func lookup(by type: String) -> ParametersDecoder {
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) {
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 type = try container.decode(ItemTypeRaw.self, forKey: .type)
switch type {
case .appleScriptTitledButton:
let source = try container.decode(Source.self, forKey: .source)
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
@ -337,7 +449,7 @@ enum ActionType: Decodable {
case keyPress(keycode: Int)
case appleScript(source: SourceProtocol)
case shellScript(executable: String, parameters: [String])
case custom(closure: ()->())
case custom(closure: () -> Void)
case openUrl(url: String)
private enum CodingKeys: String, CodingKey {
@ -389,14 +501,13 @@ enum ActionType: Decodable {
}
}
enum LongActionType: Decodable {
case none
case hidKey(keycode: Int32)
case keyPress(keycode: Int)
case appleScript(source: SourceProtocol)
case shellScript(executable: String, parameters: [String])
case custom(closure: ()->())
case custom(closure: () -> Void)
case openUrl(url: String)
private enum CodingKeys: String, CodingKey {
@ -448,14 +559,13 @@ enum LongActionType: Decodable {
}
}
enum GeneralParameter {
case width(_: CGFloat)
case image(source: SourceProtocol)
case align(_: Align)
case bordered(_: Bool)
case background(_:NSColor)
case title(_:String)
case background(_: NSColor)
case title(_: String)
}
struct GeneralParameters: Decodable {
@ -532,7 +642,7 @@ struct Source: Decodable, SourceProtocol {
}
var appleScript: NSAppleScript? {
return filePath?.fileURL.appleScript ?? self.string?.appleScript
return filePath?.fileURL.appleScript ?? string?.appleScript
}
private init(filePath: String?, base64: String?, inline: String?) {
@ -577,7 +687,6 @@ extension String {
var encoding: String.Encoding = .utf8
return try? String(contentsOfFile: self, usedEncoding: &encoding)
}
}
extension Data {
@ -608,7 +717,7 @@ extension String {
extension URL {
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)
}
}

View File

@ -18,7 +18,7 @@ struct GenericKeyPress: KeyPress {
}
extension KeyPress {
func send () {
func send() {
let src = CGEventSource(stateID: .hidSystemState)
let keyDown = CGEvent(keyboardEventSource: src, virtualKey: keyCode, keyDown: true)
let keyUp = CGEvent(keyboardEventSource: src, virtualKey: keyCode, keyDown: false)

View File

@ -12,20 +12,20 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
stackView.orientation = .horizontal
let scrollView = NSScrollView(frame: CGRect(origin: .zero, size: stackView.fittingSize))
scrollView.documentView = stackView
self.view = scrollView
view = scrollView
let twofingers = NSPanGestureRecognizer(target: self, action: #selector(twofingersHandler(_:)))
twofingers.allowedTouchTypes = .direct
twofingers.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(twofingers)
view.addGestureRecognizer(twofingers)
let threefingers = NSPanGestureRecognizer(target: self, action: #selector(threefingersHandler(_:)))
threefingers.allowedTouchTypes = .direct
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")
}
@ -36,7 +36,7 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
case .began:
twofingersPrev = position
case .changed:
if (((position-twofingersPrev) > 10) || ((twofingersPrev-position) > 10)) {
if ((position - twofingersPrev) > 10) || ((twofingersPrev - position) > 10) {
if position > twofingersPrev {
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
} else if position < twofingersPrev {
@ -58,7 +58,7 @@ class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
case .began:
threefingersPrev = position
case .changed:
if (((position-threefingersPrev) > 15) || ((threefingersPrev-position) > 15)) {
if ((position - threefingersPrev) > 15) || ((threefingersPrev - position) > 15) {
if position > threefingersPrev {
GenericKeyPress(keyCode: CGKeyCode(144)).send()
} else if position < threefingersPrev {

View File

@ -6,7 +6,7 @@
// 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, *) {
NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
} 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, *) {
NSTouchBar.presentSystemModalTouchBar(touchBar, placement: placement, systemTrayItemIdentifier: identifier)
} 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, *) {
NSTouchBar.minimizeSystemModalTouchBar(touchBar)
} else {

View File

@ -8,7 +8,6 @@
import Cocoa
class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource {
private var scrubber: NSScrubber!
private let hf: HapticFeedback = HapticFeedback()
@ -23,22 +22,20 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
private var runningAppsIdentifiers: [String] = []
private var frontmostApplicationIdentifier: String? {
get {
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
return frontmostId
}
}
private var applications: [DockItem] = []
override init(identifier: NSTouchBarItem.Identifier) {
super.init(identifier: identifier)
scrubber = NSScrubber();
scrubber = NSScrubber()
scrubber.delegate = self
scrubber.dataSource = self
scrubber.mode = .free // .fixed
let layout = NSScrubberFlowLayout();
let layout = NSScrubberFlowLayout()
layout.itemSize = NSSize(width: 36, height: 32)
layout.itemSpacing = 2
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)
if let persistent = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.dock.persistent") {
self.persistentAppIdentifiers = persistent
persistentAppIdentifiers = persistent
}
updateRunningApplication()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func activeApplicationChanged(n: Notification) {
@objc func activeApplicationChanged(n _: Notification) {
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()
}
@ -86,7 +83,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
scrubber.selectedIndex = index ?? 0
}
public func numberOfItems(for scrubber: NSScrubber) -> Int {
public func numberOfItems(for _: NSScrubber) -> Int {
return applications.count
}
@ -105,7 +102,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
let dotView = NSView(frame: .zero)
dotView.wantsLayer = true
if self.runningAppsIdentifiers.contains(app.bundleIdentifier!) {
if runningAppsIdentifiers.contains(app.bundleIdentifier!) {
dotView.layer?.backgroundColor = NSColor.white.cgColor
} else {
dotView.layer?.backgroundColor = NSColor.black.cgColor
@ -118,44 +115,44 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
return item
}
public func didBeginInteracting(with scrubber: NSScrubber) {
public func didBeginInteracting(with _: NSScrubber) {
stopTimer()
self.ticks = 0
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(checkTimer), userInfo: nil, repeats: true)
ticks = 0
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(checkTimer), userInfo: nil, repeats: true)
}
@objc private func checkTimer() {
self.ticks += 1
ticks += 1
if (self.ticks == minTicks) {
if ticks == minTicks {
hf.tap(strong: 2)
}
if (self.ticks > maxTicks) {
if ticks > maxTicks {
stopTimer()
hf.tap(strong: 6)
}
}
private func stopTimer() {
self.timer?.invalidate()
self.timer = nil
self.lastSelected = 0
timer?.invalidate()
timer = nil
lastSelected = 0
}
public func didCancelInteracting(with scrubber: NSScrubber) {
public func didCancelInteracting(with _: NSScrubber) {
stopTimer()
}
public func didFinishInteracting(with scrubber: NSScrubber) {
stopTimer()
if (ticks == 0) {
if ticks == 0 {
return
}
if (self.ticks >= minTicks && scrubber.selectedIndex > 0) {
self.longPress(selected: scrubber.selectedIndex)
if ticks >= minTicks && scrubber.selectedIndex > 0 {
longPress(selected: scrubber.selectedIndex)
return
}
@ -176,7 +173,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
private func longPress(selected: Int) {
let bundleIdentifier = applications[selected].bundleIdentifier
if (self.ticks > maxTicks) {
if ticks > maxTicks {
if let processIdentifier = applications[selected].pid {
if !(NSRunningApplication(processIdentifier: processIdentifier)?.terminate())! {
NSRunningApplication(processIdentifier: processIdentifier)?.forceTerminate()
@ -185,26 +182,26 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
} else {
hf.tap(strong: 6)
if let index = self.persistentAppIdentifiers.index(of: bundleIdentifier!) {
self.persistentAppIdentifiers.remove(at: index)
persistentAppIdentifiers.remove(at: index)
} 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()
}
self.ticks = 0
ticks = 0
updateRunningApplication()
}
private func launchedApplications() -> [DockItem] {
self.runningAppsIdentifiers = []
runningAppsIdentifiers = []
var returnable: [DockItem] = []
for app in NSWorkspace.shared.runningApplications {
guard app.activationPolicy == NSApplication.ActivationPolicy.regular 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)
returnable.append(dockItem)
@ -212,7 +209,7 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
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 let appPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier!) {
return NSWorkspace.shared.icon(forFile: appPath)
@ -227,12 +224,11 @@ class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrub
return genericIcon ?? NSImage(size: .zero)
}
public func getDockPersistentAppsList() -> [DockItem] {
var returnable: [DockItem] = []
for bundleIdentifier in persistentAppIdentifiers {
if !self.runningAppsIdentifiers.contains(bundleIdentifier) {
if !runningAppsIdentifiers.contains(bundleIdentifier) {
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier))
returnable.append(dockItem)
}

View File

@ -6,8 +6,8 @@
// Copyright © 2018 Anton Palgunov. All rights reserved.
//
import IOKit.ps
import Foundation
import IOKit.ps
class BatteryBarItem: CustomButtonTouchBarItem {
private let batteryInfo = BatteryInfo()
@ -18,15 +18,15 @@ class BatteryBarItem: CustomButtonTouchBarItem {
batteryInfo.start { [weak self] in
self?.refresh()
}
self.refresh()
refresh()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func refresh() {
self.attributedTitle = self.batteryInfo.formattedInfo()
attributedTitle = batteryInfo.formattedInfo()
}
deinit {
@ -42,14 +42,14 @@ class BatteryInfo: NSObject {
var isCharging: Bool = false
var ACPower: String = ""
var timeRemaining: String = ""
var notifyBlock: ()->() = {}
var loop:CFRunLoopSource?
var notifyBlock: () -> Void = {}
var loop: CFRunLoopSource?
func start(notifyBlock: @escaping ()->()) {
func start(notifyBlock: @escaping () -> Void) {
self.notifyBlock = notifyBlock
let opaque = Unmanaged.passRetained(self).toOpaque()
let context = UnsafeMutableRawPointer(opaque)
loop = IOPSNotificationCreateRunLoopSource({ (context) in
loop = IOPSNotificationCreateRunLoopSource({ context in
guard let ctx = context else {
return
}
@ -61,7 +61,7 @@ class BatteryInfo: NSObject {
}
func stop() {
self.notifyBlock = {}
notifyBlock = {}
guard let loop = self.loop else {
return
}
@ -76,32 +76,32 @@ class BatteryInfo: NSObject {
for ps in psList {
if let psDesc = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
let current = psDesc[kIOPSCurrentCapacityKey]
if (current != nil) {
if current != nil {
self.current = current as! Int
}
let timeToEmpty = psDesc[kIOPSTimeToEmptyKey]
if (timeToEmpty != nil) {
if timeToEmpty != nil {
self.timeToEmpty = timeToEmpty as! Int
}
let timeToFull = psDesc[kIOPSTimeToFullChargeKey]
if (timeToFull != nil) {
if timeToFull != nil {
self.timeToFull = timeToFull as! Int
}
let isCharged = psDesc[kIOPSIsChargedKey]
if (isCharged != nil) {
if isCharged != nil {
self.isCharged = isCharged as! Bool
}
let isCharging = psDesc[kIOPSIsChargingKey]
if (isCharging != nil) {
if isCharging != nil {
self.isCharging = isCharging as! Bool
}
let ACPower = psDesc[kIOPSPowerSourceStateKey]
if (ACPower != nil) {
if ACPower != nil {
self.ACPower = ACPower as! String
}
}
@ -109,7 +109,7 @@ class BatteryInfo: NSObject {
}
func getFormattedTime(time: Int) -> String {
if (time > 0) {
if time > 0 {
let timeFormatted = NSString(format: " %d:%02d", time / 60, time % 60) as String
return timeFormatted
}
@ -119,7 +119,7 @@ class BatteryInfo: NSObject {
public func formattedInfo() -> NSAttributedString {
var title = ""
self.getPSInfo()
getPSInfo()
if ACPower == "AC Power" {
if current < 100 {
@ -143,5 +143,4 @@ class BatteryInfo: NSObject {
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
return newTitle
}
}

View File

@ -1,6 +1,6 @@
import Cocoa
import AppKit
import AVFoundation
import Cocoa
import CoreAudio
class BrightnessViewController: NSCustomTouchBarItem {
@ -9,7 +9,7 @@ class BrightnessViewController: NSCustomTouchBarItem {
init(identifier: NSTouchBarItem.Identifier, refreshInterval: Double, image: NSImage? = nil) {
super.init(identifier: identifier)
if (image == nil) {
if image == nil {
sliderItem = CustomSlider()
} else {
sliderItem = CustomSlider(knob: image!)
@ -20,13 +20,13 @@ class BrightnessViewController: NSCustomTouchBarItem {
sliderItem.maxValue = 100.0
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)
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@ -42,13 +42,13 @@ class BrightnessViewController: NSCustomTouchBarItem {
@objc func sliderValueChanged(_ sender: Any) {
if let sliderItem = sender as? NSSlider {
setBrightness(level: Float32(sliderItem.intValue)/100.0)
setBrightness(level: Float32(sliderItem.intValue) / 100.0)
}
}
private func getBrightness() -> Float32 {
if #available(OSX 10.13, *) {
return Float32(CoreDisplay_Display_GetUserBrightness(0));
return Float32(CoreDisplay_Display_GetUserBrightness(0))
} else {
var level: Float32 = 0.5
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
@ -60,13 +60,12 @@ class BrightnessViewController: NSCustomTouchBarItem {
private func setBrightness(level: Float) {
if #available(OSX 10.13, *) {
CoreDisplay_Display_SetUserBrightness(0, Double(level));
CoreDisplay_Display_SetUserBrightness(0, Double(level))
} else {
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
IODisplaySetFloatParameter(service, 1, kIODisplayBrightnessKey as CFString, level)
IOObjectRelease(service)
}
}
}

View File

@ -45,7 +45,7 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
if let prefix = currencies[from] {
self.prefix = prefix
} else {
self.prefix = from
prefix = from
}
super.init(identifier: identifier, title: "")
@ -59,21 +59,21 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
updateCurrency()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func updateCurrency() {
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 {
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]
var value: Float32!
if let data_array = json["data"] as? [String : AnyObject] {
if let rates = data_array["rates"] as? [String : AnyObject] {
if let data_array = json["data"] as? [String: AnyObject] {
if let rates = data_array["rates"] as? [String: AnyObject] {
if let item = rates["\(self.to)"] as? String {
value = Float32(item)
}
@ -103,13 +103,13 @@ class CurrencyBarItem: CustomButtonTouchBarItem {
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])
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
self.attributedTitle = newTitle
attributedTitle = newTitle
}
}

View File

@ -8,22 +8,22 @@
import Foundation
class DnDBarItem : CustomButtonTouchBarItem {
class DnDBarItem: CustomButtonTouchBarItem {
private var timer: Timer!
init(identifier: NSTouchBarItem.Identifier) {
super.init(identifier: identifier, title: "")
self.isBordered = false
self.setWidth(value: 32)
isBordered = false
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)
self.refresh()
refresh()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@ -33,7 +33,7 @@ class DnDBarItem : CustomButtonTouchBarItem {
}
@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")
}
}
@ -67,7 +67,7 @@ public struct DoNotDisturb {
commitChanges()
}
static var isEnabled:Bool {
static var isEnabled: Bool {
get {
return CFPreferencesGetAppBooleanValue("doNotDisturb" as CFString, appId, nil)
}

View File

@ -8,7 +8,6 @@
import Cocoa
class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
var jsonItems: [BarItemDefinition]
var itemDefinitions: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
@ -23,37 +22,35 @@ class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
init(identifier: NSTouchBarItem.Identifier, items: [BarItemDefinition]) {
jsonItems = items
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")
}
deinit {
deinit {}
}
@objc override func showPopover(_: Any?) {
itemDefinitions = [:]
items = [:]
leftIdentifiers = []
centerItems = []
rightIdentifiers = []
@objc override func showPopover(_ sender: Any?) {
self.itemDefinitions = [:]
self.items = [:]
self.leftIdentifiers = []
self.centerItems = []
self.rightIdentifiers = []
self.loadItemDefinitions(jsonItems: jsonItems)
self.createItems()
loadItemDefinitions(jsonItems: jsonItems)
createItems()
centerItems = centerIdentifiers.compactMap({ (identifier) -> NSTouchBarItem? in
return items[identifier]
items[identifier]
})
self.centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
self.scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
TouchBarController.shared.touchBar.delegate = self
TouchBarController.shared.touchBar.defaultItemIdentifiers = []
TouchBarController.shared.touchBar.defaultItemIdentifiers = self.leftIdentifiers + [centerScrollArea] + self.rightIdentifiers
TouchBarController.shared.touchBar.defaultItemIdentifiers = leftIdentifiers + [centerScrollArea] + rightIdentifiers
if TouchBarController.shared.showControlStripState {
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 {
return self.scrollArea
return scrollArea
}
guard let item = self.items[identifier],
@ -96,8 +93,8 @@ class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
}
func createItems() {
for (identifier, definition) in self.itemDefinitions {
self.items[identifier] = TouchBarController.shared.createItem(forIdentifier: identifier, definition: definition)
for (identifier, definition) in itemDefinitions {
items[identifier] = TouchBarController.shared.createItem(forIdentifier: identifier, definition: definition)
}
}
}

View File

@ -9,33 +9,32 @@
import Cocoa
class InputSourceBarItem: CustomButtonTouchBarItem {
fileprivate var notificationCenter: CFNotificationCenter
let buttonSize = NSSize(width: 21, height: 21)
init(identifier: NSTouchBarItem.Identifier) {
notificationCenter = CFNotificationCenterGetDistributedCenter();
notificationCenter = CFNotificationCenterGetDistributedCenter()
super.init(identifier: identifier, title: "")
observeIputSourceChangedNotification();
observeIputSourceChangedNotification()
textInputSourceDidChange()
self.tapClosure = { [weak self] in
tapClosure = { [weak self] in
self?.switchInputSource()
}
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()));
CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()))
}
@objc public func textInputSourceDidChange() {
let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
var iconImage: NSImage? = nil
var iconImage: NSImage?
if let imageURL = currentSource.iconImageURL,
let image = NSImage(contentsOf: imageURL) {
@ -46,10 +45,10 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
if let iconImage = iconImage {
iconImage.size = buttonSize
self.image = iconImage
self.title = ""
image = iconImage
title = ""
} else {
self.title = currentSource.name
title = currentSource.name
}
}
@ -65,15 +64,15 @@ class InputSourceBarItem: CustomButtonTouchBarItem {
})
for item in inputSources {
if (item.id != currentSource.id) {
if item.id != currentSource.id {
TISSelectInputSource(item)
break
}
}
}
@objc public func observeIputSourceChangedNotification(){
let callback: CFNotificationCallback = { center, observer, name, object, info in
@objc public func observeIputSourceChangedNotification() {
let callback: CFNotificationCallback = { _, observer, _, _, _ in
let mySelf = Unmanaged<InputSourceBarItem>.fromOpaque(observer!).takeUnretainedValue()
mySelf.textInputSourceDidChange()
}
@ -96,7 +95,7 @@ extension TISInputSource {
private func getProperty(_ key: CFString) -> AnyObject? {
let cfType = TISGetInputSourceProperty(self, key)
if (cfType != nil) {
if cfType != nil {
return Unmanaged<AnyObject>.fromOpaque(cfType!).takeUnretainedValue()
} else {
return nil
@ -131,4 +130,3 @@ extension TISInputSource {
return OpaquePointer(TISGetInputSourceProperty(self, kTISPropertyIconRef)) as IconRef?
}
}

View File

@ -20,51 +20,51 @@ class MusicBarItem: CustomButtonTouchBarItem {
"com.spotify.client",
"com.coppertino.Vox",
"com.google.Chrome",
"com.apple.Safari"
"com.apple.Safari",
]
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) {
self.interval = interval
super.init(identifier: identifier, title: "")
self.isBordered = false
isBordered = false
self.tapClosure = { [weak self] in self?.playPause() }
self.longTapClosure = { [weak self] in self?.nextTrack() }
tapClosure = { [weak self] in self?.playPause() }
longTapClosure = { [weak self] in self?.nextTrack() }
self.refreshAndSchedule()
refreshAndSchedule()
}
@objc func marquee(){
let str = self.title
if (str.count > 10) {
@objc func marquee() {
let str = title
if str.count > 10 {
let indexFirst = str.index(str.startIndex, offsetBy: 0)
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")
}
@objc func playPause() {
for ident in playerBundleIdentifiers {
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
if (musicPlayer.isRunning) {
if (musicPlayer.className == "SpotifyApplication") {
if musicPlayer.isRunning {
if musicPlayer.className == "SpotifyApplication" {
let mp = (musicPlayer as SpotifyApplication)
mp.playpause!()
return
} else if (musicPlayer.className == "ITunesApplication") {
} else if musicPlayer.className == "ITunesApplication" {
let mp = (musicPlayer as iTunesApplication)
mp.playpause!()
return
} else if (musicPlayer.className == "VOXApplication") {
} else if musicPlayer.className == "VOXApplication" {
let mp = (musicPlayer as VoxApplication)
mp.playpause!()
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'.
let safariApplication = musicPlayer as SafariApplication
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
@ -74,7 +74,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_play')[0].click()", in: tab)
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)
return
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
@ -112,23 +112,23 @@ class MusicBarItem: CustomButtonTouchBarItem {
@objc func nextTrack() {
for ident in playerBundleIdentifiers {
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
if (musicPlayer.isRunning) {
if (musicPlayer.className == "SpotifyApplication") {
if musicPlayer.isRunning {
if musicPlayer.className == "SpotifyApplication" {
let mp = (musicPlayer as SpotifyApplication)
mp.nextTrack!()
updatePlayer()
return
} else if (musicPlayer.className == "ITunesApplication") {
} else if musicPlayer.className == "ITunesApplication" {
let mp = (musicPlayer as iTunesApplication)
mp.nextTrack!()
updatePlayer()
return
} else if (musicPlayer.className == "VOXApplication") {
} else if musicPlayer.className == "VOXApplication" {
let mp = (musicPlayer as VoxApplication)
mp.next!()
updatePlayer()
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'.
let safariApplication = musicPlayer as SafariApplication
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)
updatePlayer()
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)
updatePlayer()
return
@ -171,15 +171,15 @@ class MusicBarItem: CustomButtonTouchBarItem {
for var ident in playerBundleIdentifiers {
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
if (musicPlayer.isRunning) {
if musicPlayer.isRunning {
var tempTitle = ""
if (musicPlayer.className == "SpotifyApplication") {
if musicPlayer.className == "SpotifyApplication" {
tempTitle = (musicPlayer as SpotifyApplication).title
} else if (musicPlayer.className == "ITunesApplication") {
} else if musicPlayer.className == "ITunesApplication" {
tempTitle = (musicPlayer as iTunesApplication).title
} else if (musicPlayer.className == "VOXApplication") {
} else if musicPlayer.className == "VOXApplication" {
tempTitle = (musicPlayer as VoxApplication).title
} else if (musicPlayer.className == "SafariApplication") {
} else if musicPlayer.className == "SafariApplication" {
let safariApplication = musicPlayer as SafariApplication
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
for window in safariWindows! {
@ -190,7 +190,7 @@ class MusicBarItem: CustomButtonTouchBarItem {
tempTitle = (tab.name)!
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)!
break
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
@ -202,18 +202,18 @@ class MusicBarItem: CustomButtonTouchBarItem {
if tempTitle == "" {
ident = ""
}
} else if (musicPlayer.className == "GoogleChromeApplication") {
} else if musicPlayer.className == "GoogleChromeApplication" {
let chromeApplication = musicPlayer as GoogleChromeApplication
let chromeWindows = chromeApplication.windows?().compactMap({ $0 as? GoogleChromeWindow })
for window in chromeWindows! {
for tab in window.tabs!() {
let tab = tab as! GoogleChromeTab
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
if (!(tab.title?.hasSuffix("на Яндекс.Музыке"))!) {
if !(tab.title?.hasSuffix("на Яндекс.Музыке"))! {
tempTitle = tab.title!
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!
break
} 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
} else {
self.songTitle = tempTitle
@ -265,18 +265,20 @@ class MusicBarItem: CustomButtonTouchBarItem {
}
@objc protocol SpotifyApplication {
@objc optional var currentTrack: SpotifyTrack {get}
@objc optional var currentTrack: SpotifyTrack { get }
@objc optional func nextTrack()
@objc optional func previousTrack()
@objc optional func playpause()
}
extension SBApplication: SpotifyApplication{}
extension SBApplication: SpotifyApplication {}
@objc protocol SpotifyTrack {
@objc optional var artist: String {get}
@objc optional var name: String {get}
@objc optional var artist: String { get }
@objc optional var name: String { get }
}
extension SBObject: SpotifyTrack{}
extension SBObject: SpotifyTrack {}
extension SpotifyApplication {
var title: String {
@ -285,20 +287,21 @@ extension SpotifyApplication {
}
}
@objc protocol iTunesApplication {
@objc optional var currentTrack: iTunesTrack {get}
@objc optional var currentTrack: iTunesTrack { get }
@objc optional func playpause()
@objc optional func nextTrack()
@objc optional func previousTrack()
}
extension SBApplication: iTunesApplication{}
extension SBApplication: iTunesApplication {}
@objc protocol iTunesTrack {
@objc optional var artist: String {get}
@objc optional var name: String {get}
@objc optional var artist: String { get }
@objc optional var name: String { get }
}
extension SBObject: iTunesTrack{}
extension SBObject: iTunesTrack {}
extension iTunesApplication {
var title: String {
@ -307,16 +310,15 @@ extension iTunesApplication {
}
}
@objc protocol VoxApplication {
@objc optional func playpause()
@objc optional func next()
@objc optional func previous()
@objc optional var track: String {get}
@objc optional var artist: String {get}
@objc optional var track: String { get }
@objc optional var artist: String { get }
}
extension SBApplication: VoxApplication{}
extension SBApplication: VoxApplication {}
extension VoxApplication {
var title: String {
@ -324,7 +326,6 @@ extension VoxApplication {
}
}
@objc public protocol SBObjectProtocol: NSObjectProtocol {
func get() -> Any!
}
@ -338,6 +339,7 @@ extension VoxApplication {
@objc optional func windows() -> SBElementArray
@objc optional func doJavaScript(_ x: String!, in in_: Any!) -> Any // Applies a string of JavaScript code to a document.
}
extension SBApplication: SafariApplication {}
@objc public protocol SafariWindow: SBObjectProtocol {
@ -346,36 +348,39 @@ extension SBApplication: SafariApplication {}
// @objc optional var document: SafariDocument { get } // The document whose contents are displayed in the window.
// @objc optional func setCurrentTab(_ currentTab: SafariTab!) // The current tab.
}
extension SBObject: SafariWindow {}
//@objc public protocol SafariDocument: SBObjectProtocol {
// @objc public protocol SafariDocument: SBObjectProtocol {
// @objc optional var name: String { get } // Its name.
// @objc optional var URL: String { get } // The current URL of the document.
//}
//extension SBObject: SafariDocument {}
// }
// extension SBObject: SafariDocument {}
@objc public protocol SafariTab: SBObjectProtocol {
@objc optional var URL: String { get } // The current URL of the tab.
@objc optional var name: String { get } // The name of the tab.
}
extension SBObject: SafariTab {}
@objc public protocol GoogleChromeApplication: SBApplicationProtocol {
@objc optional func windows() -> SBElementArray
@objc optional func executeJavaScript(javascript: String!) -> Any // Applies a string of JavaScript code to a document. //, id: Any!
}
extension SBApplication: GoogleChromeApplication {}
@objc public protocol GoogleChromeWindow: SBObjectProtocol {
@objc optional var name: String { get } // The title of the window.
@objc optional func tabs() -> SBElementArray
}
extension SBObject: GoogleChromeWindow {}
@objc public protocol GoogleChromeTab: SBObjectProtocol {
@objc optional var URL: String { get } // The current URL of the tab.
@objc optional var title: String { get } // The name of the tab.
}
extension SBObject: GoogleChromeTab {}

View File

@ -19,35 +19,35 @@ class NightShiftBarItem: CustomButtonTouchBarItem {
}
private var isNightShiftEnabled: Bool {
return self.blueLightStatus.enabled.boolValue
return blueLightStatus.enabled.boolValue
}
private func setNightShift(state: Bool) {
self.nsclient.setEnabled(state)
nsclient.setEnabled(state)
}
init(identifier: NSTouchBarItem.Identifier) {
super.init(identifier: identifier, title: "")
self.isBordered = false
self.setWidth(value: 28)
isBordered = false
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)
self.refresh()
refresh()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func nightShiftAction() {
self.setNightShift(state: !self.isNightShiftEnabled)
self.refresh()
setNightShift(state: !isNightShiftEnabled)
refresh()
}
@objc func refresh() {
self.image = isNightShiftEnabled ? #imageLiteral(resourceName: "nightShiftOn") : #imageLiteral(resourceName: "nightShiftOff")
image = isNightShiftEnabled ? #imageLiteral(resourceName: "nightShiftOn") : #imageLiteral(resourceName: "nightShiftOff")
}
}

View File

@ -8,16 +8,15 @@ class TimeTouchBarItem: CustomButtonTouchBarItem {
dateFormatter.setLocalizedDateFormatFromTemplate(formatTemplate)
super.init(identifier: identifier, title: " ")
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
self.isBordered = false
isBordered = false
updateTime()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func updateTime() {
self.title = self.dateFormatter.string(from: Date())
title = dateFormatter.string(from: Date())
}
}

View File

@ -1,6 +1,6 @@
import Cocoa
import AppKit
import AVFoundation
import Cocoa
import CoreAudio
class VolumeViewController: NSCustomTouchBarItem {
@ -12,11 +12,12 @@ class VolumeViewController: NSCustomTouchBarItem {
var forPropertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
mScope: kAudioDevicePropertyScopeOutput,
mElement: kAudioObjectPropertyElementMaster)
mElement: kAudioObjectPropertyElementMaster
)
AudioObjectAddPropertyListenerBlock(defaultDeviceID, &forPropertyAddress, nil, audioObjectPropertyListenerBlock)
if (image == nil) {
if image == nil {
sliderItem = CustomSlider()
} else {
sliderItem = CustomSlider(knob: image!)
@ -25,18 +26,18 @@ class VolumeViewController: NSCustomTouchBarItem {
sliderItem.action = #selector(VolumeViewController.sliderValueChanged(_:))
sliderItem.minValue = 0.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 {
self.sliderItem.floatValue = self.getInputGain() * 100
}
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@ -46,7 +47,7 @@ class VolumeViewController: NSCustomTouchBarItem {
@objc func sliderValueChanged(_ sender: Any) {
if let sliderItem = sender as? NSSlider {
_ = setInputGain(Float32(sliderItem.intValue)/100.0)
_ = setInputGain(Float32(sliderItem.intValue) / 100.0)
}
}
@ -76,9 +77,9 @@ class VolumeViewController: NSCustomTouchBarItem {
var inputVolume: Float32 = volume
if inputVolume == 0.0 {
_ = setMute( mute: 1)
_ = setMute(mute: 1)
} else {
_ = setMute( mute: 0)
_ = setMute(mute: 0)
}
let size: UInt32 = UInt32(MemoryLayout.size(ofValue: inputVolume))
@ -89,7 +90,7 @@ class VolumeViewController: NSCustomTouchBarItem {
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &inputVolume)
}
private func setMute( mute: Int) -> OSStatus {
private func setMute(mute: Int) -> OSStatus {
var muteVal: Int = mute
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress()
address.mSelector = AudioObjectPropertySelector(kAudioDevicePropertyMute)
@ -99,4 +100,3 @@ class VolumeViewController: NSCustomTouchBarItem {
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &muteVal)
}
}

View File

@ -20,7 +20,7 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
private let iconsText = ["01d": "", "01n": "", "02d": "", "02n": "", "03d": "", "03n": "", "04d": "", "04n": "", "09d": "", "09n": "", "10d": "", "10n": "", "11d": "", "11n": "", "13d": "", "13n": "", "50d": "", "50n": ""]
private var iconsSource: Dictionary<String, String>
private var manager:CLLocationManager!
private var manager: CLLocationManager!
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval, units: String, api_key: String, icon_type: String? = "text") {
activity = NSBackgroundActivityScheduler(identifier: "\(identifier.rawValue).updatecheck")
@ -51,7 +51,7 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
}
if !CLLocationManager.locationServicesEnabled() {
print("Location services not enabled");
print("Location services not enabled")
return
}
@ -69,24 +69,24 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
manager.startUpdatingLocation()
}
required init?(coder: NSCoder) {
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func updateWeather() {
if self.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)")!)
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=\(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 {
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]
// print(json)
var temperature: Int!
var condition_icon = ""
if let main = json["main"] as? [String : AnyObject] {
if let main = json["main"] as? [String: AnyObject] {
if let temp = main["temp"] as? Double {
temperature = Int(temp)
}
@ -115,25 +115,24 @@ class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
}
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!
self.location = lastLocation
location = lastLocation
if prev_location == nil {
updateWeather()
}
prev_location = lastLocation
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error);
func locationManager(_: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
func locationManager(_: CLLocationManager, didChangeAuthorization _: CLAuthorizationStatus) {
// print("inside didChangeAuthorization ");
updateWeather()
}
}