Repeat with contents of multiple lists - applescript

Below is a simplfied version of a script I've been working (and had help with).
and is all working fine.
I'm wanting to develop this so when starting the script it shows dialog box with buttons with that do the below.
Button one Runs Both "Spec1" and "Spec2"
Button Two Runs Both "Spec2" and "Spec3"
Button Three shows a list dialog to select either "Spec1","Spec2","Spec3" (Like the script already does)
The final script will have a few more specs however this is enough to illustrate what I'm trying to achieve
Thanks
-- Spec realted file extensions
--Spec 1
set ListSpec1 to {"_0006", "_0007", "_0010", "_0011"}
--Spec 2
set ListSpec2 to {"_0000", "_0001", "_0002", "_0003", "_0004", "_0005"}
--Spec 3
set ListSpec3 to {"_0006"}
-- Obtain user choice of PS action
set PhotoshopActionList to {"Spec1", "Spec2", "Spec3"}
set ChosenSpec to choose from list PhotoshopActionList with title "Actions Picker" with prompt "Choose Action?"
-- If user cancels, then terminate the script
if ChosenSpec is false then
error number -128 (* user cancelled *)
else
set ChosenSpec to ChosenSpec's item 1 (* extract choice from list*)
end if
--Set image source folder
set SourceFolder to (choose folder with prompt "Choose Base Images:")
set FoldertoReplace to SourceFolder & ChosenSpec as text
--set image save folder
set DestinationFolder to (choose folder with prompt "Choose Save Location:")
set filelocation to DestinationFolder as text
--Setting Files list
tell application "Finder" to set filesList to files of entire contents of SourceFolder whose name ends with ".tif"
repeat with CurrentFile in filesList
tell application "Finder"
set NameF to name of CurrentFile
set currentFileAlias to (CurrentFile as alias) as text
end tell
-- Canadian Files Lists
if ChosenSpec is "Spec1" then
set theListSpecToUse to ListSpec1
else if ChosenSpec is "Spec2" then
set theListSpecToUse to ListSpec2
else
set theListSpecToUse to ListSpec3
end if
-- the file name contains a valid pattern, then process the file
if FNameOK(NameF, theListSpecToUse) then
--open photoshop
tell application "Adobe Photoshop CC 2017"
open alias currentFileAlias
--Canadain Actions
if ChosenSpec is "Spec1" then
do action "Spec1" as text from "Specs"
else if ChosenSpec is "Spec2" then
do action "Spec2" as text from "Specs"
else if ChosenSpec is "Spec3" then
do action "Spec3" as text from "Specs"
end if
--Saving to Format
-- Canadian Saves
if ChosenSpec is "Spec1" then
save current document in filelocation as TIFF with options {class:TIFF save options, image compression:LZW, transparency:true, embed color profile:true}
else if ChosenSpec is "Spec2" then
save current document in filelocation as TIFF with options {class:TIFF save options, image compression:LZW, transparency:true, embed color profile:true}
else
save current document in filelocation as PNG with options {class:PNG save options, compression:9, interlaced:false} appending no extension with copying
end if
--Close Photoshop Document
close current document without saving
end tell
end if
end repeat
on FNameOK(Local_Name, LocalList) -- check if the file name contains an element of the list
set LocalCheck to false
repeat with OneItem in LocalList
if Local_Name contains OneItem then
return true
end if
end repeat
return false
end FNameOK

Related

Applescript / Finder select specific items in a folder including those in disclosed subfolders by file name or file path list

Here's our situation:
We have a list of file names and/or full file paths (we can generate either)
The files in our list are all contained under one folder, but scattered across multiple sub-folders. (There are hundreds of items in our select list from thousands of possible files. Selecting manually isn't an option)
We've got the root folder open in list view and all sub-folders, sub-sub etc disclosure-opened (btw thanks to http://hints.macworld.com/article.php?story=20030218164922494 for the shortcut "command, option, control and shift when pressing the right arrow")
With all files visible under one window open we want to automatically select all the items in our file list so that they can then be dragged at once to an application.
I do not believe that with basic AppleScript one can programmatically select multiple items in Finder which span throughout different folders and subfolders within a given folder in one window. Maybe with Cocoa-AppleScript, don't know, however if Avid can open files from file aliases, then the following example AppleScript code is a viable option.
The example AppleScript code makes the following assumptions:
There is a plain text file containing the fully qualified POSIX pathnames of the target files to be processed with Avid and the name of the file is: List of Files to Process with Avid.txt
The name of the folder containing the aliases is: Aliases of Files to Process with Avid
The Desktop is used as the location in the filesystem that the aforementioned file and folder exists, to be processed by Avid.
Obviously these settings can be changed as needed/wanted, see the comments in the code.
Example AppleScript code:
-- # Set the value of the following three property variables:
-- #
-- # The value of 'thisLocation' is an colon-delimited path string, e.g. 'path to desktop as string' returns: "Macintosh HD:Users:me:Desktop:"
-- # NOTE: When not using 'path to (folder)' where 'folder' is a 'folder constant' , the special folder for which to return the path, the value should be in the form of an colon-delimited path string.
-- # See: https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW19
-- #
-- # The value of 'theListFilename' is the name of the plain text file containing the fully quilified pathnames of the target files to be opened in Avid.
-- # The value of 'theFolderName' is the name of the temporary folder the temporary aliases will be created in. This folder gets created new each run with new aliases.
-- #
-- # NOTE: For ease of use, as each run is presumed to be temporary to get that job run done, the location of the 'theListFilename' and 'theFolderName' are both in 'thisLocation'.
property thisLocation : (path to desktop as string)
property theListFilename : "List of Files to Process with Avid.txt"
property theFolderName : "Aliases of Files to Process with Avid"
-- # The remaining code is tokenized and should not need to be modified.
tell application "Finder"
if (exists thisLocation & theListFilename) then
tell current application to set theList to read alias (thisLocation & theListFilename)
else
display dialog "The file, \"" & theListFilename & "\", was not found at the expected location." buttons {"OK"} ¬
default button 1 with title "Missing File" with icon 0
return
end if
set theFolderPathname to thisLocation & theFolderName
if not (exists theFolderPathname) then
make new folder at thisLocation with properties {name:theFolderName}
else
move theFolderPathname to trash
make new folder at thisLocation with properties {name:theFolderName}
end if
repeat with i from 1 to length of theList
try
make new alias file at theFolderPathname to POSIX file (paragraph i of theList)
end try
end repeat
reveal theFolderPathname
activate
-- delay 1 -- # In necessary, uncomment and adjust value as appropriate.
select every item of alias theFolderPathname
end tell
In Script Editor, save this script and an application, e.g. Select Files to Process with Avid, and then run as needed after replacing the e.g. List of Files to Process with Avid.txt with the current set of target files to be processed with Avid.
The script does the following:
Checks to see the file e.g. List of Files to Process with Avid.txt exists and if not displays error message and exits.
Checks to see if the folder e.g. Aliases of Files to Process with Avid exist and if not creates it, and if it exists, moves it to the Trash and creates it anew, for the new run of target files to be processed.
Creates an alias of each file listed, as a fully qualified POSIX pathname, in the file e.g.: List of Files to Process with Avid.txt
Opens the folder, e.g. Select Files to Process with Avid, in Finder and selects the aliases.
You are now ready to drag and drop the selected aliases to Avid.
Note: This script assumes the fully qualified POSIX pathnames of the target files to be processes with Avid do not contain linefeeds, carriage returns and or null characters in their pathnames.
This works using the latest version of Sierra.
I was not able to figure out a way to selectively select files in folders with subfolders with subfolders etc. The only solution I was able to come up with was to create folder called “Aliases” and have AppleScript create alias files to all of the ”selected files” and store all of the aliases in the aliases folder. From there you can drag all of the files and drop them into your application as you desired
If you have a plain text file containing POSIX path filenames, each on a separate line like the example in this next image, this version will load the pathnames from the text file directly into the script. Just save this script as an application. You can drag text files directly onto the icon of the app because the code is set up to be a droplet
global theFile
property theInfo : missing value
property theName : missing value
property theList : {}
property theList2 : {}
property aliasFolder : (path to desktop as text) & "Aliases"
on open theFiles
set theInfo to info for theFiles
set theName to POSIX path of theFiles
getLinesofFileAsList(theName)
tell application "Finder"
if not (exists of alias aliasFolder) then
make new folder at (path to desktop as text) with properties {name:"Aliases"}
end if
delete every item of alias aliasFolder
end tell
repeat with i from 1 to count of theList
try
set theResult to POSIX file (item i of theList) as text
set end of theList2 to theResult
tell application "Finder"
set theAliases to make new alias file at aliasFolder to theResult
end tell
end try
end repeat
delay 0.5
tell application "Finder"
activate
delay 0.5
set hmmm to reveal aliasFolder
delay 0.5
set hmmm to select every item of alias aliasFolder
activate hmmm
end tell
end open
on getLinesofFileAsList(theName)
set theFile to theName
set theFile to POSIX path of theName
set theList to read POSIX file theFile as text
set saveTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set theList to paragraphs of theList
if last item of theList is "" then
set theList to reverse of rest of reverse of theList
end if
set AppleScript's text item delimiters to saveTID
end getLinesofFileAsList
--on run
-- -- Handle the case where the script is launched without any dropped files
--end run

Copy multiple files using AppleScript

I have to duplicate multiple files using an AppleScript. What this script should do is first, ask the user to select the folder which contains the files that have to be duplicated. Second, show a list of all of the files that there're in the folder that user have selected. In this step, the user can select multiple files. And the last step is duplicate the files. Here's t'he script I'm using:
--Get the folder
set theFolder to (choose folder with prompt "Select the folder that contains the files to copy. In the next step you'll be able to select the files to copy.") as text
--Get the path to de destination folder of the files
set destination_folder to (path to home folder) as text
--Generate the list of files inside theFolder
tell application "Finder"
set theItems to items of folder theFolder
set theNames to {}
repeat with anItem in theItems
set end of theNames to name of anItem
end repeat
end tell
-Let user select the files of the list
choose from list theNames with prompt "Select the files" OK button name "OK" cancel button name "Cancel" with multiple selections allowed
tell result
if it is false then error number -128 -- cancel
set theChoices to it
end tell
if (count of theChoices) is greater than or equal to 1 then
repeat with aChoice in theChoices
set thisItem to theFolder & aChoice
-- do something with thisItem
duplicate thisItem to destination_folder
end repeat
end if
The problem is that when the srcipt has to run the line "copy thisItem to destination_folder" it crashes. Here's the oputput that generates AppleScript Editor when I try to run:
tell application "AppleScript Editor"
choose from list {"Obres.xlsx", "Programa_sardanes", "Sardanes.xlsx"} with prompt "Escull els arxius o l'arxiu que vols afegir" OK button name "Acceptar" cancel button name "Cancelar" with multiple selections allowed
--> {"Sardanes.xlsx"}
-- 'core'\'clon'{ 'insh':'utxt'("Macintosh HD:Users:Joan:"), '----':'utxt'("Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx"), &'subj':null(), &'csig':65536 }
--> error number -1700 from "Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx" to reference
Result:
error "Can't generate \"Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx\" on the type reference." number -1700 from "Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx" to reference
I have been trying several hours to solve this problem but I don't know where is the error on the script. I hope someone could help me. And if someone knows a much more simple way to do this would be helpful also. Thank you!
I made some small changes to your script and it should work now...
Basically, you were missing a couple small portions. The "duplicate" command is a function of the "Finder", so I added a "Tell application "Finder"" to the duplicate portion. You were also storing your path to your file and folder as text, I modified them to be referenced as "alias".
on run
--Get the folder
set theFolder to (choose folder with prompt "Select the folder that contains the files to copy. In the next step you'll be able to select the files to copy.") as text
--Get the path to de destination folder of the files
set destination_folder to (path to home folder)
--Generate the list of files inside theFolder
tell application "Finder"
set theItems to items of folder theFolder
set theNames to {}
repeat with anItem in theItems
set end of theNames to name of anItem
end repeat
end tell
--Let user select the files of the list
choose from list theNames with prompt "Select the files" OK button name "OK" cancel button name "Cancel" with multiple selections allowed
tell result
if it is false then error number -128 -- cancel
set theChoices to it
end tell
if (count of theChoices) is greater than or equal to 1 then
repeat with aChoice in theChoices
set thisItem to (theFolder & aChoice) as alias
-- do something with thisItem
tell application "Finder" to duplicate thisItem to destination_folder
end repeat
end if
end run

Applescript CS5 and CS6 export with save for web will not work

I am at my wit's end. I have tried all variations to get this script to work. The error I get is Adobe Photoshop CS6 got an error: Can’t get current document. and the highlighted script error is my "export in file newFileName.." block. I've tried putting alias in different positions, using file, not using file. Also I get this error message, but the actual script seems to stop working right after "set docName to name of docRef"
And basically I just copied this code from another script that was working fine and just changed a save this file... to a export this file...
-- set the folders that you want to use
set inputFolder to choose folder with prompt "Choose the folder of images to downsize."
set pathToDesktop to (path to desktop folder as string)
set outputFolder to pathToDesktop & "PhotoshopRetina:"
tell application "Finder"
set filesList to files in folder inputFolder
if not (exists folder outputFolder) then
make new folder at desktop with properties {name:"PhotoshopRetina"}
end if
end tell
with timeout of 86400 seconds
tell application "Adobe Photoshop CS6"
set display dialogs to never
close every document saving no
end tell
repeat with aFile in filesList
tell application "Finder"
-- The step below is important because the 'aFile' reference as returned by
-- Finder associates the file with Finder and not Photoshop. By converting
-- the reference below 'as alias', the reference used by 'open' will be
-- correctly handled by Photoshop rather than Finder.
set theFile to aFile as string
set theFileName to name of aFile
set theFileInfo to info for alias theFile
if kind of theFileInfo is "Adobe Photoshop JPEG file" then
my retinaDisplay(theFile)
end if
end tell
end repeat
end timeout
end
on retinaDisplay(theFile)
tell application "Adobe Photoshop CS6"
open alias theFile
set docRef to the current document
-- Convert the document to a document mode that supports saving as jpeg
if (mode of docRef is not RGB) then
change mode docRef to RGB
end if
tell docRef
set color profile kind to none
end tell
set infoRef to get info of docRef
set docName to name of docRef
set docBaseName to getBaseName(docName) of me
set newFileName to (my outputFolder as string) & docBaseName & ".jpg"
tell current document
export in file newFileName as save for web with options {class:save for web export options, web format:JPEG, embed color profile:false, quality:45} with copying
end tell
close current document without saving
end tell
end retinaDisplay
-- Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
exit repeat
end if
end repeat
return baseName
end getBaseName
end
If I open an image in photoshop I can run this code with no errors.
set f to (path to desktop as text) & "test.jpg"
tell application "Adobe Photoshop CS6"
tell current document
export in file f as save for web
end tell
end tell
However, if I additionally add your "with options" code then I get your error. I don't even know what the "with copying" part is. I don't think that means anything to photoshop. So the problem is not with the "current document". The problem is with your options. You must be doing that part wrong.
Good luck.

Folder Action to resize images in Leopard 10.5.8

I know nothing about AppleScript, so please forgive me.
Goal is to create a folder that our graphics guy can drop stock photos into and have them resized to 1280. The chosen folder is a network folder, so don't know if that's part of the issue or not. He will be pasting the images into the folder from his Windows workstation.
Here is what I have pieced together so far:
on adding folder items to this_folder after receiving added_items
repeat with this_item in added_items
try
rescale_and_save(this_item)
end try
end repeat
end adding folder items to
to rescale_and_save(this_item)
tell application "Image Events"
launch
set the target_height to 1280
-- 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_height is greater than current_width then
scale this_image to size target_height
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_width to (current_width * target_height) / current_height
scale this_image to size new_width
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "ex" & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
I've right clicked on the folder, enabled folder actions, and added my script. I copy in the test file but nothing happens.
Any ideas?
EDIT:
I looked at the samples and came up with the following script that WORKS!:
property done_foldername : "Scaled Images"
property target_height : 1280
-- the list of file types which will be processed
-- eg: {"PICT", "JPEG", "TIFF", "GIFf"}
property type_list : {"JPEG", "TIFF", "PNGf"}
-- since file types are optional in Mac OS X,
-- check the name extension if there is no file type
-- NOTE: do not use periods (.) with the items in the name extensions list
-- eg: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
property extension_list : {"jpg", "jpeg", "tif", "tiff", "png"}
on adding folder items to this_folder after receiving these_items
-- CHECK FOR THE DESTINATION FOLDER WITHIN THE ATTACHED FOLDER
-- IF IT DOESN'T EXIST, THEN CREATE IT
tell application "Finder"
if not (exists folder done_foldername of this_folder) then
make new folder at this_folder with properties {name:done_foldername}
set current view of container window of this_folder to list view
end if
set the target_folder to folder done_foldername of this_folder
end tell
-- PROCESS EACH OF THE ITEMS ADDED TO THE ATTACHED FOLDER
try
repeat with i from 1 to number of items in these_items
set this_item to item i of these_items
set the item_info to the info for this_item
-- CHECK TO SEE IF THE ITEM IS AN IMAGE FILE OF THE ACCEPTED FILE TYPE
if (alias of the item_info is false and the file type of the item_info is in the type_list) or (the name extension of the item_info is in the extension_list) then
tell application "Finder"
-- LOOK FOR EXISTING MATCHING ITEMS IN THE DESTINATION FOLDER
-- IF THERE ARE MATCHES, THEN RENAME THE CONFLICTING FILES INCREMENTALLY
my resolve_conflicts(this_item, target_folder)
-- MOVE THE ITEM TO THE DESTINATION FOLDER
set the target_file to (move this_item to the target_folder with replacing) as alias
end tell
-- PROCESS THE ITEM
process_item(target_file)
end if
end repeat
on error error_message number error_number
if the error_number is not -128 then
tell application "Finder"
activate
display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
end tell
end if
end try
end adding folder items to
on resolve_conflicts(this_item, target_folder)
tell application "Finder"
set the file_name to the name of this_item
if (exists document file file_name of target_folder) then
set file_extension to the name extension of this_item
if the file_extension is "" then
set the trimmed_name to the file_name
else
set the trimmed_name to text 1 thru -((length of file_extension) + 2) of the file_name
end if
set the name_increment to 1
repeat
set the new_name to (the trimmed_name & "." & (name_increment as string) & "." & file_extension) as string
if not (exists document file new_name of the target_folder) then
-- rename to conflicting file
set the name of document file file_name of the target_folder to the new_name
exit repeat
else
set the name_increment to the name_increment + 1
end if
end repeat
end if
end tell
end resolve_conflicts
-- this sub-routine processes files
on process_item(this_item)
-- NOTE that the variable this_item is a file reference in alias format
-- FILE PROCESSING STATEMENTS GOES HERE
try
-- convert alias reference to string
set this_item to this_item as string
with timeout of 900 seconds
tell application "Image Events"
launch -- always use with Folder Actions
set this_image to open file this_item
scale this_image to size target_height
save this_image with icon
close this_image
end tell
end timeout
on error error_message
tell application "Finder"
activate
display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
end tell
end try
end process_item
I just tested your script on a folder dropping 1 image in, and it turns out it runs repeatedly because the resulting (resized) image is also added to that folder. Here's what it looked like after a couple of seconds, before I interrupted it:
You should have a look at the default image processing scripts inside /Library/Scripts/Folder Action Scripts and maybe use one of them as a template. They basically use a sub-folder for the processed images and contain some possibly useful filename conflict resolving function, too.

Automator/AppleScript to find same file name with different extension in same directory

I'd like to create an automator action to help manage DNG/XMP files. I'd like to be able to drag a DNG (or several) onto the action which will send the DNG and the matching XMP file to the trash. The files have the same name except for the extension, they are in the same directory. For example, IMGP1361.DNG and IMGP1361.xmp
This would be a simple task for a shell script, but is there an Automator way to do it (to learn more about Automator)? Is there a way to get at the file name of the input finder item, change it in a variable and use that as input to another action?
Thanks.
This script for Automator will delete all of the files that share the same prefix and whose name extension is listed in the grep command. You may add additional extensions as well. (xmp|DNG|pdf|xls)
on run {input, parameters}
try
repeat with anItem in input
tell (info for anItem) to set {theName, theExt} to {name, name extension}
set shortName to text 1 thru ((get offset of "." & theExt in theName) - 1) of theName
tell application "Finder"
set parentFolder to parent of anItem as alias
set matchList to every paragraph of (do shell script "ls " & POSIX path of parentFolder & " | grep -E '" & shortName & ".(xmp|DNG)'")
delete (every file of parentFolder whose name is in matchList)
end tell
end repeat
end try
end run
OK, got it. You can use the AppleScript given below inside an Automator workflow like this:
For every selected file in the Finder, if its extension is in ext_list, it will be moved to the Trash, and so will all other files of the same name in the same folder whose extension is one of those in also_these_extensions.
It can be useful, e.g. also for cleaning a folder with auxiliary LaTeX files: just put "tex" into ext_list and all the other extensions (such as "aux", "dvi", "log") into also_these_extensions.
The selected files don't need to be inside the same folder; you can also select several items in a Spotlight search results window.
on run {input, parameters}
-- for every item having one of these extensions:
set ext_list to {"dng"}
-- also process items with same name but these extensions:
set other_ext_list to {"xmp"}
tell application "Finder"
set the_delete_list to {}
set delete_list to a reference to the_delete_list
-- populate list of items to delete
repeat with the_item in input
set the_item to (the_item as alias)
if name extension of the_item is in ext_list then
copy the_item to the end of delete_list
set parent_folder to (container of the_item) as alias as text
set item_name to text 1 thru ((length of (the_item's name as text)) - (length of (the_item's name extension as text))) of (the_item's name as text)
repeat with ext in other_ext_list
try
copy ((parent_folder & item_name & ext) as alias) to the end of delete_list
end try
end repeat
end if
end repeat
-- delete the items, show info dialog
move the_delete_list to the trash
display dialog "Moved " & (length of the_delete_list) & " files to the Trash." buttons {"OK"}
end tell
end run

Resources