/varanus

Swift framework for managing both global and local hotkeys

Primary LanguageSwiftMIT LicenseMIT

varanus

Varanus is an OSX framework written in Swift responsible for managing both global and local application hotkeys.

varanus

The framework was named after the Varanus genus which monitor lizards are a part of, because, after all, the main function the framework exposes is to 'monitor' the key down events in the system.

How to include the framework in a project?

  1. Clone the Varanus repository
git clone https://github.com/gfjalar/varanus.git
  1. Open the project in XCode and build it
  2. In XCode, right click Varanus/Products/Varanus.framework and 'Show in Finder'
  3. Drag & drop Varanus.framework in the project
  4. Inside the project(General settings) add Varanus.framework to 'Embedded Binaries'

I found Haroon Baig's post very helpful when creating the framework

Usage

To import:

import Varanus

To create new monitor:

// Event lifetime equals 0.1 by default
// Event lifetime is the time that can pass between different keyDown events
//   for them to still be considered as simultaneous
// Monitor reacts to KeyDown events by default
let monitor = KeyMonitor(lifetime: 0.1, mask: .Down)

To create a hotkey:

// Creates a hotkey for Shift + Cmd + 'a' + 's'
let hotkey = KeyCombination(
	modifiers: [.Shift, .Cmd],
	codes: [0, 1]
)

To create a handler:

func handler(combination: KeyCombination) {
	let modifiers = combination.modifiers
	let codes = combination.codes
	println(combination)
}
// Or
func emptyHandler() {
	println("Handler")
}

To bind hotkey to the handler:

// Rebinding will overwrite the handler
monitor.bind(hotkey, to: handler)

To remove binding:

monitor.unbind(hotkey)

To add fallback handler:

monitor.register(handler)

To remove fallback handler:

monitor.unregister()

To start the monitor:

// To capture events when application is not active
monitor.startGlobal()

// To capture events when application is active
monitor.startLocal()

To stop the monitor:

monitor.stopGlobal()
monitor.stopLocal()

Why doesn't the global monitor work?

After Apple Documentation

A global event monitor looks for user-input events dispatched to applications other than the one in which it is installed. The monitor cannot modify an event or prevent its normal delivery. And it may only monitor key events if accessibility is enabled or if the application is trusted for accessibility.

To enable accessibility:

  1. Go to Apple -> System Preferences -> Security & Privacy -> Privacy -> Accessibility
  2. Click the lock to make changes
  3. Enable the app you created or XCode if still in development

TODO:

  • examples, how it works