Is it possible to copy the full directory of the current active window on Mac?
e.g. say I have example.txt open in Sublime Text, can I execute an Apple Script that will grab the full path of that file? (without going to Finder).
The result would be that /Users/Bob/Dropbox/example.txt would then be in my clipboard.
You could assign a shortcut to a script like this:
try
tell application (path to frontmost application as text)
set the clipboard to (path of document 1) as text
end tell
on error
try
tell application "System Events" to tell (process 1 where frontmost is true)
value of attribute "AXDocument" of window 1
end tell
do shell script "ruby -rcgi -e 'print CGI.unescape ARGV[0][16..-1]' " & quoted form of result
set the clipboard to result
end try
end try
The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn.
Related
I'm new to Xcode as well as I am to AppleScript
All I need is to run an AppleScript in an Xcode application.
Bassically, the application is downloading pictures from a url list in Excel and renames the files acording the list in Excel
Here is the applescript code :
tell application "Microsoft Excel"
set filenames to value of every cell of range "K3:K200" of sheet "Image_Moves" of document 1
set URLs to value of every cell of range "L3:L200" of sheet "Image_Moves" of document 1
end tell
repeat with i from 1 to count URLs
if (item i of filenames is not missing value) and (item i of URLs is not missing value) then
set thisFname to quoted form of (POSIX path of ({path to desktop, "Image_Moves:"} as text) & item i of filenames)
set thisUrl to quoted form of item i of URLs
set status to (do shell script "curl -s -o " & thisFname & space & thisUrl)
end if
end repeat
try
tell application "Finder"
delete (every item of folder ("Image_Moves") whose name begins with "0")
end tell
on error
display dialog ("Error. Couldn't Move the File") buttons {"OK"}
end try
In Xcode, you can write a full application in AppleScript with the "Cocoa-AppleScript" template. Also, you can compile and execute an AppleScript with the NSAppleScript class. If your question is just about making an AppleScript executable, use Save As... in Script Editor and save your AppleScript as an application.
HTH
I have been trying to cobble together a script to take a list of files from a text document and have applescript go through the list line by line and then do something with the file. In this case it is changing the label on the file, but we would use it in other instances to move files, etc.
It works with a test file on my desktop the files get marked with the purple Label, but when trying to run it in the folder I actually need to it fails with this error message:
error "Finder got an error: Can’t set 1 to 5." number -10006 from 1
The text files are the same except for the length of their content.
Could this be a an issues with filenames, and if so how do I make the script more tolerant.
Here is the script:
set textFileContents to POSIX path of (choose file)
set dataList to paragraphs of (read textFileContents as «class utf8»)
tell application "System Events"
repeat with thisFileName in dataList
tell application "Finder" to set (label index of files whose name is thisFileName) to 5
end repeat
end tell
Any help would be appreciated, thanks.
1080074 3.tif
1080074 2.tif
1080069_A1.tif
Here is the final code from the solution to this problem and some further work I did.
Thanks to #Mark Setchell & #jackjr300 for all of their patient help.
set justpath to POSIX path of (choose folder with prompt "Select the Folder with Files You Want to Use")
set textFileContents to (choose file with prompt "Select the list of files")
set dataList to paragraphs of (read textFileContents as «class utf8»)
tell application "Finder"
repeat with FileName in dataList
try -- need a try block to ignore error, in case that the file has been moved or deleted
set label index of (justpath & FileName as POSIX file as alias) to 5
end try
end repeat
end tell
You seem to have a spurious tell application "System Events" in there. It works like this:
set FileName to POSIX path of (choose file)
set FileRecords to paragraphs of (read FileName)
repeat with ThisFileName in FileRecords
say ThisFileName
tell application "Finder" to set (label index of files whose name is thisFileName) to 5
end repeat
Note that my test file isn't UTF8.
Update
By the way, if all you want do is set the label colour on some files, it may be easier to do that from the Terminal and not worry with Applescript. Say you start the Terminal, and go to your Desktop like this
cd Desktop
you can then change the labels of all files on your Desktop (and in any subdirectories) whose names contain "Freddy" followed by "Frog" (i.e "fileForFreddyFrog.txt", "file from Freddy the Frog.php")
find . -name "*Freddy*Frog*" -exec xattr -wx com.apple.FinderInfo "0000000000000000000700000000000000000000000000000000000000000000" {} \;
You need to specify the folder because the finder has no current folder, except the Desktop if you don't specify a folder.
set textFileContents to choose file
set dataList to paragraphs of (read textFileContents as «class utf8»)
set theFolder to "/Users/jack/Desktop/xxx/yyy" as POSIX file as alias -- change it to the path of your folder
tell application "Finder"
repeat with thisFileName in dataList
try -- need a try block to ignore error, in case that the file has been moved or deleted
set label index of file thisFileName of theFolder to 5
end try
end repeat
end tell
Change the path in the third line of this script
--
If the text file contains the full path of the file, you can use this script.
set textFileContents to choose file
set dataList to paragraphs of (read textFileContents as «class utf8»)
tell application "Finder"
repeat with thisPath in dataList
try -- need a try block to ignore error, in case that the file has been moved or deleted
set label index of (thisPath as POSIX file as alias) to 5
end try
end repeat
end tell
I am trying to tie together a filemaker script that will export PDFs to a temporary space and use and apple script to print them.
I was able to cull together info from this and some other boards to create an applescript that will print the PDFs using Acrobat from a folder.
I have already created a script that finds the Related attachments and exports them to the desktop.
What I'm having trouble with is merging the two.
I need to export the PDF to a folder or temporary place and trigger the apple script to initiate the printing...
This great Suggestion was provided by Chuck of chivalrysoftware.com/…...
Calculate the location to export by appending the filename to Get( TemporaryPath ).
Export the container field contents to FileMaker to that path.
Save the path to a global field in FileMaker
Use an embedded AppleScript to access the global field path
Use AppleScript to open the file in Preview and print it
This is my apple script:
set myFolder to (path to desktop folder as text) & "Print:"
set myfiles to list folder myFolder without invisibles
repeat with myfile in myfiles
set mycurrentfile to ((myFolder as string) & (myfile as string)) as string
batchprint(mycurrentfile)
end repeat
on batchprint(mycurrentfile)
tell application "Adobe Acrobat Pro"
activate -- bring up acrobat
open alias mycurrentfile -- acrobat opens that new file
tell application "System Events"
tell process "Acrobat"
click menu item "Print..." of menu 1 of menu bar item "File"¬
of menu bar 1
click button "Print" of window "Print"
tell application "System Events"
tell process "Acrobat"
click menu item "Close" of menu 1 of menu bar item "File"¬
of menu bar 1
end tell
end tell
end tell
end tell
end tell
tell application "Finder" -- to move the printed file out
set x to ((path to desktop folder as text) & "Printed PDFs:")
if alias x exists then
beep
else
make new folder at the desktop with properties {name:"Printed PDFs"}
end if
move alias mycurrentfile to folder "Printed PDFs"
end tell
end batchprint
My Filemaker script is:
Go to Related Record[
Show only related records; From table: 'Attachments";
Using layout: "Attachements Report' (Attachments); New window
]
Enter Find Mode
Constrain Found Set [Restore]
Sort Records [Restore; No dialog]
# After finding the related attachments and constraining them to the specific type
# we rename and export them to the desktop
Go to Record/Request/Page [First]
Loop
Set Variable [$Path; Value:
Get ( DesktopPath ) & Attachments::Record number & "-"
& Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1]
Export Field Contents [Attachments::file_c; $Path]
Go to Record/Request/Page [Next: Exit after last]
End Loop
Close Window [Current Window]
First of all, the FileMaker part. Create a global text field in one of your tables. It looks like the Attachments table would be the best place for it. I'll call it g_applescript_parameter for this.
Now we're going to use your $Path variable, which given the calc you've provided should be something like /Aslan/Users/chuck/Desktop/1234-ABC4321. I'd recommend appending a .pdf to the end of it since you'll be exporting PDF files. This may help later.
Also, I would recommend that you use Get( TemporaryPath ) instead of Get( DesktopPath ). Anything you place in the temporary folder will be automatically deleted when you quit FileMaker, which means you don't have to write anything to clean up the desktop folder later and you don't have to manually trash them either. Let FileMaker do that work for you. :)
Regardless, FileMaker uses a path of the form filemac:/volumeName/directoryName/fileName (see the notes in the Specify output file dialog box for the Export Field Contents script step). So you should also prepend filemac: to the beginning of your path variable.
All told, your $Path should be set to something like this:
"filemac:" & Get( DesktopPath ) & Attachments::Record number & "-" &
Attachment Type List 2::Prefix_z & Lien::Lien_ID_z1 & ".pdf"
So your export path for FileMaker should work better now. But AppleScript requires a different format for the path to the same file. Given the above, AppleScript's version should be something like /Users/chuck/Desktop/1234-ABC4321.pdf. In other words, everything after the drive name. Fortunately FileMaker can get the drive name with the Get( SystemDrive ) function. For me that function returns /Aslan/. So if we take the $Path variable as defined above and remove filemac: and the name of the drive as defined by Get( SystemDrive ) and add an extra slash at the beginning, that would convert our FileMaker path into an AppleScript path:
"/" & Substitute( $Path; "filemac:" & Get( SystemDrive ); "" )
Use Set Variable to create an $ASPath variable and set it to the above.
Now within your loop store the contents of the $ASPath variable within that global text field:
Loop
Set Variable[ $Path; …]
Set Variable[ $ASPath; …]
Set Field[Attachments::g_applescript_parameter; $ASPath)
Export Field Contents[Attachments::file_c; $Path]
Go to Record/Request/Page[Next; Exit after last]
End Loop
Now AppleScript can extract that information. I'm assuming that given an accurate file being passed to the batchprint function, batchprint will work, so keep that, but remove everything before it and use something like this:
set _pdf_path to contents of cell "g_applescript_parameter" of current layout
batchprint(_pdf_path)
on batchprint(mycurrentfile)
...
end batchprint
Add a Perform AppleScript step after the Export Field Contents step and place the above code in it.
Note that the first line of the above AppleScript will only work as written from within FileMaker. If you're testing this outside of FileMaker in, for example, Script Editor, then you'll need to make that first line read
tell applicaiton "FileMaker" to set _pdf_path ...
You don't need to do this within the Perform AppleScript script step because by default commands are sent to the enclosing FileMaker application.
(I'm a real novice) I was able to create an apple script by culling together bits from other posts. This script batchprints PDFS from a folder using the acrobat pro 11 engine and moves them to a separate folder when complete... While the script works well on one computer where the desktop path is fixed. It must be modified for every different computer we use. Is there a way to script the watch folder in a variable location?
property myFolder : "HD:Users:User:desktop:Print:"
set myfiles to list folder myFolder without invisibles
repeat with myfile in myfiles
set mycurrentfile to ((myFolder as string) & (myfile as string)) as string
batchprint(mycurrentfile)
end repeat
on batchprint(mycurrentfile)
tell application "Adobe Acrobat Pro"
activate -- bring up acrobat
open alias mycurrentfile -- acrobat opens that new file
tell application "System Events"
tell process "Acrobat"
click menu item "Print..." of menu 1 of menu bar item "File" of menu bar 1
click button "Print" of window "Print"
tell application "System Events"
tell process "Acrobat"
click menu item "Close" of menu 1 of menu bar item "File" of menu bar 1
end tell
end tell
end tell
end tell
end tell
tell application "Finder" -- to move the printed file out
set x to (("HD:Users:User:desktop:Printed PDFs") as text)
if alias x exists then
beep
else
make new folder at the desktop with properties {name:"Printed PDFs"}
end if
move alias mycurrentfile to folder "Printed PDFs"
end tell
end batchprint
In AppleScript, you can refer the Desktop folder of the current user with path to Desktop Folder
E.g.:
set myFolder to (path to Desktop Folder as text) & "Print:"
I'm working on a project for OSX where the user can pick a collection of documents (from any application) which I need to generate PDF's from. The standard Macintosh Print dialog has a PDF button which has a number of PDF-related commands including "Save as PDF...". However, I need to generate the PDF file without requiring user interactions. I ideally want this to work with any type of document.
Here's the options I've explored so far:
Automator actions. There's a PDF library for Automator but it provides actions for working with PDF files, not generating them. There's a Finder action for printing any file but only to a real printer.
AppleScript. Some applications have the ability to generate PDF files (for instance, if you send 'save doc in "test.pdf"' to Pages it will generate a PDF (but this only works for Pages - I need support for any type of document).
Custom Printer. I could create a virtual printer driver and then use the automator action but I don't like the idea of confusing the user with an extra printer in the print list.
My hope is that there's some way to interact with the active application as if the user was carrying out the following steps:
Do Cmd-P (opens the print dialog)
Click the "PDF" button
Select "Save as PDF..." (second item in menu)
Type in filename in save dialog
Click "Save"
If that's the best approach (is it?) then the real problem is: how do I send UI Events to an external application (keystrokes, mouse events, menu selections) ?
Update: Just to clarify one point: the documents I need to convert to PDF are documents that are created by other applications. For example, the user might pick a Word document or a Numbers spreadsheet or an OmniGraffle drawing or a Web Page. The common denominator is that each of these documents has an associated application and that application knows how to print it (and OSX knows how to render print output to a PDF file).
So, the samples at Cocoa Dev Central don't help because they're about generating a PDF from my application.
I think you could use applescript to open a document and then use applescript UI scripting to invoke print menu.
For example :
tell application "System Events"
tell window of process "Safari"
set foremost to true
keystroke "p" using {command down}
delay 3
click menu button "PDF" of sheet 2
click menu item "Save as PDF…" of menu 1 of menu button "PDF" of sheet 2
keystroke "my_test.file"
keystroke return
delay 10
end tell
end tell
Take a look at a program called CUPS-PDF
It is a virtual printer for OS X which does what the "Save As PDF" method does when print through your normal printer except every print job passed through it results in a pdf output.
Once you install it then you could create shell or AppleScripts using the lp command.
For example, once the virtual printer is setup you could print test.txt and have it automatically save as a pdf. To do this using an AppleScript you would use the following code:
do shell script "lp -d CUPS_PDF test.txt"
The CUPS-PDF app saves all output to /Users/Shared/CUPS-PDF. I am not sure if you can change that path but you could retrieve the file in your script and move it.
There are a few caveats though.
First, the lp command cannot print .doc files. I think there are some other third party apps which will allow you to do this though.
Second, the CUPS-PDF app shows in the Printer pane of System Preferences as having the hyphen in its name but CUPS shows the queue name as having an underscore. So, on the command line you need to refer to the CUPS queue name which is CUPS_PDF with an underscore.
Even if you don't find it very useful to build a script via the lp command
and still want to involve GUI scripting then having a virtual printer should save you some steps.
you could use cups like this
on open afile
set filename to name of (info for afile)
tell application "Finder"
set filepath to (container of (afile as alias)) as alias
end tell
set filepath to quoted form of POSIX path of filepath
set tid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "."
set filename to text item 1 of filename
set AppleScript's text item delimiters to tid
set afile to quoted form of POSIX path of afile
do shell script "cupsfilter " & afile & " > " & filepath & filename & ".pdf"
end open
I have created an alias in bash for this:
convert2pdf() {
/System/Library/Printers/Libraries/convert -f "$1" -o "$2" -j "application/pdf"
}
I typed up the code below with the assistance of Automator (recording an action, and then dragging the specific action out of the "Watch Me Do" window in order to get the Applescript). If you want to print a PDF from an application other than Safari, you might have to run through the same process and tweak this Applescript around the Print dialogue, since each program might have a different Print GUI.
# Convert the current Safari window to a PDF
# by Sebastain Gallese
# props to the following for helping me get frontmost window
# http://stackoverflow.com/questions/480866/get-the-title-of-the-current-active-window- document-in-mac-os-x
global window_name
# This script works with Safari, you might have
# to tweak it to work with other applications
set myApplication to "Safari"
# You can name the PDF whatever you want
# Just make sure to delete it or move it or rename it
# Before running the script again
set myPDFName to "mynewpdfile"
tell application myApplication
activate
if the (count of windows) is not 0 then
set window_name to name of front window
end if
end tell
set timeoutSeconds to 2.0
set uiScript to "keystroke \"p\" using command down"
my doWithTimeout(uiScript, timeoutSeconds)
set uiScript to "click menu button \"PDF\" of sheet 1 of window \"" & window_name & "\" of application process \"" & myApplication & "\""
my doWithTimeout(uiScript, timeoutSeconds)
set uiScript to "click menu item 2 of menu 1 of menu button \"PDF\" of sheet 1 of window \"" & window_name & "\" of application process \"" & myApplication & "\""
my doWithTimeout(uiScript, timeoutSeconds)
set uiScript to "keystroke \"" & myPDFName & "\""
my doWithTimeout(uiScript, timeoutSeconds)
set uiScript to "keystroke return"
my doWithTimeout(uiScript, timeoutSeconds)
on doWithTimeout(uiScript, timeoutSeconds)
set endDate to (current date) + timeoutSeconds
repeat
try
run script "tell application \"System Events\"
" & uiScript & "
end tell"
exit repeat
on error errorMessage
if ((current date) > endDate) then
error "Can not " & uiScript
end if
end try
end repeat
end doWithTimeout
"/System/Library/Printers/Libraries/./convert"
has been removed in later version of MacOS.
You can use sips now. AppleScript example:
do shell script: sips -s format pdf Filename.jpg --out Filename.pdf