Rev 5 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
//
// AppDelegate.swift
// GyroServer
//
// Created by Matteo Riva on 07/08/15.
// Copyright © 2015 Matteo Riva. All rights reserved.
//
import Cocoa
import CoreServices
let ActiveScreenDidChangeNotification = Notification.Name("ActiveScreenDidChangeNotification")
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mouseHandler: MouseHandler!
let statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
let screenMenu = NSMenu()
func applicationDidFinishLaunching(_ aNotification: Notification) {
//Add menuItem to menu
let menu = NSMenu()
let screenItem = NSMenuItem()
screenItem.title = "act_screen".localized
for (i,_) in NSScreen.screens.enumerated() {
screenMenu.addItem(withTitle: "\(1 + i)", action: #selector(AppDelegate.setActiveScreen(_:)), keyEquivalent: "")
}
var selected = UserDefaults.standard.integer(forKey: "activeScreen")
let maxScreens = NSScreen.screens.count - 1
if maxScreens < selected {
selected = 0
UserDefaults.standard.set(selected, forKey: "activeScreen")
}
screenMenu.item(at: selected)?.state = NSControl.StateValue.on
screenItem.submenu = screenMenu
menu.addItem(screenItem)
menu.addItem(withTitle: "exit".localized, action: #selector(AppDelegate.exitAction), keyEquivalent: "q")
statusBarItem.menu = menu
let icon = NSImage(named: NSImage.Name("statusIcon"))!
icon.isTemplate = true
statusBarItem.image = icon
mouseHandler = MouseHandler()
// attempt a keystroke ; if it fails, notify the user that he needs to allow the app
let script = NSAppleScript(source: "tell app \"System Events\"\n" +
" key down shift\n" +
" key up shift\n" +
"end tell")! // harmless keystroke
var error: NSDictionary? = nil
let resultMaybe = script.executeAndReturnError(&error) as NSAppleEventDescriptor?
if (resultMaybe == nil)
{
let myStringDict = error as? [String:AnyObject]
if (myStringDict?["NSAppleScriptErrorNumber"] as! Int16 == 1002) {
let alert = NSAlert()
alert.addButton(withTitle: "OK".localized)
alert.messageText = "system_message".localized + "\n" + (myStringDict?["NSAppleScriptErrorBriefMessage"] as! String)
alert.informativeText = "allow_perms".localized
alert.alertStyle = .warning
alert.runModal()
}
print (error as Any)
exit (1)
}
}
@objc func exitAction(){
NSApp.terminate(self)
}
@objc func setActiveScreen(_ sender: NSMenuItem) {
for (i,screen) in screenMenu.items.enumerated() {
if screen == sender {
sender.state = NSControl.StateValue.on
UserDefaults.standard.set(i, forKey: "activeScreen")
} else {
screen.state = NSControl.StateValue.off
}
}
NotificationCenter.default.post(name: ActiveScreenDidChangeNotification, object: nil)
}
}