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
Related
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
Since OSX seems to lack a keyboard shortcut to create a new space/desktop, I'm wondering if this could be accomplished creating an applescript and binding that to a keyboard shortcut.
Looked a ton on google and couldn't find anything. Surprised no one has asked this before... seems like it would be something that lots of people would find very useful.
Here are the list of AppleScript Spaces routines I found online ::
--my get_spaces_enabled()
--my set_spaces_enabled(enable_spaces)
--my toggle_spaces_enabled()
--my get_spaces_rows()
--my set_spaces_rows(row_count)
--my get_spaces_columns()
--my set_spaces_columns(column_count)
--my get_spaces_count()
--my show_all_spaces()
--my get_spaces_application_bindings()
--my set_spaces_application_bindings(new_bindings)
--my collect_application_in_current_space(application_bundle_id)
--my set_spaces_application_binding_for_application(application_bundle_id, chosen_space)
--my get_space_binding_for_application(application_bundle_id)
--my choose_space_for_current_application()
--my choose_space_for_application(application_bundle_id)
--my remove_spaces_application_binding(application_bundle_id)
--my get_spaces_arrow_key_modifiers()
--my get_spaces_numbers_key_modifiers()
--my switch_to_space(space_number)
--my open_spaces_preferences()
--my display_spaces_not_enabled_error()
on get_spaces_enabled()
tell application "System Events" to tell spaces preferences of expose preferences to return (get spaces enabled)
end get_spaces_enabled
on set_spaces_enabled(enable_spaces)
tell application "System Events" to tell spaces preferences of expose preferences to set spaces enabled to enable_spaces
end set_spaces_enabled
on toggle_spaces_enabled()
my set_spaces_enabled(not (my get_spaces_enabled()))
end toggle_spaces_enabled
on get_spaces_rows()
tell application "System Events" to tell spaces preferences of expose preferences to return (get spaces rows)
end get_spaces_rows
on set_spaces_rows(row_count)
tell application "System Events" to tell spaces preferences of expose preferences to set spaces rows to row_count
end set_spaces_rows
on get_spaces_columns()
tell application "System Events" to tell spaces preferences of expose preferences to return (get spaces columns)
end get_spaces_columns
on set_spaces_columns(column_count)
tell application "System Events" to tell spaces preferences of expose preferences to set spaces columns to column_count
end set_spaces_columns
on get_spaces_count()
return ((my get_spaces_rows()) * (my get_spaces_columns()))
end get_spaces_count
on show_all_spaces()
try
tell application "Finder" to set spaces_app_path to (application file id "com.apple.spaceslauncher") as string
do shell script "open " & quoted form of POSIX path of spaces_app_path
end try
end show_all_spaces
on get_spaces_application_bindings()
tell application "System Events" to tell spaces preferences of expose preferences to return (get application bindings)
end get_spaces_application_bindings
on set_spaces_application_bindings(new_bindings)
tell application "System Events" to tell spaces preferences of expose preferences to set application bindings to new_bindings
end set_spaces_application_bindings
on collect_application_in_current_space(application_bundle_id)
set application_bundle_id to my make_lowercase(application_bundle_id)
set app_bindings to my get_spaces_application_bindings()
my set_spaces_application_bindings((run script "{|" & application_bundle_id & "|:65544}") & app_bindings)
my set_spaces_application_bindings(app_bindings)
end collect_application_in_current_space
on set_spaces_application_binding_for_application(application_bundle_id, chosen_space)
set application_bundle_id to my make_lowercase(application_bundle_id)
if chosen_space is in {0, "None"} then
my remove_spaces_application_binding(application_bundle_id)
else
if chosen_space = "All" then set chosen_space to 65544
my set_spaces_application_bindings((run script "{|" & application_bundle_id & "|: " & chosen_space & "}") & (my get_spaces_application_bindings()))
end if
end set_spaces_application_binding_for_application
on get_space_binding_for_application(application_bundle_id)
set application_bundle_id to my make_lowercase(application_bundle_id)
set app_bindings to my get_spaces_application_bindings()
try
get app_bindings as string
on error error_string
set app_bindings to my string_to_list(text 13 thru -20 of error_string, ", ")
end try
repeat with i from 1 to (count app_bindings)
if item i of app_bindings starts with ("|" & application_bundle_id & "|:") then return (item 2 of (my string_to_list(item i of app_bindings, ":"))) as number
end repeat
return 0
end get_space_binding_for_application
on choose_space_for_current_application()
return my choose_space_for_application(bundle identifier of (info for (path to frontmost application)))
end choose_space_for_current_application
on choose_space_for_application(application_bundle_id)
set application_bundle_id to my make_lowercase(application_bundle_id)
if (not my get_spaces_enabled()) then if (not my display_spaces_not_enabled_error()) then return false
try
tell application "Finder" to set app_path to (application file id application_bundle_id) as string
set app_name to short name of (info for (app_path as alias))
set the_choices to {"None", "All"}
repeat with i from 1 to (my get_spaces_count())
set end of the_choices to i
end repeat
set default_space to my get_space_binding_for_application(application_bundle_id)
if default_space = 0 then
set default_space to "None"
else if default_space = 65544 then
set default_space to "All"
end if
set chosen_space to (choose from list the_choices default items {default_space} with title "Spaces Assigner" with prompt "Assign " & app_name & " to Space:" OK button name "Assign" without multiple selections allowed and empty selection allowed)
if chosen_space = false then return false
my set_spaces_application_binding_for_application(application_bundle_id, item 1 of chosen_space)
return true
on error e number n
log "choose_space_for_application (" & application_bundle_id & ") Error (" & n & "): " & e
return false
end try
end choose_space_for_application
on remove_spaces_application_binding(application_bundle_id)
set application_bundle_id to my make_lowercase(application_bundle_id)
set app_bindings to my get_spaces_application_bindings()
try
get app_bindings as string
on error error_string
set app_bindings to my string_to_list(text 13 thru -20 of error_string, ", ")
end try
set new_bindings to {}
repeat with i in app_bindings
set i to contents of i
if i does not start with "|" & application_bundle_id & "|:" then set end of new_bindings to i
end repeat
my set_spaces_application_bindings(run script "{" & (my list_to_string(new_bindings, ", ")) & "}")
end remove_spaces_application_binding
on get_spaces_arrow_key_modifiers()
tell application "System Events" to tell spaces preferences of expose preferences to return (get key modifiers of (get properties of arrow key modifiers))
end get_spaces_arrow_key_modifiers
on get_spaces_numbers_key_modifiers()
tell application "System Events" to tell spaces preferences of expose preferences to return (get key modifiers of (get properties of numbers key modifiers))
end get_spaces_numbers_key_modifiers
on switch_to_space(space_number)
if not my gui_scripting_check() then return
set key_modifiers to my get_spaces_numbers_key_modifiers()
tell application "System Events"
set key_modifier_list to {}
if key_modifiers contains command then set end of key_modifier_list to "command down"
if key_modifiers contains control then set end of key_modifier_list to "control down"
if key_modifiers contains option then set end of key_modifier_list to "option down"
if key_modifiers contains shift then set end of key_modifier_list to "shift down"
set key_modifier_list to my list_to_string(key_modifier_list, ", ")
if key_modifier_list ≠ "" then set key_modifier_list to " using {" & key_modifier_list & "}"
end tell
run script ("tell application \"System Events\" to keystroke \"" & space_number & "\"" & key_modifier_list)
end switch_to_space
on open_spaces_preferences()
tell application "System Preferences"
activate
tell pane id "com.apple.preference.expose" to reveal anchor "Spaces"
end tell
end open_spaces_preferences
on display_spaces_not_enabled_error()
beep
activate
if ((button returned of (display dialog "Spaces is not enabled. Would You like to enable it now?" with title "Spaces Error" buttons {"Keep Disabled", "Enable"} default button 2 with icon 0)) = "Keep Disabled") then return false
my set_spaces_enabled(true)
return true
end display_spaces_not_enabled_error
on list_to_string(l, d)
tell (a reference to my text item delimiters)
set {o, contents} to {contents, d}
set {l, contents} to {"" & l, o}
end tell
return l as Unicode text
end list_to_string
on string_to_list(s, d)
tell (a reference to my text item delimiters)
set {o, contents} to {contents, d}
set {s, contents} to {s's text items, o}
end tell
return s
end string_to_list
on gui_scripting_check()
tell application "System Events" to set gui_scripting_enabled to UI elements enabled
if not gui_scripting_enabled then
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.universalaccess"
display dialog "This application utilizes the built-in Graphic User Interface Scripting architecture of Mac OS X which is currently disabled." & return & return & "You can activate GUI Scripting by selecting the checkbox \"Enable access for assistive devices\" in the Universal Access preference pane." with icon 2 buttons {"OK"} default button 1
end tell
end if
return gui_scripting_enabled
end gui_scripting_check
on make_lowercase(the_string)
return do shell script "echo " & quoted form of the_string & " | /usr/bin/perl -pe 'use encoding utf8; s/(\\w)/\\L$1/gi'"
end make_lowercase
You can use these to make your code :)
Link to the routines site :: MacScripter - Applescript Spaces Routine
Anyone of you guys could point me to why this applescript (which was working on snow leopard) does not work anymore on 10.7 Lion.
It intend to copy the file named "folder.jpg" from each album folder into ID3 tags of selected mp3 in iTunes.
property tempfile : ((path to temporary items as string) & "itunespicturefile_temporaire.pict")
global vPictFolder
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData("folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(vAlbumpictName)
tell application "Finder" to tell file vAlbumpictName of folder vPictFolder to if exists then
set t_file to it as string
else
display dialog vPictFolder & vAlbumpictName
return ""
end if
do shell script "/opt/local/bin/convert " & quoted form of POSIX path of t_file & " " & quoted form of POSIX path of tempfile
display dialog "ok"
return read (tempfile as alias) from 513 as picture
end getpictData
on ParentFromPath(thePath)
set wantPath to true
set thePath to (thePath as text)
set saveDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to {":"}
set pathAsList to text items of thePath
if the last character of thePath is ":" then
set idx to (the number of text items in thePath) - 2
else
set idx to -2
end if
if wantPath then
set folderName to ((text items 1 through idx of pathAsList) as text) & ":"
else
set folderName to item idx of pathAsList
end if
set AppleScript's text item delimiters to saveDelim
return folderName
end ParentFromPath
Because Picture format (".pict") is not supported on Lion and newer OS.
You can use the term picture to read a image file (JPEG, PNG, ...), the format will not be in the Picture format , but the original format of the file.
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData(vPictFolder & "folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(tFile)
try
return (read (tFile as alias) as picture)
end try
display dialog tFile
return "" -- not exists
end getpictData
Code snippet:
tell application "Finder" to set new_item to ¬
(container of this_item as string) & (name of this_item) & "s"
save this_image in new_item as typ
Its saving the file as filename.pngs I want it to save as filenames.png. Any ideas how to fix this?
Save this as an application, then you can drop things on it and it will copy them adding an s to the name. Or you can double-click it and it will ask you to choose a file to copy. NOTE: change the property appendText if you want to change the text (i.e. "s") that's added to the name.
Notice the handler getName_andExtension(f). That's what I use to get the name and extension from a file. I use that to calculate the new path when adding the s.
I hope that helps!
property appendText : "s"
on run
set f to choose file
duplicateInPlace_appendingText(f, appendText)
end run
on open the_items
repeat with f in the_items
duplicateInPlace_appendingText(f, appendText)
end repeat
end open
on duplicateInPlace_appendingText(f, textToAppend)
set f to f as text
set {nm, ex} to getName_andExtension(f)
tell application "Finder" to set theContainer to (container of item f) as text
if ex is "" then
set new_path to theContainer & nm & textToAppend
else
set new_path to theContainer & nm & textToAppend & "." & ex
end if
do shell script "cp -R " & quoted form of POSIX path of f & space & quoted form of POSIX path of new_path
end duplicateInPlace_appendingText
on getName_andExtension(f)
set f to f as text
set {name:nm, name extension:ex} to info for file f without size
if ex is missing value then set ex to ""
if ex is not "" then
set nm to text 1 thru ((count nm) - (count ex) - 1) of nm
end if
return {nm, ex}
end getName_andExtension
name of this_item gives the full name of the Finder item, including the file extension. You need to split it up. Unfortunately, this isn't as easy as it could be. You could do something like:
tell application "Finder"
get the selection
set {dispname, ext, exthidden} to {displayed name, name extension, extension hidden} of item 1 of the result
end tell
if exthidden then
dispname & "s." & ext
else
((characters 1 through -(2 + (count of ext)) of dispname) as string) & "s." & ext
end if
That just builds the modified name for the first item in the Finder selection, without doing anything with it.