Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4: Bitwise AND for NSEvent.modifierFlags [duplicate]

Tags:

swift

swift4

I'm trying to set up a hotkey (option-tab) using NSEvent.addGlobalMonitorForEvents

let keycode = 48 // tab
let keymask: NSEvent.ModifierFlags = .option

func handler(event: NSEvent!) {

    if event.keyCode == keycode && 
        event.modifierFlags == event.modifierFlags & keymask     {

        // do whatever

    }
}

NSEvent.addGlobalMonitorForEvents(matching: [.keyDown], handler: handler)

But I get this error in the bitwise AND part:

Cannot convert value of type 'NSEvent.ModifierFlags' to expected argument type 'UInt8'

Replacing event.ModifierFlags with UInt8(event.modifierFlags.rawValue) etc also fails.

How do I fix this?

Edit:

Directly comparing event.modifierFlags == keymask fails (Even when I press only option-tab (and no other modifier key)).

On printing event.modifierFlags to console, a different value gets printed depending on whether I press the left or right option keys.

print (event.modifierFlags) // prints: ModifierFlags(rawValue: 524576) using LEFT OPTION 
// and  ModifierFlags(rawValue: 524608) when using RIGHT OPTION.

print(keymask) // prints: ModifierFlags(rawValue: 524288)

At this point my vague hunch is that I need to ignore the lower order bits and compare only the higher order ones. I just don't know how to go about doing this.

like image 462
Anshuman Sharma Avatar asked Nov 12 '17 23:11

Anshuman Sharma


1 Answers

NSEvent.ModifierFlags is an OptionSet (which is a SetAlgebra). See the documentation for those as needed.

Given your current code, you basically want to see if the only flags set are those in the mask. But you do need to mask out for just the device independent flags.

Update your if as:

if event.keyCode == keyCode && event.modifierFlags.intersection(.deviceIndependentFlagsMask) == keymask {
}
like image 192
rmaddy Avatar answered Nov 02 '22 04:11

rmaddy