I am new to applescript. I want to develop an application in applescript.
Below is my code. And while running it, it's showing finder that can't make alias. Kindly help me.
property script_name : "image Tracker"
property script_description : "image property data finder"
--set the_folder to (choose folder with prompt "Select the folder for get the image property:") as Unicode text
--set the_folder to quoted form of POSIX path of (choose folder with prompt "Select the folder for get the image property:")
set the_folder to (choose folder)
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtentions
tell application "Finder" to set fPaths to file the_folder
repeat with thisFilePath in fPaths
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_file
-- extract the properties record
set the props_rec to the properties of this_image
-- purge the open image data
close this_image
-- extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimemsions: " & x & ", " & y
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access ("Macintosh HD:Users:varghese.pt:Desktop:") & "image_data.txt" with write permission
write image_info to myfile
close access myfile
If anyone found the answer, please send me the details.
Thanks in advance.
Nidhin Joseph
Let me say up front: Unfortunately, in general, AppleScript is a finicky beast, and sometimes trial and error are your only friends.
There are several problems with your code - some obvious, one not:
validExtentions is misspelled in the copy {"jpg ... statement - you later refer to with the (correctly spelled) name validExtensions
In the tell application "Finder" command, you must replace file with folder.
In command set this_image to open this_file, you must replace this_file with (thisFilePath as text). NOTE: Parenthesizing and as text is crucial, as the file will otherwise be opened by Finder (and therefore open in Preview.app) - don't ask me WHY this is so.
I also suggest replacing the hard-coded path in the write-to-file command with (path to desktop as text) & "image_data.txt"
If we put it all together, we get:
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtensions
set the_folder to (choose folder)
tell application "Finder" to repeat with thisFilePath in folder the_folder
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
# start the Image Events application
launch
# open the image file
# set this_image to open thisFilePath
set this_image to open (thisFilePath as text)
# extract the properties record
set the props_rec to the properties of this_image
# purge the open image data
close this_image
# extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimensions: " & x & ", " & y
# my dlog(image_info)
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access (path to desktop as text) & "image_data.txt" with write permission
write image_info to myfile
close access myfile
Finally, you can improve the performance of your code by switching from enumerating files in the Finder context to enumerating in the System Events context:
If you substitute the following two lines for their current counterparts in the code above, your script will run much more quickly. Why, you ask? Again, I do not know.
tell application "System Events" to repeat with thisFilePath in alias (the_folder as text)
set this_image to open (get path of thisFilePath)
Related
this code almost works. :) Basically I am trying to zip a file and then attach that email to a new mail message.
The process starts in automator and then the script runs. Everything works except the actual attaching of the file.
My knowledge of AppleScript is pretty limited but trying to wrap my head around this. I combined to different code snippets to get this far.
on run {input, parameters}
set display_text to "Please enter your password:"
repeat
considering case
set init_pass to text returned of (display dialog display_text default answer "" with hidden answer)
set final_pass to text returned of (display dialog "Please verify your password below." buttons {"OK"} default button 1 default answer "" with hidden answer)
if (final_pass = init_pass) then
exit repeat
else
set display_text to "Mismatching passwords, please try again"
end if
end considering
end repeat
tell application "Finder"
set theItems to selection
set theItem to (item 1 of input) as alias
set itemPath to quoted form of POSIX path of theItem
set fileName to name of theItem
set theFolder to POSIX path of (container of theItem as alias)
set zipFile to quoted form of (fileName & ".zip")
do shell script "cd '" & theFolder & "'; zip -x .DS_Store -r0 -P '" & final_pass & "' " & zipFile & " ./'" & fileName & "'"
end tell
tell application "Finder"
#I believe this is where the problem is, I am trying to use the variables from above in order to attach the file in mail.
set folderPath to theFolder
set theFile to zipFile
set fileName to zipFile
end tell
set theSubject to fileName
set theBody to "Hello sir. Here is my " & fileName
set theAddress to "Some Email"
set theAttachment to theFile
set theSender to "Some Sender"
tell application "Mail"
set theNewMessage to make new outgoing message with properties {subject:theSubject, content:theBody & return & return, visible:true}
tell theNewMessage
set visibile to true
set sender to theSender
make new to recipient at end of to recipients with properties {address:theAddress}
try
make new attachment with properties {file name:theAttachment} at after the last word of the last paragraph
set message_attachment to 0
on error errmess -- oops
log errmess -- log the error
set message_attachment to 1
end try
log "message_attachment = " & message_attachment
#send
end tell
end tell
return input
end run
I've fixed up most of the things that are off with your code. The following works in an automator Run AppleScript action if you pass in a list containing an alias to a file:
on run {input, parameters}
set display_text to "Please enter your password:"
repeat
considering case
set init_pass to text returned of (display dialog display_text default answer "" with hidden answer)
set final_pass to text returned of (display dialog "Please verify your password below." buttons {"OK"} default button 1 default answer "" with hidden answer)
if (final_pass = init_pass) then
exit repeat
else
set display_text to "Mismatching passwords, please try again"
end if
end considering
end repeat
tell application "System Events"
set selected_file to item 1 of input
set selected_file_name to name of selected_file
set containing_folder_path to POSIX path of (container of selected_file) & "/"
set zip_file_path to containing_folder_path & selected_file_name & ".zip"
do shell script "cd " & quoted form of containing_folder_path & "; zip -x .DS_Store -r0 -P " & quoted form of final_pass & " " & quoted form of zip_file_path & " " & quoted form of selected_file_name
set zip_file_alias to file zip_file_path as alias
end tell
set theSubject to selected_file_name
set theBody to "Hello sir. Here is my " & selected_file_name
set theAddress to "Some Email"
set theSender to "Some Sender"
tell application "Mail"
set theNewMessage to make new outgoing message with properties {subject:theSubject, content:theBody & return & return, visible:true}
tell theNewMessage
set visibile to true
set sender to theSender
make new to recipient at end of to recipients with properties {address:theAddress}
try
make new attachment with properties {file name:zip_file_alias} at end of attachments
on error errmess -- oops
log errmess -- log the error
end try
log "message attachment count = " & (count of attachments)
#send
end tell
end tell
return input
end run
Highlights:
I switched from using the Finder to using System Events. Avoid using the Finder unless you absolutely need to (it's a very busy app)
I set the name property of the attachment to an alias to the compressed file the script creates
I cleaned up this and that to make things clearer.
Here is what I ultimately came up with, which worked but the file handling for the attachment still needed work.
on run {input, parameters}
tell application "Finder"
set theItem to (item 1 of input) as alias
set theItemCopy to theItem
set itemPath to quoted form of POSIX path of theItem
set fileName to name of theItem
set theFolder to POSIX path of (container of theItem as alias)
set zipFile to quoted form of (fileName & ".zip")
set setPass to "Password" #test password
do shell script "cd '" & theFolder & "'; zip -x .DS_Store -r0 -P '" & setPass & "' " & zipFile & " ./'" & fileName & "'"
end tell
tell application "Mail"
set fileLocation to (fileName & ".zip")
set theSubject to "Subject" -- the subject
set theContent to "Attached are the documents from the last session." -- the content
set theAddress to "email#email.com" -- the receiver
set theAttachmentFile to "Macintosh HD:Users:dave:desktop:" & fileLocation -- the attachment path
set msg to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}
delay 1
tell msg to make new to recipient at end of every to recipient with properties {address:theAddress}
tell msg to make new attachment with properties {file name:theAttachmentFile as alias}
end tell
return input
end run
Still a Noob / novice here
So I am trying to rename a file within a folder
set newfoldername to DT & "-" & JobName & " - " & Wedding --Adds Date, Couples name and event type to make directory name
MORE CODE HERE
set destFolder to loc & newfoldername & ":Final Delivery:DVD:"
tell application "Finder"
duplicate file sourcedvdtemp to folder destFolder
set the name of file "DVD_template.dspproj" to newfoldername
end tell
But I just get an error
"error "Finder got an error: Can’t set file \"DVD_template.dspproj\" to \"newfoldername.dspproj\"." number -10006 from file "DVD_template.dspproj""
I have tried various ways, with and without the extension "newfoldername" is set above and creates a folder with the users input as a name
Am I just being stupid or have I missed something completely.
EDIT
tell application "Finder" to set frontmost to true
set DT to text returned of (display dialog "Please enter the wedding date" default answer "YYYY/MM/DD") --Asks for date of wedding
set JobName to text returned of (display dialog "Please enter the couples name" default answer "Bride & Groom + Surname") --Asks for couples name
set Wedding to text returned of (display dialog "Please enter the type of day" default answer "Wedding") --Asks for type of day, Wedding, Party, etc
--Creates directory with info from above
set loc to (choose folder "Please choose where you would like to save the files") as text --Loc = Location of where directory will be placed
set newfoldername to DT & "-" & JobName & " - " & Wedding --Adds Date, Couples name and event type to make directory name
set folderStructure to "/{Audio/{Music,RAW\\ Audio\\ Cards},Documents,Exports,FCPX\\ Library,Film\\ Poster,Final\\ Delivery/{DVD,USB,WEB},Images/{Graphics,Stills},RAW\\ Cards/{C100-1,C100-2,7D,100D},XML}"
do shell script "mkdir -p " & quoted form of POSIX path of (loc & newfoldername) & folderStructure
set sourcedvdtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:DVD_template.dspproj" --Gets file DVD_template
set sourceusbtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:USB_template.zip" --Gets file USB_template
set sourcewebtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:WEB_template.zip" --Gets file WEB_template
set sourcefcpxtemp to (path to movies folder as text) & "## - WeddingTemplate - ##:FCPX_template.fcpbundle" --Gets file FCPX_template
set sourcefilmpostemp to (path to movies folder as text) & "## - WeddingTemplate - ##:FILM_POSTER_Template.psd" --Gets file FILM_POSTER_template
set destFolder to loc & newfoldername & ":Final Delivery:DVD:"
tell application "Finder"
duplicate file sourcedvdtemp to folder destFolder
set the name of file "DVD_template.dspproj" to newfoldername
end tell
set destFolder to loc & newfoldername & ":FCPX Library:"
tell application "Finder"
duplicate file sourcefcpxtemp to folder destFolder
set the name of file "FCPX_template.fcpbundle" to newfoldername
end tell
set destFolder to loc & newfoldername & ":Film Poster:"
tell application "Finder"
duplicate file sourcefilmpostemp to folder destFolder
set the name of file "FILM_POSTER_Template.psd" to newfoldername
end tell
You are trying to rename a file "DVD_template.dspproj" on desktop which obviously does not exist. The desktop folder is the root folder of the Finder.
The duplicate command of the Finder returns the duplicated file so it's simply
tell application "Finder"
set fileExtension to name extension of file sourcedvdtemp
set duplicatedFile to duplicate file sourcedvdtemp to folder destFolder
set name of duplicatedFile to newfoldername & "." & fileExtension
end tell
If you want to rename the file to newfoldername you have to copy and add the file extension.
PS: Instead of calculating the template folder 5 times I recommend to write
set weddingTemplateFolder to (path to movies folder as text) & "## - WeddingTemplate - ##:"
set sourcedvdtemp to weddingTemplateFolder & "DVD_template.dspproj" --Gets file DVD_template
set sourceusbtemp to weddingTemplateFolder & "USB_template.zip" --Gets file USB_template
... etc.
I feel it should be a simple task, but I could not find a solution yet. Basically, I want to clean up the items of the desktop using Applescript, the same way I would by right-clicking the desktop and clicking "Clean up".
Unfortunately, something like the following does not work:
tell application "Finder" to clean up desktop
Any ideas?
This is what I use:
set theFiles to {}
set folderExtensions to {}
set _extensions to {}
tell application "Finder" to set theFiles to every file in folder (desktop as string)
tell application "Finder"
if not (folder ((desktop as string) & "Mydesktop") exists) then
make folder at (desktop as string) with properties {name:"Mydesktop"}
end if
end tell
set i to 0
repeat (number of items in theFiles) times
set i to i + 1
set _extensions to _extensions & (name extension of (info for file ((item i of theFiles) as string)))
end repeat
set i to 0
repeat (number of items in _extensions) times
set i to i + 1
if folderExtensions does not contain (item i of _extensions) then
set folderExtensions to folderExtensions & (item i of _extensions)
end if
end repeat
set i to 0
repeat (number of items in folderExtensions) times
set i to i + 1
tell application "Finder"
if not (folder ((desktop as string) & "Mydesktop:" & (item i of folderExtensions)) exists) then
make folder at ((desktop as string) & "Mydesktop:") with properties {name:(item i of folderExtensions)}
end if
end tell
end repeat
set i to 0 ------we are moving the files now
set _key to ""
set x to 1
set letters to {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
repeat
set x to x + 1
if x > 100 then return
set _key to ""
repeat 20 times
set _key to _key & (item (random number from 1 to 26) of letters)
end repeat
tell application "Finder"
if not (folder ((desktop as string) & "Mydesktop:" & _key) exists) then
make folder at folder ((desktop as string) & "Mydesktop:") with properties {name:_key}
exit repeat
end if
end tell
end repeat
repeat (number of items in theFiles) times
set i to i + 1
tell application "Finder"
if not (file ((desktop as string) & "Mydesktop:" & (item i of _extensions) & ":" & (name of (info for file ((item i of theFiles) as string)))) exists)
then
move file ((item i of theFiles) as string) to folder ((desktop as string) & "Mydesktop:" & (item i of _extensions) & ":")
else
set x to 1
repeat
set x to x + 1
if x > 100 then exit repeat
if not (file ((desktop as string) & "Mydesktop:" & (item i of _extensions) & ":" & (name of (info for file ((item i of theFiles) as string))) & " " & x) exists) then
set someItem to (item i of theFiles)
tell application "System Events" to tell disk item (someItem as text) to set {theName, theExtension} to {name, name extension}
if theExtension is not "" then set theName to text 1 thru -((count theExtension) + 2) of theName -- the name part
set old to ((desktop as string) & "Mydesktop:" & _key & ":" & (name of (info for file ((item i of theFiles) as string))))
move file ((item i of theFiles) as string) to folder ((desktop as string) & "Mydesktop:" & _key & ":")
set the name of file old to theName & " " & x & "." & theExtension
move file ((desktop as string) & "Mydesktop:" & _key & ":" & theName & " " & x & "." & theExtension) to folder ((desktop as string) & "Mydesktop:" & (item i of _extensions) & ":")
exit repeat
end if
end repeat
end if
end tell
end repeat
set item1 to (the quoted form of POSIX path of ((((path to desktop) as string) & "Mydesktop:" & _key) as alias))
set deleteit to "rm -rf " & item1 & ""
try
do shell script deleteit
on error
do shell script deleteit with administrator privileges
end try
It creates a folder (if it does not already exist) and sorts all my files.I have exported it as an application and have set it to open every time I log in!That way I start with a nice clean desktop.
This seems to work for me:
tell application "System Events"
tell application "Finder"
activate desktop
end tell
-- this delay is to ensure that the second block of code doesnt run too fast, or it will not work, if this doesn't work, try increasing this delay
delay 0.1
tell process "Finder"
-- this clicks the the clean up button from the menu bar at the top, the "activate desktop" at the beginning was to make sure that the desktop's menu bar was the front menu bar
click menu item "Clean Up" of menu "View" of menu bar item "View" of front menu bar
end tell
end tell
Edit: new improved script
tell application "System Events"
-- hides everything, which makes the menu bar become the desktop's menu bar
set visible of every process to false
set visible of process "Finder" to false
end tell
delay 0.1
tell application "System Events"
tell process "Finder"
click menu item "Clean Up" of menu "View" of menu bar item "View" of front menu bar
end tell
end tell
The AppleScript I'm making extracts the frames from a gif file and puts the individual images in a folder inside the application's contents. It then changes the desktop background rapidly to the images inside the folder, hence giving you a gif for a wallpaper. However, I can't figure out how to extract the gif files to the folder in the application. This is what I have so far:
on delay duration
set endTime to (current date) + duration
repeat while (current date) is less than endTime
tell AppleScript to delay duration
end repeat
end delay
set gifFiles to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFiles
set dest to quoted form of POSIX path of (path to me) & "Contents:Resources:Gif"
set pScript to quoted form of "from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os
tName=os.path.basename(sys.argv[1])
dir=sys.argv[2]
app=NSApplication.sharedApplication()
img=NSImage.alloc().initWithContentsOfFile_(sys.argv[1])
if img:
gifRep=img.representations()[0]
frames=gifRep.valueForProperty_('NSImageFrameCount')
if frames:
for i in range(frames.intValue()):
gifRep.setProperty_withValue_(NSImageCurrentFrame, i)
gifRep.representationUsingType_properties_(NSGIFFileType, None).writeToFile_atomically_(dir + tName + ' ' + str(i + 1).zfill(2) + '.gif', True)
print (i + 1)"
repeat with f in gifFiles
set numberOfExtractedGIFs to (do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of f) & " " & dest) as integer
end repeat
repeat
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 01.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 02.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 03.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 04.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 05.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
end repeat
There are some issues in the script.
choose file returns a single file. The repeat loop repeat with f in gifFiles breaks the script.
The proper POSIX path to the destination folder is
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
A slash must be added when composing the file path
Try this, the script assumes that the folder Gif in the Resources folder exists.
set gifFile to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFile
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
set pScript to quoted form of "from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os
tName=os.path.basename(sys.argv[1])
dir=sys.argv[2]
app=NSApplication.sharedApplication()
img=NSImage.alloc().initWithContentsOfFile_(sys.argv[1])
if img:
gifRep=img.representations()[0]
frames=gifRep.valueForProperty_('NSImageFrameCount')
if frames:
for i in range(frames.intValue()):
gifRep.setProperty_withValue_(NSImageCurrentFrame, i)
gifRep.representationUsingType_properties_(NSGIFFileType, None).writeToFile_atomically_(dir + '/' + tName + ' ' + str(i + 1).zfill(2) + '.gif', True)
print (i + 1)"
do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of gifFile) & " " & dest
tell application "Finder"
set extractedGiFFiles to files of folder ((path to me as text) & "Contents:Resources:Gif:")
repeat
repeat with aFile in extractedGiFFiles
set the desktop picture to aFile
delay 0.05
end repeat
end repeat
end tell
I am trying to achieve some automation in my current workflow. I'd like to drop images to my applescript application, then have it autoresize to the size as set by the user.
I prompt the user a dialog, where one can enter the pixelsize for width, then have the script do the donkey work.
For some reason it is not running properly, and for the life of my i can't figure out why.
Any and all help is very much appreciated!
Here's the script:
display dialog "What is the desired size?" default answer "64"
set my_answer to text returned of result
on open some_items
repeat with this_item in some_items
try
rescale_and_save(this_item)
end try
end repeat
end open
to rescale_and_save(this_item)
tell application "Image Events"
launch
set the target_width to my_answer
-- open the image file
set this_image to open this_item
set typ to this_image's file type
copy dimensions of this_image to {current_width, current_height}
if current_width is greater than current_height then
scale this_image to size target_width
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_height to (current_height * target_width) / current_width
scale this_image to size new_height
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "scaled." & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
I wrote this script a while ago. It will re-sample an image so its largest dimension is the input value.
on open of myFiles
set my_answer to text returned of (display dialog "What is the desired size?" default answer "64")
repeat with aFile in myFiles
set filePath to aFile's POSIX path
set bPath to (do shell script "dirname " & quoted form of filePath)
tell application "System Events" to set {fileName, fileExt} to {name, name extension} of aFile
set baseName to text 1 thru ((get offset of "." & fileExt in fileName) - 1) of fileName
do shell script "sips " & quoted form of aFile's POSIX path & " -Z " & my_answer & " --out " & quoted form of (bPath & "/" & baseName & "-" & my_answer & "." & fileExt as text)
end repeat
end open