Typing a keyboard shortcut using rb-appscript - applescript

I'm trying to convert the following script to Ruby using rb-appscript:
-- Runs the keyboard shortcut for the provided application name.
-- applicationName - The name of the application to run the keyboard shortcut on.
-- key - The key to press. For example, this could be "n" or "q".
-- modifiersList - A list of modifiers for the keyboard shortcut. This could be something like
-- { command down } or { command down, shift down, option down }.
on runKeyboardShortcut(applicationName, key, modifiersList)
tell application applicationName to activate
tell application "System Events"
keystroke key using modifiersList
end tell
end runKeyboardShortcut
Here's what I have so far:
def run_keyboard_shortcut(application_name, key, modifiers_list)
Appscript.app.by_name(application_name).activate
Appscript.app.by_name("System Events").keystroke(key)
end
How do I add the modifiers to the keystroke command?

The solution is to do this:
def run_keyboard_shortcut(application_name, key, modifiers)
Appscript.app.by_name(application_name).activate
Appscript.app.by_name("System Events").keystroke(key, :using => modifiers)
end
run_keyboard_shortcut("Finder", "n", [ :command_down ])

Related

Automator Quick Action (AppleScript) for Deepl Translator

I have an Automator quick action (service) to get texts from applications and open them on the Deepl website to translate them. It works, but the spaces between the words get replaced with + signs. The translation is filled with + signs, like this:
"...+in+third+place+on+the+list+of+the+most+..."
What is causing this?
on run {input, parameters}
set output to "https://www.deepl.com/translator#pt/en/" & urldecode(input as string)
return output
end run
on urldecode(x)
set cmd to "'require \"cgi\"; puts CGI.escape(STDIN.read.chomp)'"
do shell script "echo " & quoted form of x & " | ruby -e " & cmd
end urldecode
I'd use 'Listing 32-7 AppleScriptObjC: Handler that URL encodes text' from Encoding and Decoding Text.
Example AppleScript code:
use framework "Foundation"
use scripting additions
on run {input, parameters}
set output to "https://www.deepl.com/translator#pt/en/" & encodeText(input as string)
return output
end run
on encodeText(theText)
set theString to stringWithString_(theText) of NSString of current application
set theEncoding to NSUTF8StringEncoding of current application
set theAdjustedString to stringByAddingPercentEscapesUsingEncoding_(theEncoding) of theString
return (theAdjustedString as string)
end encodeText

Automator + Applescript - An error “Can’t make "f" into type alias.” - text replacement

So I established to replace a specific text inside a text file using variables, but the problem is when it comes to the second variable/ another text it simply shows me this message: “Can’t make "f" into type alias.”
I don’t know what’s wrong with the code… when I’m using it for the first variable it simply works, how Can I fix it?
Thay’s how the code looks like and just simply does the job with the first variable
“use framework "Foundation"
use AppleScript version "2.4"
use scripting additions
property NSString : a reference to current application's NSString
on run {input, parameter}
set stringToFind to (item 1 of input) as text
set stringToReplace to (item 2 of input) as text
set theTextFile to (item 3 of input)
set theContent to read (theTextFile as alias) as text
set newContent to my replace_text(theContent, stringToFind, stringToReplace)
try
set fileRef to (open for access theTextFile with write permission)
set eof of fileRef to 0 # truncate file
write newContent to fileRef
close access fileRef
on error
close access fileRef
end try
# display dialog (item 1 of input) & return & (item 2 of input) & return & (item 3 of input)
return
end run
on replace_text(atext, xfind, xreplace)
return ((NSString's stringWithString:atext)'s stringByReplacingOccurrencesOfString:xfind withString:xreplace) as text
end replace_text”
But when I’m trying to use it for the second time in the same automator workflow it just gives me this message…
“Can’t make "f" into type alias.”
“F” - I typed as a variable that replaces the old text…
enter image description here
enter image description here
enter image description here
enter image description here

Signing Applescript Application So It Doesn't Ask For Password

I have an applescript application I wrote modifies my network settings to connect me to my vpn provider. Problem: It asks me for my password every time I want to run it.
Hopeful Solution: It runs without asking for a password.
(************************ Run *************************)
on run #{VPNconfiguration}
set rand_vpn to random_vpn()
set VPNconfiguration to pick_vpn(rand_vpn) # Returns a list with one item
set VPNconfiguration to item 1 of VPNconfiguration # Selects that item from the list
connect_vpn(VPNconfiguration)
end run
(******************** Random Vpn **********************)
on random_vpn()
set rand_vpn to some item of {"US-Cali", "US-West", "US-East", "US-Midwest", ¬
"US-Texas", "US-Flordia", "US-Seattle", "US-Siliconvallay", "US-NewYorkCity"}
return rand_vpn
end random_vpn
(********************* Pick Vpn ***********************)
on pick_vpn(rand_vpn)
set VPNconfiguration to choose from list {¬
"US-Cali", "US-West", "US-East", "US-Midwest", "US-Texas", "US-Flordia", ¬
"US-Seattle", "US-Siliconvallay", "US-NewYorkCity", "Mexico", "Brazil", ¬
"Canada", "Canada-Toronto", "UK-London", "UK-Southampton", "German", ¬
"France", "Switzerland", "Netherlands", "Sweden", "Romania", "Hong-Cong", ¬
"Isreal", "Russia", "Turkey", "Singapore", "Australia", "Australia-Melbourne", "Japan"} ¬
with title ¬
"VPN Connection Client" with prompt ¬
"Choose One Location" OK button name ¬
"This VPN" cancel button name ¬
"Quit" default items {rand_vpn}
if result = false then quit
return VPNconfiguration
end pick_vpn
(******************** Connect Vpn *********************)
on connect_vpn(VPNconfiguration)
tell application "System Events"
tell network preferences
tell current location
set aPPPoEService to a reference to configuration VPNconfiguration of service "AllVPNs"
connect aPPPoEService
end tell
end tell
end tell
end connect_vpn
(*********************** Quit *************************)
on quit
continue quit
end quit

Capturing An AppleEvent in Applescript

Ok Unity3d allows you to set your external script editor in the application preferences. So I want to use applescript to launch my own editor. This applescript has worked pretty well for me so far but I have been unable to jump to the line number.
According to Unity the "line number should be sent through a parameter in an AppleEvent. It should be of typeChar and of keyAEPosition ('kpos') The structure sent through this parameter has the following layout:"
struct TheSelectionRange
{
short unused1; // 0 (not used)
short lineNum; // line to select (<0 to specify range)
long startRange; // start of selection range (if line < 0)
long endRange; // end of selection range (if line < 0)
long unused2; // 0 (not used)
long theDate; // modification date/time
};
"lineNum should be populated with the correct line. The other fields will not be populated with anything than 0 and -1."
So how come I don't see any of this coming through my input? how do I capture this apple event?
My Script:
on run input
set element to item 1 of input
if (element is in {{}, {""}, ""}) then
return
else
tell application "System Events"
set ProcessList to name of every process
if "iTerm" is in ProcessList then
set iterm_running to true
else
set iterm_running to false
end if
log iterm_running
end tell
tell application "iTerm"
activate
if (count terminal) < 1 then
set term to (make new terminal)
else
set term to current terminal
end if
tell term
set create_session to false
try
do shell script ("/usr/local/bin/vim --servername UNITY --remote-send ''")
set create_session to false
on error errorMessage number errorNumber
set create_session to true
end try
if iterm_running then
if create_session then
launch session "Default Session"
activate current session
tell current session
set name to "Unity"
write text "/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\""
end tell
else
do shell script ("/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\"")
end if
else
activate current session
tell current session
set name to "Unity"
write text "/usr/local/bin/vim --servername UNITY --remote-silent \"$(echo \"/Volumes/" & input & "\" | tr : /)\""
end tell
end if
end tell
end tell
end if
return input
end run
If you handle the open event, you should see some parameters, including the line number:
on open (x,y)
display dialog x
display dialog y
-- use x and y in your own script
end open

Look for file names that match a rule with Applescript

A client has a massive WordPress uploads folder with 7 or 8 size versions of each file.
I'm looking to filter out all images that have -NNNxNNN as part of the file name - "NNN" being any number. For eg:
Originally uploaded file: 7Metropolis711.jpg
Example resized version of same file: 7Metropolis711-792x373.jpg
I'm using Automator for this, and I'm just looking for the Applescript to filter out those files from the inputted folder of files.. IE:
Here is another approach:
on run {input}
set newList to {}
repeat with aFile in input
tell application "System Events" to set fileName to name of aFile
try
set variableName to do shell script "echo " & quoted form of fileName & " | grep -Eo [0-9]{3}x[0-9]{3}"
on error
set end of newList to (aFile's contents)
end try
end repeat
return newList
end run
Try this. You can see a handler "isFormatNNNxNNN(fileName)" which tests the file name for your format. Obviously remove the first 2 lines of the code. They're used so I could test this in AppleScript Editor. They should equal your input variable in Automator.
EDIT: based on your comments I modified the script to account for more than one "-" in the file name. Now I start looking at the text in front of the file extension since I assume your format is the last characters in the file name.
It didn't work in Automator because you have to put "on run {input, parameters}" around the code. I have done that now so just copy/paste this into automator.
on run {input, parameters}
set newList to {}
repeat with aFile in input
if not (my isFormatNNNxNNN(aFile)) then set end of newList to (contents of aFile)
end repeat
return newList
end run
on isFormatNNNxNNN(theFile)
set theBool to false
try
tell application "System Events"
set fileName to name of theFile
set fileExt to name extension of theFile
end tell
set endIndex to (count of fileExt) + 2
set nameText to text -(endIndex + 7) thru -endIndex of fileName
if nameText starts with "-" then
if character 5 of nameText is "x" then
-- test for numbers
text 2 thru 4 of nameText as number
text 6 thru 8 of nameText as number
set theBool to true
end if
end if
end try
return theBool
end isFormatNNNxNNN

Resources