Open file in Preview - applescript

I struggle with a basic file operation in Apple Script. A pdf is (successfully) written in the script like this:
theDocument's writeToURL:targetFile
Now I want to open the file in Preview like this:
tell application "Preview"
activate
open targetFile
end tell
I also tried this:
tell application "Preview"
activate
open POSIX path of targetFile
end tell
to no avail. I somehow seem to lack an understanding how to get the path to a given file.
What am I missing?

Your code doesn’t show what targetFile is, but assuming from the first line it’s an NSURL you need to convert it to an AppleScript file type before passing it to Preview’s open command:
set targetFile to targetFile's |path|() as string as POSIX file
AppleScript’s Apple event bridge doesn’t accept ObjC classes, only native AS types.

Related

Create apple notes with AppleScript

I get the text from the file and create a note, but the text is added to the notes without hyphenation, in one line! How to make all hyphenations be copied?
My code:
set x to read POSIX file "/files/mytext.txt"
tell application "Notes"
tell account "iCloud"
make new note at folder "Blogs" with properties {name:"My Blogs", body:x}
end tell
end tell
Thanks!
I discovered that the "Notes" application is actually using HTML format (it said so in the AppleScript Dictionary for that application), and HTML does not correctly format newlines; so that means that all of the newlines need to be replaced with <br> using the shell command awk. Reading the file using awk instead of AppleScript itself also seems to solve the hyphenation problem.
Here is the fixed command:
set x to (do shell script "awk '{printf \"%s\\<br>\", $0}' '/files/mytext.txt'")
tell application "Notes"
tell account "iCloud"
make new note at folder "Blogs" with properties {name:"My Blogs", body:x}
end tell
end tell

OS X 10.9 Applescript changes: using the `move` command in the "System Events" context to move a file

I went to run an old script and it broke after the 10.9 update. I used to move files with system events with the following code.
set Somefilepath to "Design_005_HD:Users:Design_005:Desktop:Start:TextFile.txt"
set somefolderpath to "Design_005_HD:Users:Design_005:Desktop:End:"
tell application "System Events"
move file (Somefilepath) to folder (somefolderpath)
end tell
Now it gives me the following error.
error "System Events got an error: Can’t make file
\"Design_005_HD:Users:Design_005:Desktop:Start:TextFile.txt\" into
type integer." number -1700 from file
"Design_005_HD:Users:Design_005:Desktop:Start:TextFile.txt" to integer
I know I can swap it out and use finder but I rather not use it. What changed that is no longer works?
Update 4/2/14
I have tried this in every way of giving the file/folder location to system events and it doesn't work. I am glad it is just not me who cannot get it to work. I will update this post if I find an answer or a working update is made.
Update 4/3/14
It seems this is just a bug that system events can't move files. I have reported it here http://bugreport.apple.com/ and everyone else should too.
Please do not take my code to heart, it is just where things ended up when I couldn't get it to work. I have working code for 10.8.5 and it is what is shown above minus the folder tag in the system events tell block. No idea why it works with out the folder tag but it does. Tested on multiple comps. If it isn't broken don't fuss over it. Noted it and moved on.
Update 10/20/14
For anyone interested. I have received an e-mail stating my ticket has been closed/resolved. So mavericks will for ever be broken but there might be light for Yosemite when it comes out.
In general, Applescript works with colon delimited paths (:) not slash delimited paths (/). I say in general because some applications will work with slashes but all programs will work with colons. For an example of what the colon paths look like try this code and look at the result...
set colonPath to (path to desktop as text) & "untitled folder 2:"
So first I would convert your slashes to the colon style.
Also to applescript these are just strings not paths. To make applescript understand they are paths we can do a few things. First you can add the words file or folder in front of them as appropriate. I notice in your code you are using "file" in front of the file string but you aren't using "folder" in front of the folder string. So try that. Second you can just use "alias" in front of the strings whether they're files or folders. There are other ways as well but I'll stop here. Either of those ways should work.
UPDATE: with all of the above being said, it seems System Events in 10.9 still has trouble with the move command. As such here's 2 alternatives for you. I used slash style paths since that's what you're using.
set somefilepath to POSIX file "/Users/Design_005/Desktop/Start/TextFile.txt"
set somefolderpath to POSIX file "/Users/Design_005/Desktop/End"
tell application "Finder"
move somefilepath to somefolderpath
end tell
or
set somefilepath to "/Users/Design_005/Desktop/Start/TextFile.txt"
set somefolderpath to "/Users/Design_005/Desktop/End"
do shell script "mv " & quoted form of somefilepath & space & quoted form of somefolderpath
Good luck.
You can’t do that. System Events can delete and open, but not move. Here’s a simple example in case it helps someone else find a better answer in a future OS. System Events appears to treat move differently than delete and open.
tell application "System Events"
set myFile to file "Macintosh HD:Users:velma:Desktop:Test.png"
set myFolder to folder "Macintosh HD:Users:velma:Desktop:Test"
--delete works! with both type “file/folder” and type “disk item”
--delete myFile
--delete myFolder
--open works!
open myFile
open myFolder
--move fails!
move myFile to myFolder
end tell
The error it’s returning, in this case, is “Can’t get file”, number -1728.
There appears to be bug in the move command in the "System Events" context in OX 10.9 (and possibly 10.8).
The workaround is the to use the "Finder" context instead:
Using HFS-style paths (separator is :)
set somefilepath to "Design_005_HD:Users:Design_005:Desktop:Start:TextFile.txt"
set somefolderpath to "Design_005_HD:Users:Design_005:Desktop:End:"
tell application "Finder"
move file somefilepath to folder somefolderpath
end tell
Using POSIX-style paths (separator is /) - as in the original question
set somefilepath to "/Users/Design_005/Desktop/Start/TextFile.txt"
set somefolderpath to "/Users/Design_005/Desktop/End"
# Note that we use `as POSIX file` even in the case of the *folder*
# - this works, however.
tell application "Finder"
move somefilepath as POSIX file to somefolderpath as POSIX file
end tell
Note:
as POSIX file returns a file object in both cases, but Finder still handles the move properly - it is fine to use POSIX file with both files and folders.
Note that using the prefix form of POSIX file- e.g., POSIX file "/Library", only works with a path string literal; if you try to build the path string as an expression, it breaks (in the "Finder" context, but NOT in the AppleScript context(!)): POSIX file ("/" & "Library") - by contrast, "/" & "Library" as POSIX file works (in both contexts) - go figure. To be safe, always use the postfix form: ... as POSIX file
A downside of using as POSIX file - at least as of OS X 10.9 - is that the error messages are cryptic if a file/folder doesn't exist: you'll see Finder got an error: Handler can’t handle objects of this class. and Finder got an error: AppleEvent handler failed. - both with number -10000.
(Using folder directly with a POSIX path, as in an earlier version of the question - e.g., folder "/Library" - ONLY works in a "System Events" context, and is therefore NOT an option in the "Finder" context.)
As for what changed in AppleScript OS X 10.9:
The behavior you see appears to be a bug (also see #Jerry Stratton's answer); nothing in the AppleScript release notes for 10.9 indicates a change in that area.
I now think that the problem affects OS X 10.8 as well.
I encourage you to submit a bug report to Apple at http://bugreport.apple.com, as I already have.
Sadly, handling files, folders, and aliases in AppleScript has always been a mess, with confusion stemming from classes of the same name from different dictionaries (AppleScript itself, System Events, Finder) with subtly different behavior.
A general recommendation: for file-system manipulation, use the tell application "Finder" context.
The "System Events" dictionary, in its Disk-Folder-File Suite, duplicates some of Finder's file-system manipulation functionality, but only some - a curious omission is a file copy command, for instance.

AppleScript : Trying to write in a TextEdit file

I'm trying to write in a TextEdit file already created.
The file is in rwxrwxrwx mode so no permission problem.
But when I execute my code, here is the error :
error "Network file permission error." number -5000 from file "/Users/me/Desktop/A directory/file.txt" to «class fsrf»
My code here :
-- Writing in the TextEdit file
set file_URLs_content to "HEEEELLOOOOOO"
tell application "TextEdit"
set theFile to "/Users/me/Desktop/A directory/file.txt"
set file_ref to (open for access file theFile with write permission)
set eof file_ref to 0
write file_URLs_content to file_ref
close access file_ref
end tell
And my file.txt is still empty, how can I avoid this error ?
The way you can avoid errors when writing text with TextEdit is to remember that it is a text editor. It already knows how to create and save text documents without generating errors. You don’t have to use (error-prone) open for access. You don’t have to use (error-prone) shell scripting. All you have to do is ask TextEdit to make you a text document with whatever contents you like and and save it wherever you like. TextEdit knows how to do that without generating file access errors (like open for access) or accidentally overwriting folders (like shell scripting.)
tell application "TextEdit"
activate
set theDesktopPath to the path to the desktop folder as text
set file_URLs_content to "HEEEELLOOOOOO"
make new document with properties {text:file_URLs_content}
save document 1 in file (theDesktopPath & "file.txt")
close document 1
end tell
The advantage of this method is it is faster and easier to write, it is less error-prone, the text file that you get as output has the same properties as text files that you create manually with TextEdit, and your script can now be easily expanded to include other apps. For example, the text content could come from another app or the clipboard, and the text file could be opened in another app or emailed after it is saved.
The most fundamental feature of AppleScript is sending messages to Mac apps in this way. If you want to convert a PNG to a JPEG, you don’t write a PNG decoder and JPEG encoder in AppleScript and open the PNG file for access and read it byte by byte and then encode a JPEG byte by byte. You simply tell Photoshop to open the PNG image and export it as a JPEG to a particular file location. The “open for access” command is a last resort for reading and writing files that you simply don’t have an app to read or write. The “do shell script” command is for incorporating command-line apps when you simply don’t have a Mac app to do the job, for example, you can do regex stuff with Perl. If all you are doing is working with text files, you not only have TextEdit, but you can also get the free TextWrangler from Mac App Store and it has a giant AppleScript dictionary for reading, writing, and editing text files.
You don't need TextEdit for that. Try this:
set the logFile to ((path to desktop) as text) & "log.txt"
set the logText to "This is a text that should be written into the file"
try
open for access file the logFile with write permission
write (logText & return) to file the logFile starting at eof
close access file the logFile
on error
try
close access file the logFile
end try
end try
Try:
set file_URLs_content to "HEEEELLOOOOOO"
set filePath to POSIX path of (path to desktop as text) & "file.txt"
do shell script "echo " & quoted form of file_URLs_content & " > " & quoted form of filePath

How can I batch save a bunch of AppleScript scpt files to applications?

I have a bunch of AppleScript scripts in a directory that I want to be able to build as apps without having to go into each one and manually save as application.
I've already created a "build script" that used to work, but for some reason it doesn't work anymore. So I'm able to iterate through the scripts, open them in the AppleScript Editor, create the output directory, but the save command doesn't do anything anymore. Here's the relevant part:
on makeApp(sourcedir, outputdir, curFile)
tell application "Finder" to set outName to name of curFile
tell application "AppleScript Editor"
set outNameRoot to my remove_extension(outName)
set outAppName to outNameRoot & ".app"
set outFileName to ((outputdir as string) & outAppName as string)
set scriptFile to open curFile
save scriptFile as "application" in outFileName
--display dialog outFileName
--close scriptFile
end tell
end makeApp
The line that fails is:
save scriptFile as "application" in outFileName
This was working around September. The only thing I can think of is that I've upgraded to Lion. So my question is:
Does anyone know why that would fail (silently)?
Is there another way to accomplish what I'm trying to do?
Thanks
The open command is supposed to return a document, but it returns missing value on my machine. You should be able to just save document 1, since the newly opened script will be in front. Another option would be to use osacompile - you don't get a bunch of script documents popping up that way.

"POSIX file" works in Applescript Editor, not in XCode

Try this:
Make a new XCode4 Applescript project. In the delegate, paste this code:
on doIt_(sender)
set goodHFSLoc to (path to desktop folder)
set test1 to (POSIX path of goodHFSLoc)
log "test1:"&test1
set theJSPath to "/Users/dave/Desktop/MakeTSLabels.js"
set jsHFSFile to (POSIX file theJSPath)
set test2 to (POSIX path of jsHFSFile)
end doIt_
Hook this method up to a button in the UI window.
Run the program
Click the button, and you should get this error:
Can’t get POSIX path of class "NSObject".
Put the same code (minus the "on" and "end" lines) into AppleScript editor, and it runs fine.
Apparently, "POSIX file" in ApplescriptObjC doesn't make a file object as the language specification requires. Instead it makes an NSObject.
I need to have an applescript file specifier to provide to Adobe Illustrator's do javascript command, and I need to use NSBundle's functions to get the javascript file, which is packaged in my application bundle.
Am I doing something wrong?
You will see the same behavior in a Finder or System Events tell statement. The solution is the same for ASObjC - you need to use it as a coercion:
set jsHFSFile to (theJSPath as POSIX file)

Resources