~habibalamin/Commandeer

Fix flag-release-while-command-held treated as command-pressed-alone
1 files changed, 24 insertions(+), 12 deletions(-)

M Commandeer/CommandPressToEscapePressTransformer.swift
M Commandeer/CommandPressToEscapePressTransformer.swift => Commandeer/CommandPressToEscapePressTransformer.swift +24 -12
@@ 9,13 9,18 @@
import Foundation
import AppKit

func keyEventCmdPressed(_ eventFlags: CGEventFlags) -> Bool
func keyEventCmdPressedAlone(_ event: CGEvent) -> Bool
{
  return
    (Int32(eventFlags.rawValue) & NX_DEVICELCMDKEYMASK) ==
    NX_DEVICELCMDKEYMASK ||
    (Int32(eventFlags.rawValue) & NX_DEVICERCMDKEYMASK) ==
    NX_DEVICERCMDKEYMASK
    Int32(event.flags.rawValue) ==
      NX_NONCOALSESCEDMASK | NX_COMMANDMASK | NX_DEVICELCMDKEYMASK ||
    Int32(event.flags.rawValue) ==
      NX_NONCOALSESCEDMASK | NX_COMMANDMASK | NX_DEVICERCMDKEYMASK
}

func keyEventNoFlagsPressed(_ event: CGEvent) -> Bool
{
  return Int32(event.flags.rawValue) == NX_NONCOALSESCEDMASK // no flags
}

func commandPressToEscapePressTransformer(proxy: CGEventTapProxy,


@@ 26,14 31,12 @@ func commandPressToEscapePressTransformer(proxy: CGEventTapProxy,
{
  if (event.type != .flagsChanged) {
    refcon?.storeBytes(of: nil, as: CGEvent?.self)
  } else if (keyEventCmdPressed(event.flags)) {
    refcon?.storeBytes(of: event, as: CGEvent?.self)
  } else if (refcon?.load(as: CGEvent?.self) != nil) {
    let currentKeyDown = refcon!.load(as: CGEvent.self)

    if (keyEventCmdPressed(currentKeyDown.flags) &&
        !keyEventCmdPressed(event.flags))
  } else if let currentKeyDown = refcon?.load(as: CGEvent?.self) {
    if (keyEventNoFlagsPressed(event) &&
      keyEventCmdPressedAlone(currentKeyDown))
    {
      refcon?.storeBytes(of: nil, as: CGEvent?.self)

      if (event.timestamp - currentKeyDown.timestamp <= 200_000_000) // ns
      {
        let eventSource = CGEventSource(event: event)


@@ 52,7 55,16 @@ func commandPressToEscapePressTransformer(proxy: CGEventTapProxy,

        return nil
      }
    } else if (keyEventCmdPressedAlone(event) &&
      !keyEventNoFlagsPressed(currentKeyDown))
    {
      // Don't treat this as a true cmd-pressed-alone to be stored,
      // treat it as whatever's already been stored.
    } else {
      refcon?.storeBytes(of: event, as: CGEvent?.self)
    }
  } else {
    refcon?.storeBytes(of: event, as: CGEvent?.self)
  }

  return Unmanaged.passRetained(event)