In OSX can I use a system call to pass a command to a running terminal in a new tab? - macos

Specifically,
In OSX 10.6 from a system call, I want to open a file for editing with VIM in a preexisting terminal (i.e. Terminal.app) by opening a new tab.
Of course I can open a new instance of terminal
/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal -e vim MyFile
And, of course I can figure out the PID of the running instance of Terminal but I don't know how to pass a command into that running program. Or, if Terminal supports receiving commands and if it will open a new tab.
If someone knows how to do this with a similar system (e.g. linux and xterm) it could help me figure it out with OSX and Terminal - or, is there some other technique to prevent opening so many terminals instances?
EDIT: CHEAP SOLUTION
I created an AppleAcript script
on run app_arg
tell application "System Events"
tell application process "Terminal"
key code {55, 36}
set frontmost to true
key code {55, 17}
keystroke item 1 of app_arg
keystroke return
end tell
end tell
end run
and run it via the system call like so
/usr/bin/osascript NEWSCRIPT.scpt "args"
It's dirty but it gets the job done - thanks!

The way to accomplish the is with applescript. You can send applescript to things in OS X with the osascript command. I wasn't able to find anything quickly that directly shows how to open a new tab with a command running in it, but I was able to find a couple of references to automating Terminal.app in various other ways with applescript, and I think they may point you in the right direction.
Various random Terminal.app applescript hacks mostly centered around changing colors.
An applescript hack that opens a new terminal window without creating a new Terminal process.
A nice StackOverflow question about how to query an application to discover what applescript it supports (stolen from a comment on your question by #dmckee)
And this nice StackOverflow question concerning Terminal.app's applescript specifically (again stolen from a comment by #dmckee)
An even better exploration of the Leopard Terminal.app's applescript from Ruby no less
And from that last link, it looks like the only way to do it is to use applescript to send the Command-T keystroke to the terminal. That's ugly, but it'll work. And then you can send the command you want to execute. :-)

There are three ways to do this:
Use popen
Use system
Use exec family

Related

Bring Terminal in the front with Ruby

I am using Ruby on a mac to open a dozen URLs one at a time with Nokogiri etc.
For each URL I need to let my ruby program know
whether to keep the URL window for further inspection or close it.
But I cannot see the terminal window and its prompt, it is hidden behind
the last URL window.
I have to click on the terminal window in order to bring it to the front, in order to enter my decision on the keyboard.
puts "close webpage?"
if gets =~ /^y/i then 1 ; else; 0; end;
I would like the terminal window to come to the front before it prompts
me for an answer.
I think the question is two fold
Is there a terminal command that tells a terminal window to become
the active one (the one in the front) that would work with mac iTerm.
The Apple script "bringiTermtofront" works in the applescript editor.
tell application "iTerm" to activate
Is there a way to execute a terminal command from ruby.
the ruby code
system "osascript bringiTermtofront.scpt"
brings the iTerm to the front.
For Question 1, one approach would be to write an Applescript to handle the switch, and then use the Terminal command osascript to run it from your Ruby code. You could also check if rb-appscript is still usable (it's no longer supported, but might work).
For Question 2, you have a few choices. Using backticks around the command will let you capture the output of a brief command, if you want to store the result of the command in a variable. (E.g. use grep or something similar).
The system method in Kernel is probably your best choice, though, as it will execute shell commands as if at the terminal.
Per the edit showing what script you're using, you need to execute the script as Applescript, not as a terminal script. You don't even need a separate file as it's just one line. This would be :
command = %q[osascript -e "tell application \"iTerm\" to activate"]
system(command)
You could also put the Applescript in a file and execute it using just
system("osascript bringiTermtofront")
See "Running shell commands from Ruby" for a little more help on how to interact with these methods.

Custom Keyboard Shortcut Service Not Working 10.11 (el capitan)

I've seen a few questions dealing with this issue but nothing recently. I'm not sure if El Capitan (10.11) is breaking something, and I'm an AppleScript (and Automator) newbie.
I just want to have the basic functionality where a keyboard shortcut opens a new terminal window in the space I'm in. After doing the following things, absolutely nothing happens when I trigger the keyboard shortcut
1. Create an Automator Service
Open Automator and choose Service for my document type.
Set Service recieves selected to no input
Drag a Run AppleScriptaction into my workflow.
on run {input, parameters}
tell application "Terminal"
do script ""
activate
end tell
return input
end run
(At this point, running the workflow from automator by pressing Play opens a new terminal window correctly).
Save the service as Launch New Terminal Window
2. Assign a Keyboard Shortcut
Open System Preferences -> Keyboard -> Shortcuts -> Services
Assign Shift Command T to Launch New Terminal Window
When I try my new command, nothing happens.
Note, I tried to delete the service and retrace my steps. When I recreated a new service with the same name, the keyboard shortcut was remembered by the system. Does anyone know which .plist/where these keyboard shortcuts are saved?
If anyone can help me out, that would be great. A 30 second project has turned into 30 minutes of hair pulling.
I also encountered a similar problem. The issue is that, most probably some other application is using the key combination that you tried. You can check by using a bizarre key combination and check whether it works and then modify it. Try using something like Shift + alt + command + G. Or something like this ( use at least 4 keys ). It worked for me. Hope it helps you.
For future reference, since it seems a very common question, I think the only reason why a shortcut won't work is that it's being used by other application, as 2XSamurai said.
You can have quick feedback if the shortcut is going to work or not by navigating to Finder and then Services.
If your brand new shortcut is showing next to the service you created, that means is going to work, otherwise, it won't.
No need to perform other actions, you just need to pick a good shortcut. Somewhere on the web, you may also read that you must include the command key to make your shortcut work. That's also not necessary (see the screenshot with just ctrl + T combination working just fine).
PS I can't post pictures on answers yet so StackOverflow generated links to the images instead, but this caused the answer to broke (I was getting a message error stating there was code in my answer (??), so no screenshots, sorry, I hope the answer is clear enough even without them :)
I did exactly what you've described (Automator Service, no entry, only one Applescript Action, and assign the Automator Service to short cut key (in my case command shift Y).
All is working OK on my ElCapitain with bellow script in Automator action : (I mean the short cut opens a new Terminal window as expected)
tell application "Terminal" to activate
tell application "System Events"
tell process "Terminal"
keystroke "n" using {command down}
end tell
end tell
But I still ask myself the basic question : what do you really want to achieve ? usually the bash instruction could be done in do shell script command...no need for Terminal window... may be you have an other constraint.
I had the same problem before, solved it somehow, forgot about it and ran into it again when setting up a new MacBook today.
This solution works for me on several Macs:
Instead of using System Preferences -> Keyboard -> Shortcuts -> Services (screenshot 1 - for some reason I'm not allowed to insert pictures directly into posts) you can use
System Preferences -> Keyboard -> Shortcuts -> App Shortcuts (screenshot 2).
There you have to spell out the name of your service.
There are some issues with the App Shortcuts menu as well. For example a shortcut for the "Tags..." menu in Finder simply won't work but for services it works for me.

Launching a Shell Script using a Global Shortcut on OSX Snow Leopard

I have a shell script, which I launch several times during work everyday. I do this by launching terminal, and launching the script from within. However, I would like to be able to launch it (from within a terminal) with a global OSX keyboard shortcut (Cmd+Shift+R say).
There are quite a few applications which work in this manner already (for eg. EverNote, RemindMeLater, even the default Cmd-Space which brings up the search utility) and hence, I am guessing this should be at least theoretically possible.
Could someone please tell me if and how this can be done?
Instead of using a global shortcut key, maybe try creating an applescript that runs the shell script? So just open at AppleScript Editor, and enter something like this.
do shell script "//Your script";
Then save it as an application in the format drop down.
After that, you can run the script just by opening up the application with something like spotlight.

Putting the display to sleep (⇧⌃⏏/shift+control+eject) in AppleScript

Is it possible to write an AppleScript to put the display to sleep (which locks the display if the computer is set to lock on sleep)? You can do this from the keyboard by entering ⌃⇧⏏ (shift+control+eject); this leaves all the programs, etc., running, and just turns off the screen.
I've been wanting to do this for a while now. I just found out how in the man pages. You can use the following command to achieve instant display sleep. (I have tested it on OS X 10.10.)
pmset displaysleepnow
(no root privileges / sudo required!)
I'm not sure if this works for 10.9.4 yet but by all means give it a shot!
you can use: tell application "Finder" to sleep
Or use bettertouchtool. It is a small app which you can use native functions in addition to applescript.
do shell script "pmset displaysleepnow"
Edit 2015-08-23: This is possible (from the shell) as of OS X 10.9! Go see user3064009's answer for the update :-)
There's no good way to do this; there's a SuperUser question about this same thing. Depending on why you want this, however, there's one workaround I know: activate the screen saver. (This is what they suggest over on SuperUser). You can do this in AppleScript with launch application id "com.apple.ScreenSaver.Engine", or from the command line by running the application /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine. I don't know whether or not this is technically documented anywhere, but it's worked for several iterations of the OS now. It may not do exactly what you want—your screen saver may, for instance, be colorful, which isn't helpful if you want a black screen—but it will be the same in that it does lock the screen if you have that set up.
For a nice catalog of other workarounds, check out this MacScripter thread: it documents that
There's no scriptable way to do this.
You can't tell AppleScript to key code EJECT, as there's no such key code.
You can use pmset to tell the display to go to sleep in one minute, but then you have to wait.
There's an undocumented IOKit way to do this; there's a mailing list post explaining how.
I haven't found an easy way to do it programmatically, but I did find a very small, free app that puts the display immediately to sleep, called "SleepDisplay." (There is another app of the same name that did NOT work for me.)
So you can just
tell application "SleepDisplay" to activate
Link: http://www.macupdate.com/app/mac/26234/sleep-display

Google SketchUp close file

The Ruby API to Google SketchUp has a function, open_file, but I can't find a close_file function. Since I have to batch process many files, I want to close each file before moving on to the next, otherwise the program will crash from memory exhaustion.
What is the best way to close SketchUp files programmatically?
I am using Mac OS X and am willing to use AppleScript functions to signal the window to close.
EDIT
I am considering a few approaches that have proven fruitless so far.
Using the appscript Ruby gem, as described in this question. The problem here is that I cannot get SketchUp to recognize my installed gems.
In a similar vein, I am trying to use osascript (a bash program that executes AppleScripts from the shell) to close the window. That is, I call out to the shell from SketchUp's Ruby console window using one of the following:
%x[osascript -e 'tell application "SketchUp" to close window 1']
%x[osascript -e 'tell application "SketchUp" to close window 1' &]
%x[osascript -e 'tell application "SketchUp" to close every window']
%x[osascript -e 'tell application "SketchUp" to close every window' &]
Whenever I try this second approach, SketchUp just freezes. However, when I execute any of these commands from an IRB or directly from the Bash prompt outside of SketchUp, I get the desired behavior: the model window closes (incidentally, the Ruby console window remains open, which is fine).
Have a master script that launches a slave script to process each model. The slave will run within the Google SketchUp program while the master waits. When the slave is finished, it signals the master, and the master closes the SketchUp file. To do this interprocess communication, I tried using drb. However, when I try to require drb within SketchUp, I get the following message:
Error: LoadError: (eval):5:in 'require': no such file to load -- drb
EDIT 2
Having a separate process continuously running that closes Google Sketchup windows using AppleScript when signaled is clumsy for a number of reasons. First, it's ugly to have to have a separate process devoted to closing Sketchup windows. Second, the only effective way of communicating with the external script is through the creation of files, which is wasteful and the disk access may be slowing things down.
However, the most severe issue is that Sketchup is slow at responding to AppleScript commands. I have a pretty computation intensive script running in Sketchup, and it seems to starve the AppleScript response, which means that the osascript times out before the windows close. Sketchup only gets around to responding to AppleScript when there is a dialogue box prompt in Sketchup that pauses the execution of my computationally intensive script.
EDIT 3
I have modified my close_file function to pause execution of the script by displaying a dialog box. This essentially yields the current thread and allows the thread that responds to AppleScript commands to execute:
def close_file()
f = '/temp/mutex.txt' # for finer control, use different mutex for each window you want closed
File.new(f, 'w').close
result = UI.messagebox "Click OK when window has closed."
end
Then the separate ruby script that closes windows via AppleScript will additionally have to click "OK" in the dialog box. AppleScript to do that is:
tell application "System Events"
tell process "SketchUp"
set frontmost to true
keystroke return
end tell
end tell
This modification is an improvement. It corrects the "most severe issue" mentioned in EDIT 2, but the other issues remain.
There is an important limitation with using an external AppleScript to force SketchUp to do something. SketchUp will not accept any user input while a menu script is running.
I found this out trying to setup an automated rendering solution. I added a menu item which opens a WebDialog to get a list of models to download from a server. It then steps through the list and uses cURL to download each model. Once downloaded it loads the model, renders it out, uploads the images using cURL again, and goes to the next model.
What I wanted was to activate the AppleScript after each model is rendered (using the "mutex" file solution shown above) and have it close the model window. Unfortunately, since the menu script is still running, SketchUp will not respond to anything the AppleScript tells it to do. Only once all of the models have been processed and the menu script exits, will the AppleScript finally run.
This would not be so bad if all of the calls to the AppleScript were queued up, but they aren't. It seems that only the last two get honored (that number may be just an accident dependent on the timing of when my calls to the AppleScript were made relative to when the menu script finished).
Because of this limitation, I was not able to use the mutex wait() function in my menu Ruby code. Since the AppleScript was not able to execute, it never created its "I'm done" mutex file, and therefore the wait() function in Ruby never got the signal that it could continue. The result was a deadlock between AppleScript and SketchUp, such that SketchUp just freezes up (well, actually it is just stuck in a really tight loop in the wait() function).
So, when approaching this problem, think of AppleScript as a cleanup tool you can call when all of your processing is done.
One solution is to have a separate process continuously running that will close Google Sketchup windows using AppleScript when signaled. The approach described here uses files to do the interprocess communication (drb did not seem to work).
First, you have to make sure Sketchup supports AppleScripting. To do this, execute the following at the command prompt (with appropriate substitutions for different Sketchup versions, etc.):
$ defaults write /Applications/Google\ SketchUp\ 8/SketchUp.app/Contents/Info NSAppleScriptEnabled -bool YES
Now, create a separate file that will close Sketchup windows. Here is my closer.rb file:
#!/usr/bin/ruby
## closer.rb ##
def wait(f)
while !File::exists?(f)
end
File.delete(f)
end
def signal(f)
File.new(f, 'w').close
end
while true
wait('~/temp/mutex.txt')
msg = %x[osascript -e 'tell application "SketchUp" to close every window']
signal('~/temp/conf.txt')
end
Run this script from the shell. It waits until the file ~/temp/mutex.txt is created. Once the file is created, it runs osascript (essentially AppleScript) to close all the windows in Sketchup, and then signals that the windows were closed by creating a ~/temp/conf.txt file.
Here is the client code (which can be placed in your Sketchup plugins) that signals the closer script:
def wait(f)
while !File::exists?(f)
end
File.delete(f)
end
def signal(f)
File.new(f, 'w').close
end
def close_file
signal('~/temp/mutex.txt')
wait('~/temp/conf.txt')
end
The close_file signals the closer script and then waits for a confirmation that the file was closed before returning. Now you can close files in Sketchup.
You can do a lot with SketchUp using applescript and/or Automator.
tell application "SketchUp"
activate
tell application "System Events"
delay 1.0 --close window, adjust delay to suit
--key code 13 using command down -- Press ⌘W or you can use
keystroke "w" using command down
end tell
end tell
I have a number of status bar items for open new, paste to console, closing, killing SU etc.
They're tiny files that trigger the SU shortcut keys, and can be used externally, from 'Ruby Console' or as part of a plugin.
I'm not sure what kind of 'batch convert' your trying to achieve, but
I used Automator to convert most of my old v5, V6, v7 files to v8 today...
100's of them,
and your probably aware, on opening you get 'alert' warning that saving will convert the file to the latest version (which is what I wanted).
It's tricky to click this "OK" programatically.
Automator on it's own is quite restricted, but you can add an applescript to the workflow and I've found that if you use it's 'record function' to demonstrate what you need to do.
You can then copy/paste that code into 'Script Editor', get rid of the 'dowithTimeout' bits, copy it back into the workflow with delays either side and let it run.
I had to play around with delays, to accommodate some larger files, but achieved >95% success. [Success being able to select all, right click, Create Icon and Preview.]
Unfortunately I then binned the workflow, but could recreate it, if you want to have a look.
success, in Ruby Console
system("osascript -e 'tell application \"suoff\"' -e 'activate' -e 'end tell'")
and this script inside an Automator.app in applications folder....
on run
-- Make sure SU is foremost, don't click on anything else either
tell application "System Events"
tell process "SketchUp"
set frontmost to true
-- gives a message if you try to select when SU's not running
delay 0.2
tell application "SketchUp" to quit saving no
-- no dialog box etc...
delay 0.1
end tell
end tell
end run
the problem is SU has an anti self destruct ruby, that mines any linked files and aborts all efforts to shut it down... from inside itself.
so you need to bury it...
this combination works on 10.5.8 with SU8.1.
if you have a look at SketchUcation [Developer] Forum, I left a call for mac/applescript testers... I've rewritten the app since then but if you PM me I'll send you an open copy of all the bits I've got working..
john
I had to convert hundreds of .skp files with a batch processing script. I faced similar issue, since every time I opened a new file it remained opened. For me it was enough to close the active_model and the file goes with it.
This was true for SketchUp 2019 Pro Mac OS X version.
model = Sketchup.active_model
model.save(filename, Sketchup::Model::VERSION_2015)
model.close
Hope it will help

Resources