How to use AppleScript with Calculator.app to Automatically select the number of Decimals - applescript

Every time I enter a number in Calculator.app I need to go the top menu and select:
View >> Decimal Places >> [0 , 15] And choose the number of decimals.
Is there a way to make an AppleScript that will automatically do so, based on the number I entered?
My input ways are:
by pasting the number
by typing the number
For the pasting part, if you PASTE a number ending in 0, Calculator.app won't show the 0, so it will show one decimal less than the reality. I don't know if this could be also overcome.
Example, if you paste: 12.30 it will show 12.3
if you type: 12.30 it will show 12.30

Building on the addendum to my answer to your other question How can I copy result from Calculator.app to the clipboard using AppleScript, here is a way the trap ⌘V in Calculator and set Calculator > View > Decimal Places to the number of decimal places of the number on the clipboard.
What the example AppleScript code does:
When pressing ⌘V in Calculator the contents of the clipboard is set to a variable and if it contains a decimal point it sets the Calculator > View > Decimal Places menu to the number of decimal places in the number, then keystrokes the number into Calculator. Note that keystroking the number would probably not require you to set the number of decimal places, however I'll leave that up to you to decide.
Example AppleScript code:
set theNumberToType to the clipboard as text
if theNumberToType contains "." then
set theNumberOfDecimalPlaces to count characters ((offset of "." in theNumberToType) + 1) thru -1 of theNumberToType
if theNumberOfDecimalPlaces is greater than 15 then set theNumberOfDecimalPlaces to 15
else
set theNumberOfDecimalPlaces to -1
end if
tell application "Calculator" to activate
tell application "System Events"
if theNumberOfDecimalPlaces is greater than -1 then
click (first menu item of menu 1 of menu item "Decimal Places" of menu 1 of menu bar item "View" of menu bar 1 of process "Calculator" whose name is theNumberOfDecimalPlaces)
end if
delay 0.1
keystroke theNumberToType
end tell
The example AppleScript code above is saved as CalculatorSetDecimalPlaces.applescript in: ~/.hammerspoon/Scripts/, like in my other answer to your other question.
Example Lua code:
-- Create a hotkey used to trap the command v shortcut and disable it.
-- It will then be enabled/disabled as Calculator is focused/unfocused.
-- When enabled and command v is pressed it runs the AppleScript script.
local applicationCalculatorCommandVHotkey = hs.hotkey.bind({"cmd"}, "V", function()
local asFile = "/.hammerspoon/Scripts/CalculatorSetDecimalPlaces.applescript"
local ok, status = hs.osascript.applescriptFromFile(os.getenv("HOME") .. asFile)
if not ok then
msg = "An error occurred running the CalculatorResultToClipboard script."
hs.notify.new({title="Hammerspoon", informativeText=msg}):send()
end
end)
applicationCalculatorCommandVHotkey:disable()
-- Add the following two line respectively before or after the lines
-- applicationCalculatorEnterHotkey:enable()
-- applicationCalculatorEnterHotkey:disable()
-- in either of the two methods presented in my other answer.
applicationCalculatorCommandVHotkey:enable()
applicationCalculatorCommandVHotkey:disable()
Notes:
With the example Lua code, as coded, the behavior of the ⌘V keyboard shortcut is only trapped and modified to trigger the example AppleScript code while Calculator has focus. The ⌘V keyboard shortcut should work normally in all other applications.
The example Lua code above is added to the ~/.hammerspoon/init.lua file from my other answer to your other question.
The example Lua code and API's of Hammerspoon and AppleScript code, shown above, were tested respectively with Hammerspoon and Script Editor under macOS Mojave and macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
Update using only Lua without AppleScript
The following example Lua code eliminates the use of AppleScript from both this answer and the code in the other answer to your other related question.
Overwriting the existing code, copy and paste this into your ~/.hammerspoon/init.lua file, save it and run Reload Config from the Hammerspoon menu on the menu bar.
I have performed all the various actions and calculations discussed in the comments and had no issues occur with this new code. Hopefully this will eliminate any issues you were having.
This should also run faster now that it does have to process AppleScript code as well.
Note that as coded it is not automatically reloading the configuration file as that just should not be necessary.
-- Create a hotkey used to trap the enter key and disable it.
-- It will then be enabled/disabled as Calculator is focused/unfocused
-- When enabled and the enter key is pressed it presses = then command C.
local applicationCalculatorEnterHotkey = hs.hotkey.bind({}, "return", function()
-- Press the '=' key to finish the calculation.
hs.eventtap.keyStroke({}, "=")
-- Copy the result to the clipboard.
hs.eventtap.keyStroke({"cmd"}, "C")
end)
applicationCalculatorEnterHotkey:disable()
-- Create a hotkey used to trap the command v shortcut and disable it.
-- It will then be enabled/disabled as Calculator is focused/unfocused.
-- When enabled and command v is pressed it runs the Lua code within.
local applicationCalculatorCommandVHotkey = hs.hotkey.bind({"cmd"}, "V", function()
-- Get the number copied to the clipboard.
local theNumberToType = hs.pasteboard.readString()
-- See if there is a decimal in the number
-- and if so how many decimal places it has.
local l = string.len(theNumberToType)
local s, e = string.find(theNumberToType, "%.")
if s == nil then
theNumberOfDecimalPlaces = -1
elseif l - s > 15 then
theNumberOfDecimalPlaces = 15
else
theNumberOfDecimalPlaces = l - s
end
-- Set the number of decimal places to show.
if theNumberOfDecimalPlaces > -1 then
local calculator = hs.appfinder.appFromName("Calculator")
local vdpn = {"View", "Decimal Places", theNumberOfDecimalPlaces}
calculator:selectMenuItem(vdpn)
end
-- Type the number into Calculator.
hs.eventtap.keyStrokes(theNumberToType)
end)
applicationCalculatorCommandVHotkey:disable()
-- One of two methods of watching Calculator.
--
-- The other is below this one and commented out.
-- Initialize a Calculator window filter.
local CalculatorWindowFilter = hs.window.filter.new("Calculator")
-- Subscribe to when the Calculator window is focused/unfocused.
CalculatorWindowFilter:subscribe(hs.window.filter.windowFocused, function()
-- Enable hotkeys when Calculator is focused.
applicationCalculatorCommandVHotkey:enable()
applicationCalculatorEnterHotkey:enable()
end)
CalculatorWindowFilter:subscribe(hs.window.filter.windowUnfocused, function()
-- Disable hotkeys when Calculator is unfocused.
applicationCalculatorCommandVHotkey:disable()
applicationCalculatorEnterHotkey:disable()
end)
-- Alternate method to wait for Calculator and enable/disable the hotkey.
--
-- Uncomment below method and comment the above method to test between them.
-- The opening '--[[' and closing '--]]' and removed from below added to above.
--[[
function applicationCalculatorWatcher(appName, eventType, appObject)
if (eventType == hs.application.watcher.activated) then
if (appName == "Calculator") then
-- Enable hotkeys when Calculator is activated.
applicationCalculatorCommandVHotkey:enable()
applicationCalculatorEnterHotkey:enable()
end
end
if (eventType == hs.application.watcher.deactivated) then
if (appName == "Calculator") then
-- Disable hotkeys when Calculator is deactivated.
applicationCalculatorCommandVHotkey:disable()
applicationCalculatorEnterHotkey:disable()
end
end
end
appCalculatorWatcher = hs.application.watcher.new(applicationCalculatorWatcher)
appCalculatorWatcher:start()
-- appCalculatorwWatcher:stop()
--]]

Related

(NO mystery:) How Automator transfers "invisible" information to Script-Editor

( I have been pushed to an obvious answer to my "Mystery" from a friendly member here.
I feel a little ashamed not to have found this solution myself, but will leave this posting online if there aren't too many irritated folks around. Maybe someone else can learn from this … apologies to every "know-it-alls"!)
I have recorded these actions with Automator:
– Cmd-tab to bring TextEdit to front (must have some lines typed)
– Pressed left arrow 7 times using shift down
– Stopped the recording
Next I selected and copied (Cmd-c) all action icons in Automator's "Record my actions" window.
I switched to Script-Editor and pasted (Cmd-v) them into a new window.
Then, I repeated above recording with 3 times UP arrow and copied icons into another new window.
I took only the two "set uiScript to …" lines and appended them in the first script.
THEY READ IDENTICAL:
set uiScript to "keystroke \"\t\" using command down"
my doWithTimeout(uiScript)
set uiScript to "keystroke \"\" using shift down" -- 7 times left-arrow
my doWithTimeout(uiScript)
set uiScript to "keystroke \"\" using shift down" -- 3 times up-arrow
my doWithTimeout(uiScript)
on doWithTimeout(uiScript)
set endDate to (current date)
repeat
try
run script "tell application \"System Events\"\n" & uiScript & "\nend tell"
exit repeat
end try
end repeat
end doWithTimeout
(To make resulting code more readable I omitted error code and "delays".)
Now, if I disable one of the "keystroke" lines (=> --my doWith…) the script somehow knows that it either has to do Shift-leftArrow 7 times OR Shift-upArrow 3 times.
I tried this after computer restart, even copied the code from this web page and pasted it into a new Script Editor window – it still knew what to do!
HOW CAN THAT BE ???
My only idea is: there must be some internal Applescript database that recognises content even if copied/pasted.
Does anybody know ?
Only if I re-write the code identically will there happen NOTHING – until I copy the first line of either recording ("set uiScript to …"). So the information must be linked to this first line somehow.
(BTW: first two lines that bring TextEdit –or, e.g. a Finder window– to the front work only from opened Script Editor; you have to bring TextEdit to the front yourself, if you start the saved-as-program script from Script-Editor's menu icon subfolder. Nevertheless the script won't work without them…)
It "knows" because the keystrokes are in the string - keystrokes using control type keys (such as arrow keys) just don’t have a text representation, so they wind up being invisible. Some text editors such as BBEdit can show these invisible characters, but they don’t show up in the Script Editor.
Apple has obviously made Automator's Watch Me Do action able to capture some of these control keys in a string, but for the rest of us it is more difficult, since the control keys will actually perform their function when pressed. If you need to use these kinds of keys, the key code command can be used, since it refers to the actual keyboard key, for example:
tell application "System Events"
repeat 3 times
key code 126 using shift down -- up arrow
end repeat
end tell
As the answer is quite simple but may still be interesting to some, I'll explain it shortly:
red_menace (in his comment above) pointed out that strings may contain invisible elements (like arrow keys), therefore I next checked the obvious:
If you "cursor-walk" along the "set uiScript …" strings the cursor will actually "pause" for 7 or 3 "steps" respectively on its way.
I hadn't thought/heard of any "invisible" string-chars (apart from obvious ones in Word etc.).

Activate hotstring when text is pasted from clipboard

I have an Autohotkey Hotstring which displays a notification any time a job code is typed with capital letters.
:*B0C:ASSOC::
:*B0C:COORD::
:*B0C:PRACPHYS::
MsgBox Reminder - Set indirect pay to 100
return
While this works fine when manually typing out a job code, I also want these notifications to display when a job code is copy-pasted from the clipboard.
; non-functional pseudo-code
^v:: ; paste
if (pasted text == ASSOC or COORD or PRACPHYS)
MsgBox Reminder - Set indirect pay to 100
return
How can I make my script run whenever a matching string is pasted from the clipboard?
This checks the contents of the clipboard when pasting without interfering with the paste operation
~^v::
if ( clipboard == "ASSOC" || clipboard == "COORD" || clipboard == "PRACPHYS" )
MsgBox Reminder - Set indirect pay to 100
return
Notes
~ key's native function will not be blocked
clipboard contents of the clipboard in text-only format
== case sensitive string comparison
Ref
Autohotkey documentation for Hotkeys

Xcode AppleScript : change label which content of variable

Here is my script :
property MyLabel : missing value
on buttonClicked_(sender)
set the plistfile_path to "~/Desktop/MY_DATA.plist"
tell application "System Events"
set p_list to property list file (plistfile_path)
-- read the plist data
set theMyDataFromPlist to value of property list item "DATA1" of p_list
end tell
end buttonClicked_
This gonna take the data I want from a plist and set in a variable (theMyDataFromPlist).
How can I print this variable on the label "MyLabel" and make the script auto refresh when the data change ?
also, when I click on the text (or another button), can I copy the value to the clipboard. (would set the clipboard to theMyDataFromPlist work?)
I also wonder is that possible to do the same with Swift?
How can I print this variable on the label "MyLabel"
Where would you like to print the variable? You can make AppleScript display a dialog:
set variable to 42
display dialog "The value of variable is " & variable
AppleScript is not designed as a terminal language, it is for UI scripting, so it's not like most scripting languages that just offer a print as where would the user see the printed value.
and make the script auto refresh when the data change ?
Not quite sure what you expect here. That your system magically runs your script whenever the content of a file changes? That's not going to happen. You can create a launchd job and have launchd monitor that file and then execute your script when the file changes; this is described here:
https://discussions.apple.com/message/13182902#13182902
But some process will have to monitor the file and if your script should do so, it has to be running all the time, non-stop. Then you could make some code run once every X seconds, checking the file last modification date and whenever that changes, re-read the plist. This polling is super ugly but the best thing that AS can do out of the box.
BTW where is the rest? You say
also, when I click on the text (or another button),
can I copy the value to the clipboard.
Which text? Which button? Sound like you have a whole application there but all you showed us are 11 lines script code. You didn't even mention that you have a whole application with a UI. Your question starts with "Here is my script", so you make it sound like this 11 lines is all that you have.
(would set the clipboard to theMyDataFromPlist work?)
Why don't you simply try it out? Pasting that line into ScriptEditor would have taken equally long than asking this question. I just tried it and it turns out that you can only set strings.
This code won't work:
-- bad code
set variable to 42
set the clipboard to variable
But this code does work:
-- good code
set variable to 42
set the clipboard to "" & variable
I also wonder is that possible to do the same with Swift?
Personally I would not even consider writing an application in AppleScript; I'd rather stop writing code before I do that. Of course this can be done in Swift or in Obj-C. Everything you can do in AS can be done in these other two languages and no, the opposite doesn't hold true.
Using Obj-C or Swift, you can also use GCD and with GCD monitoring a file for changes is easy. Just see
https://stackoverflow.com/a/11447826/15809

Mac OS X Specify Keyboard Shortcut

How can i set the keyboard in Mac OS X Yosemite so i can map the function keys to write specified symbols?
I want to be able to write \( every time press F1
use Automator!
Open Automator (search for it in spotlight) and click the new document button
select service as the type of document
on the top left, there is a search bar in Automator. Simply search for run
one of the resulting options is Run AppleScript
Drag this onto the main part of the window, it will add a skeleton script
under where it says (*Your script goes here *), type this:
tell application "System Events"
keystroke "\\("
end tell
the two slashes are needed to produce one slash!
Now save this, the default location is fine!
Next, go into settings. open the keyboard icon
under the shortcuts tab, choose in the left pane, Services
Scroll to the bottom and your script should appear! select it and Double click where it says add shortcut. Now input your short cut. make sure there is no other shortcut assigned to that key
Now I must admit, I didn't get f1 to work in some apps because they had override shortcuts for F1. For example, the settings search bar printed ( when I hit F1 but in notes it didn't. If you have a keyboeard, you should probably try an F key greater than 12
Hope this works!

Set cliclick co-ordinates relevant to UI element in AppleScript

Firstly I have only been using AppleScript for the last couple of days, so am really new to it and have no real other scripting knowledge, so forgive me if this comes across as something trivial or I ask lots of follow up questions.
I have an element that I would like to right click on using cliclick, but the location of the element moves depending upon other windows and sidebars being open
I would like to use
position of button 1
to return the correct co-ordinates so I would like to be able to use maths to add to the X,Y co-ordinates in cliclick so it would be something like this
position of button 1
do shell script "../cliclick c:x+25,y+5"
is this possible or is it something that I will have to using another language? I am thinking the final project will be compiled into an application using Xcode and will be hiring someone for this, am just trying to make their life as easy as possible beforehand.
Ok after a bit of fumbling around the internet I found something else and then fiddled with it a bit and finally solved the above using the following
tell UI element 1 of toolbar 1 of toolbar 3 of the front window
set p to position
set x to item 1 of p
set y to item 2 of p
end tell
do shell script "/Users/dave/_app-dev/cliclick c:" & x & "," & y & ""
Just incase anyone else looks for it here is the answer
A more compact equivalent code:
set {x, y} to position of button 1 of toolbar 1 of toolbar 3 of window 1
do shell script "/Users/dave/_app-dev/cliclick c:" & x & "," & y & ""

Resources