AppleScript and modifier keys

I have extension using AppleScript which alters behavior depending on pressed modifiers keys (so it uses ‘popclip modifier flags’ inside).

It also uses ‘keystroke’ command inside to control another application. The problem is that currently pressed modifiers are mixed into modifiers I give to ‘keystroke’, so target application gets invalid combination.

I found no easy way to wait until modifier keys are released from inside applescript, so it would be cool if PopClip either:

  1. wait until modifier keys are released before running script
  2. provide way to get currently pressed modifiers (not ones which were pressed during action invocation)

Hi

This is what I have cobbled together from looking at previous posts and various google results. It seems to work for me, but I am only checking for the Option key, so you may need to change things up a bit for your purposes.

The script below takes the selected text as the basis of the name of an environment file. If Option is pressed then it adds a “1” to the selected text. The result is then written to iTerm2 as part of a command to source the required environment.

# popclip
name: ADP_Env
requires: [ text copy ]
applescript: | 
  on setClipboard(newString)
    set the clipboard to newString as string
  end setClipboard
  
  use AppleScript version "2.4" -- Yosemite (10.10) or later
  use framework "Foundation"
  use framework "AppKit"
  property NSOptionKeyMask : a reference to 524288 -- 0x80000
  property hasOption : false
  set modFlags to "{popclip modifier flags}"
  set hasOption to ((modFlags div NSOptionKeyMask) mod 2) = 1
  --
  set theText to "{popclip text}"
  --
  property NSEvent : a reference to current application's NSEvent
  on getKeyStatus()
  -- Return status of the key - Up or Down
    set theFlag to NSEvent's modifierFlags() as integer
    set theMask to NSOptionKeyMask
    if ((theFlag div theMask) mod 2) = 0 then
      set keyStatus to "Up"
    else
      set keyStatus to "Down"
    end if
    return keyStatus
  end getKeyStatus
  
  delay 1
  
  if hasOption then
    set theText to theText & "1"
    -- wait for key up
    repeat until hasOption is false
      set keyStatus to getKeyStatus()
      if keyStatus = "Up" then
        set hasOption to false
      end if
      delay 0.1
    end repeat
  end if
  --
  tell application id "com.googlecode.iterm2"
    activate
    if exists (current window) then
      tell current session of (current window)
        write text "source " & theText & ".env"
      end tell
    end if
  end tell
1 Like