Callback for key pressed?

Hi! Is there a callback that triggers when a key is pressed? I’m trying to set an alternative button title when opt is pressed, just like alternative menu titles. I get how to detect what button is pressed, but can’t find the right callback.

You can use this:

if (!_optionDownMonitor) {
	_optionDownMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged handler:^NSEvent *(NSEvent *event) {
		self.optionIsDown = (event.modifierFlags & NSEventModifierFlagOption) == NSEventModifierFlagOption;
		return event;

I have never used that from python. It might looks something like this:

from AppKit import NSEventModifierFlagOption

def mask_handler(event):
	self.optionIsDown((event.modifierFlags() & NSEventModifierFlagOption) == NSEventModifierFlagOption)
	return event
if self._optionDownMonitor is None:
	self._optionDownMonitor = NSEvent.addLocalMonitorForEventsMatchingMask_handler_(NSEventMaskFlagsChanged, Mask_handler_)

Put that code somewhere in the view loading/setup code.

Does this help?

(PyObjC support for “blocks” — PyObjC - the Python to Objective-C bridge)

1 Like

Awesome, thank you!

That works perfectly, but seems like it overrides the behavior of Glyphs.currentDocument.windowController().AltKey(). I can of course get around it, but in case some other tool relies on it, is there a way to do it non-destructively?

It shouldn’t be disturbing others. Can you show me your code (mostly that callback).

It’s a Palette plugin, I just added these:

def settings(self):
	NSEvent.addLocalMonitorForEventsMatchingMask_handler_( NSEventMaskFlagsChanged, self.mask_handler )

def mask_handler( self, event ):
	optPressed = ((event.modifierFlags() & NSEventModifierFlagOption) == NSEventModifierFlagOption)
	if optPressed:'Run, new tab')

With that, Glyphs.currentDocument.windowController().AltKey() from the plugin and from Macro panel always returns False

Don’t make the callback a method, just add it as a local function inside the method where you set it up.
And return the event in the callback.

1 Like

That works, thanks a lot!