Created
July 4, 2018 12:20
-
-
Save koenbollen/00e7361aad237ddd0c64efc6a2b09e40 to your computer and use it in GitHub Desktop.
Commandline hotkey tool. Usage: `hotkey F12 say hello`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// #cgo LDFLAGS: -framework Carbon | |
// #include <Carbon/Carbon.h> | |
// extern void Callback(); | |
// void RunApplicationEventLoop(); | |
// static inline OSStatus handler(EventHandlerCallRef nextHandler, EventRef theEvent, void* userData) | |
// { | |
// Callback(); | |
// return 1; | |
// } | |
// static inline int Register(int key) { | |
// EventTypeSpec eventType; | |
// eventType.eventClass = kEventClassKeyboard; | |
// eventType.eventKind = kEventHotKeyPressed; | |
// | |
// InstallApplicationEventHandler(&handler, 1, &eventType, NULL, NULL); | |
// | |
// EventHotKeyID g_HotKeyID; | |
// g_HotKeyID.id = 1; | |
// | |
// EventHotKeyRef g_HotKeyRef; | |
// | |
// RegisterEventHotKey(key, 0, g_HotKeyID, GetApplicationEventTarget(), 0, &g_HotKeyRef); | |
// | |
// return 0; | |
// } | |
// static inline void Run() { | |
// RunApplicationEventLoop(); | |
// } | |
import "C" | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"os/exec" | |
"strings" | |
) | |
// Callback is called by the C binding | |
//export Callback | |
func Callback() { | |
if verbose { | |
fmt.Println(keyName, "pressed! running:", command) | |
} | |
cmd := exec.Command(command[0], command[1:]...) | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
err := cmd.Run() | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
} | |
} | |
var keys = map[string]C.int{ | |
"f1": C.kVK_F1, "f2": C.kVK_F2, "f3": C.kVK_F3, "f4": C.kVK_F4, | |
"f5": C.kVK_F5, "f6": C.kVK_F6, "f7": C.kVK_F7, "f8": C.kVK_F8, | |
"f9": C.kVK_F9, "f10": C.kVK_F10, "f11": C.kVK_F11, "f12": C.kVK_F12, | |
"f13": C.kVK_F13, "f14": C.kVK_F14, "f15": C.kVK_F15, "f16": C.kVK_F16, | |
"f17": C.kVK_F17, "f18": C.kVK_F18, "f19": C.kVK_F19, "f20": C.kVK_F20, | |
} | |
var verbose bool | |
var keyName string | |
var command []string | |
func main() { | |
flag.Usage = func() { | |
fmt.Println(" usage: hotkey [-v] KEY COMMAND [ARGS...]") | |
fmt.Println("example: hotkey F12 echo hello") | |
} | |
flag.BoolVar(&verbose, "v", false, "output key presses") | |
flag.Parse() | |
if flag.NArg() < 2 { | |
flag.Usage() | |
os.Exit(1) | |
} | |
args := flag.Args() | |
keyName = args[0] | |
command = args[1:] | |
key, found := keys[strings.ToLower(keyName)] | |
if !found { | |
fmt.Fprintf(os.Stderr, "error: key not supported: %s\n", keyName) | |
os.Exit(1) | |
} | |
C.Register(key) | |
C.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment