JXA keystroke does not work with special characters - applescript

I'm trying to setup a simple Apple JXA script to write the well-known shrug emoji to screen (it simulates the key press I guess). Every thing I try produces this "¯\_(a)_/¯". I'm assuming since I'm using keystroke to simulate key press and I don't have a japanese keyboard that I'm always going to get that. Maybe I should be copying the string to clipboard instead?
Here's my code so far:
// Shrug Script
// ¯\_(ツ)_/¯
//
// contains special character:
// ツ
// KATAKANA LETTER TU
// Unicode: U+30C4, UTF-8: E3 83 84
// thought maybe I needed to decode it ¯\_(ツ)_/¯
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
// this is the newer "Script" aka Javascript way
var sysEvents = Application('System Events');
// this didn't work:
// sysEvents.keystroke("¯\\_(ツ)_/¯");
// this doesn't work either
sysEvents.keystroke("¯\\_("+ decode_utf8("\xE3\x83\x84") +")_/¯");

ok so adding it to my clipboard and immediately pasting it was a lot easier. It's not a direct answer to my question but the final result is what I wanted.
Apple Script version:
# Shrug Script
# ¯\_(ツ)_/¯
#
# contains special character:
# ツ
# KATAKANA LETTER TU
# Unicode: U+30C4, UTF-8: E3 83 84
set the clipboard to "¯\\_(ツ)_/¯"
tell application "System Events" to keystroke "v" using command down
JXA version:
var app = Application.currentApplication()
app.includeStandardAdditions = true
var seApp = Application('System Events')
// set current app's clipboard
app.setTheClipboardTo("¯\\_(ツ)_/¯")
// paste!
seApp.keystroke('v', { using: 'command down' });

I would strongly recommend Services for this kind of task as they can directly manipulate text in almost any application; no need for hacky kludges like GUI Scripting. Very easy to make a new Service in Automator that will output a piece of text, plus you can bind it to a keyboard shortcut in System Preferences when done. Here's an example you can easily adapt:
Creating an osx service to insert the current date and time

Related

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

2 clipboards ahk script

I'm trying to have 2 clipboards (or more), with an ahk script.
Desired behaviour is working with the standard ^v plus !v so it will be 2 clipboards. ^v being the usual one, !v will be the previous content that ^v had.
If I copy 'text1' on clipboard, I will have this as ^v. If I copy 'text2' I will have 'text2' on clipboard with ^v, plus the old 'text1' available with !v, and so on.
This is so far:
lastclip = %clipboard%
!v::
global lastclip
sendclip(lastclip)
return
ClipWaitChange()
ClipWaitChange()
{
While changed=0 {
global lastclip
lastclip = %clipboard%
Sleep 10
}
OnClipboardChange:
changed = 1
return
}
But it returns a blank clipboard or maybe ^v stops working.
Any hints how to do that?
sendclip is just a custom func to send the clipboard contents by keyboard
I tried put lastclip = %clipboard% inside onclipboardchange but it copies the current changed clipboard, so has to be done before that.
I assume your question is of an academic nature. If not, I recommend one of the many Clipboard Managers already out there.
Here's a solution with comments:
lastClip := ""
bufferedClip := Clipboard
OnClipboardChange("clipChangeHandler")
; Note that the ALT key can change focus, better use WIN+V
#v::
; Since we temporarily switch Clipboard's contents,
; we want to ignore the event it will fire
OnClipboardChange("clipChangeHandler", 0)
; I recommend pasting rather than sending
tmpClip := Clipboard
Clipboard := lastClip
Send, ^v
Clipboard := tmpClip
tmpClip := ""
OnClipboardChange("clipChangeHandler")
return
clipChangeHandler(evtInfo) {
global lastClip, bufferedClip
; Check if Clipboard contains actual text
if(evtInfo = 1) {
lastClip := bufferedClip
bufferedClip := Clipboard
}
}
See also OnClipboardChange in AHK docs.
A few remarks:
The event function checks for the event type being (partially) real text, ignoring pure non-text like images and also empty clipboards
clipBuffer always stores the current clipboard and lastClip contains the previous clipboard. You need the buffer variable, since the event doesn't offer something like a previous clipboard
ALT + v can be problematic when working with windows that have a classic menu bar. Hitting ALT (even before releasing it) will often switch focus away from the current control.
I recommend pasting rather than sending. E.g. when there's large text in the clipboard with thousands of words (maybe even put there by another program or simply by mistake), sending each character one by one can take a long time or may even come with other side effects. If you want to Send regardless, at least use SendRaw so that certain characters won't be mistreated as control sequences (e.g. sending #e will open Windows Explorer).
Always consider security aspects of your application. If you (our your password safe e.g.) empty your clipboard to delete sensitive data, your script will still keep an (unencrypted) copy of it, for every other process to see.

How do I write a backslash (with Alt+Shift+7) in Xcode without commenting line?

How do I write a "\" in Xcode without commenting out the whole line ?
var name = "Kevin"
var returnValue = "Hi \(name)"
When I type the backslash with alt+shift+7 it comments out the whole line...
//var returnValue = "Hello "
I assume you're using a keyboard layout in which you have to type Alt-Shift-7 to type a backslash. (That's not true for the U.S. layout, for example.)
The problem is presumably that Alt-Shift-7 (or some portion of that) is assigned as the keyboard shortcut for the Editor > Structure > Comment Selection menu item. In Xcode's Preferences, you can change the keyboard shortcut assigned to that function (or simply remove the keyboard shortcut) and that should allow the keystroke to behave normally.

Barcode scanner reads input into text file, then selects all text and deletes it

I am trying to set up a (USB) Motorola Symbol DS6708 barcode scanner to scan QR code encoded with some contact information onto a text file.
When scanning in a barcode, the expected text is displayed on in the text file. When it is finished reading it in all the text is selected and deleted.
If it hit ctr+z, the text is undeleted and displayed in the file.
The desired result is in this format:
Name
Title
Company
Phone
ect
I'm not really sure where to start with debugging this. I am assuming that there is some characters being read in at the end that doing the equivalent of ctrl+a and delete.
EDIT
I tried scanning using the 123Scan2 from Motorolo, and this was the result:
<STX> <STX> <STX>318315647 <ETX> <LF>NAME<ETX> <ETX>LNAME<ETX> <LF>TITLE <ETX>
<LF>COMPANY <ETX>
<LF>ADDRESS <ETX> <LF>ADDRESS <ETX> <LF>CITY<ETX>, <ETX>ST<ETX> <ETX>12345<ETX> <LF>USA <ETX>
<LF>PHONE <ETX> <LF>PHONE <ETX>
<LF>EMAIL <ETX> <LF> <LF> <LF> <LF> <LF> <SUB> <CR>
EDIT
I attempted to set console application with C# and read in the input with Console.Read() or Console.ReadLine(), but the input actually caused the application to stop running, and then the input text was written into the text of the Program.cs file on Visual Studio.
The simple console app:
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.WriteLine("start");
int result;
while ((result = Console.Read()) != 0)
{
Console.WriteLine("{0} = {1}", result, (char)result);
}
}
}
I'm not really sure where to start with debugging this. I am assuming
that there is some characters being read in at the end that doing the
equivalent of ctrl+a and delete.
I attempted to set console application with C# and read in the input
with Console.Read() or Console.ReadLine(), but the input actually
caused the application to stop running, and then the input text was
written into the text of the class on Visual Studio.
I would bet that the data contain an EOF char (Ctrl+Z). All text devices (like console I/O) use this as an end signal, and it is still supported in modern OSes, although little known these days. And of course it is documented.
When it is finished reading it in all the text is selected and
deleted. If it hit ctr+z, the text is undeleted and displayed in the
file.
You probably want to say, that the text is shown in the editor, and selected/deleted from the editor. A file can't hardly display anything on it's own, it just contains something. By the way, the fact that EOF is Ctrl+Z and your editor's undo is also Ctrl+Z is pure coincidence.
As you don't show any code, it's hard to say anything about it. I'd probably do a Read() loop and store everything useful I get in a suitable place, for example in a file :-) This data are then to be processed in a second step.
PS: This related question may also be helpful.
I haven't played with barcode scanners for a while but this sounds to me that either the barcode you are scanning contains the control codes to do Ctrl-A and Del or that the scanner is programmed in that way.
To the host PC a barcode scanner basically appears like a keyboard. If you can type it, the barcode scanner can deliver it, including all Ctrl / Shift / Alt shortcuts.
If you have the scanner from new you should have a sheet of barcodes that allow you to program it up and affect its behavior. Have a look for a full reset barcode and see if that improves things.
You might want to try their sdk downloaded here. tell me if it still deletes the file in the textbox of the form.
If it isn't deleted, it might be better to add an export to a text file button.

ascii codes for windows keyboard keys and the codes for function keys(F1 - F12) and other keys like shift,capslock,backspace,ctrl etc

To write a keyboard related application I wanted the list of the ASCII codes of the keys that I have on my keyboard.
It is a windows keyboard :
From where can I get the codes ? It will be great if I get the codes in hexadecimal notation.
You can get all the keyCode values (even for Function keys) by running (injecting) following JavaScript code into your browser's console. Paste the following code and press enter. Then click anywhere in the page to remove the cursor from the console.
Then press any key for which you want a keyCode in Hex
Here is the code :
document.addEventListener("keydown", function (e) {
code = (e.keyCode);
console.log("In decimal "+e.keyCode);
var hex = code.toString(16);
console.log("In hex "+hex);
}, false);
There is no ascii code for the Function (F1-F12), Control, Windows or Alt keys.
If what you need is ASCII for the characters that is already defined in most languages.
Have a look at this, it also includes the hexadecimal codes
ASCII Tables with Hex
What you are looking for is called Scancode
here and here. On linux there's a command showkey that can print a SCAN code of they pressed key. On Windows, though, you may need to write a program.

Resources