Select the first image in a folder selected in the Fiinder - applescript

I have a script that changes the icon of a folder with the image you select and it works fine but I want to be able to have the script automatically select the first image of the folder and assign that as the image that will be used to create the icon.
This is what I have so far. It is unable to select the image and gives various error messages depending on what I try. Any help would be greatly appreciated!
set exePath to (path to home folder as text) & "downloads:SetFileIcon"
tell application "Finder"
set theSelection to selection -- This is a list of selected items, even if only 1 item is selected.
set theFile to (item 1 of theSelection) as text -- Get the first item in the list. We make it text so we can convert it to a posix path for SetFileIcon.
set theimage to item 1 of theSelection
set imagePath to (path to desktop folder as text) and theimage
end tell
do shell script quoted form of POSIX path of exePath & " -image " & quoted form of POSIX path of imagePath & " -file " & quoted form of POSIX path of theFile

A couple of issues with your script at first glance. First, you’re never asking for the contents of the folder. You set theFile to item 1 of theSelection and then you set theimage to item 1 of theSelection. I expect you meant to set theimage to item 1 of the document files of theFile. Note that theFile is actually the selected folder.
Second, “and” is a boolean operation; to concatenate text in AppleScript, use “ & ”. Thus, even if theimage contained the image’s name, you would need to use & theimage.
However, since you are asking the Finder for the information, the Finder already knows the full path to any particular file. So, once you get an image, you can ask the Finder for the path directly.
tell application "Finder"
-- This is a list of selected items, even if only 1 item is selected.
set theSelections to the selection
-- This code assumes that the first selected item is a folder
set theFolder to the first item of theSelections
-- we want the first document that is also an image
set theImages to the document files of theFolder whose kind contains "image"
set theImage to item 1 of theImages as text
-- and we want it's path
set imagePath to POSIX path of theImage
end tell

Related

How do get last downloaded image to insert into object placeholder of current keynote slide?

Images are key to my work.
I am trying to find a quick way to automate image insertion to keynote. The script I am drafting is to get the last created/downloaded image, and insert it into the current slide on Keynote as a replacement of the master's object placeholder.
Error from applescript:
"Keynote got an error: Can’t set file name of slide 2 of document id \"B1054797-9A07-4642-AE79-166D1DE72674\" to alias." number -10006 from file name of slide 2 of document id "B1054797-9A07-4642-AE79-166D1DE72674" to alias
set myFolder to "/Users/Mingyu/Desktop/UpperEchelon"
tell application "Finder" to set latestFile to item 1 of (sort files of (POSIX file myFolder as alias) by creation date) as alias
tell application "Keynote"
activate
tell the front document
tell the current slide
set thisPlaceholderImageItem to item 1
set file name of thisPlaceholderImageItem to ¬
alias
end tell
end tell
end tell
I expect the script will insert last download image in the folder "UpperEchelon" to a current open slide in Keynote
Two issues:
You have to set thisPlaceholderImageItem to image 1 rather than to item 1
You have to set the file name to latestFile rather than just to alias. That's what the error is telling you.
And if the folder is a subfolder of the desktop there is a much shorter syntax
set myFolder to "UpperEchelon"
tell application "Finder" to set latestFile to item 1 of (sort files of folder myFolder by creation date) as alias
tell application "Keynote"
activate
tell the front document
tell the current slide
set thisPlaceholderImageItem to image 1
set file name of thisPlaceholderImageItem to latestFile
end tell
end tell
end tell

How to show composite icons using Display Dialog

Is there any way to display Display Dialog icons like macOS does, I tried looking for the icon below in /System/Library/CoreServices/CoreTypes.bundle
but I didn't find it.
set myIcon to (path to resource "myIcon.icns")
display dialog "this is my icon" buttons {"OK"} default button "OK" with icon myIcon
All of the standard Apple icons are stored here:
`/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources`
You can access them directly, as in the following.
set iconFIle to choose file "Choose an icon file" of type {"com.apple.icns"} ¬
default location POSIX file "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources"
display dialog "This is a test" with icon iconFIle
Note that the Finder sometimes does composite icons by using one icon as an overlay or badge applied to another icon. For instance, I believe the image you posted above is the file "KEXT.icns" overlaid with the file "AlertCautionBadgeIcon.icns." You can mimic that behavior with the following script.
set basePath to POSIX path of (path to library folder from system domain) & "CoreServices/CoreTypes.bundle/Contents/Resources/"
set tempStoragePath to POSIX path of (path to temporary items from user domain)
-- set the name of the main idon, and the overlay icon
set mainName to "KEXT"
set overlayName to "AlertCautionBadgeIcon"
set kextImgPath to basePath & mainName & ".icns"
set alertImgPath to basePath & overlayName & ".icns"
set tempSetPath to quoted form of (tempStoragePath & mainName & ".iconset" as text)
set tempOverlayPath to quoted form of (tempStoragePath & overlayName & ".iconset" as text)
-- decompose the icns into iconsets, so that we can do the overlays by hand
do shell script "iconutil -c iconset -o " & tempSetPath & " " & kextImgPath
do shell script "iconutil -c iconset -o " & tempOverlayPath & " " & alertImgPath
tell application "System Events"
set mainFolder to folder (mainName & ".iconset") of folder tempStoragePath
set overlayFolder to folder (overlayName & ".iconset") of folder tempStoragePath
set theFiles to (files of mainFolder whose name extension is "png")
(*
iconsets are folders with files named (e.g.) 'icon_16x16.png', 'icon_128x128#2x.png'
this loop runs through and finds matching sized elements of the set, then sends
them to the script object's handler for processing with ASOC
*)
repeat with thisFile in theFiles
set fileName to name of thisFile
if exists file (name of thisFile) of overlayFolder then
asocBits's mungePNGs(POSIX path of thisFile, POSIX path of (file fileName of overlayFolder))
end if
end repeat
end tell
-- convert the iconset folders back to icns files, then send the file to display dialog
do shell script "iconutil -c icns " & tempSetPath
display dialog "This is a test" with icon POSIX file (tempStoragePath & mainName & ".icns")
script asocBits
use framework "Foundation"
use framework "AppKit"
property NSImage : class "NSImage"
property NSBitmapImageRep : class "NSBitmapImageRep"
on mungePNGs(mainImg, overlay)
-- get respective images
set mainImgObj to NSImage's alloc's initWithContentsOfFile:mainImg
set overlayObj to NSImage's alloc's initWithContentsOfFile:overlay
-- create a destination image
set newImage to NSImage's alloc's initWithSize:(mainImgObj's |size|)
newImage's lockFocus()
-- set up apprpriate drawing rects, then draw the two images into the new image.
set newRect to current application's CGRectZero as list
set imgSize to mainImgObj's |size| as list
set item 2 of newRect to item 1 of imgSize
set h to (height of item 1 of imgSize)
(*
these were trial and error. remember that (0,0) is the bottom left,
not the top left (y goes from bottom to top).
placementRect is supposed to be where the overlay is placed.
cropRect is the part of the overlay that's pasted.
different badges have their effective images in different quadrants.
*)
set placementRect to current application's CGRectMake(0.5 * h, 0.0, h, h)
set cropRect to current application's CGRectMake(0.5 * h, 0.5 * h, h, h)
mainImgObj's drawInRect:newRect
set op to current application's NSCompositeSourceOver
overlayObj's drawInRect:placementRect fromRect:cropRect operation:op fraction:1.0
-- create a bitmap representation and save it back to the main iconset file
set bitmapRep to NSBitmapImageRep's alloc's initWithFocusedViewRect:newRect
newImage's unlockFocus()
set PNGType to current application's NSBitmapImageFileTypePNG
set imgData to (bitmapRep's representationUsingType:PNGType |properties|:(missing value))
imgData's writeToFile:mainImg atomically:false
end mungePNGs
end script
The script is on the slow side, but it gets the job done. In the long run, it might be more efficient simply to use the script object to create icns files that you can store in the bundle and call at need.
Technical detail: I've used a script object to isolate the ASOC routines from the rest of the script. ASOC and osax commands don't always play well together. In this case, display dialog with icon always seems to throw an error if any frameworks have been invoked. I suppose I could have used tell framework "..." blocks instead, but the script object appealed to me...
As Ted correctly answered you can't display compound icons.
But you can do the opposite, displaying your application icon with a caution or stop badge.
To do so omit the reference to the icon and use the other – enumerated – with icon parameter
display dialog "this is my icon" buttons {"OK"} default button "OK" with icon caution
display dialog "this is my icon" buttons {"OK"} default button "OK" with icon stop

AppleScript cannot save a textedit file

I'm using a code to format textedit files for lab data.
I currently am using AppleScript to create a document in TextEdit and adding text to it, but when I try to save it, TextEdit gives me the error "you do not have permission to save as blahblahblah." I have already tried changing the permission on the folder in which I'm saving it in, but I think it may have something to do with it being a file that AppleScript created.
The exact error output is a dialog box from TextEdit
The document “1.txt” could not be saved as “1”. You don’t have permission.
To view or change permissions, select the item in the Finder and choose File > Get Info.
The segments of my code that don't work are
tell application "TextEdit"
make new document with properties {name:("1.txt")}
end tell
--data formatting code here (n is set here)
tell application "TextEdit"
delay 1
close document 1 saving in ("/Users/bo/Desktop/Script Doc/" & (n as string))
set n to n + 1
make new document with properties {name:((n as string) & ".txt")}
delay 1
end tell
I have scoured other questions and I have found the code segments
open for access document 1
close access document 1
but I'm not sure how to implement these / if I even should, and if not, I'm not sure how to fix this issue.
Thanks in advance
Unfortunately, that error message isn't helping much. You are essentially trying to save into a string, which isn't going to work - you need to use a file specifier, for example:
close document 1 saving in POSIX file ("/Users/bo/Desktop/Script Doc/" & n & ".txt")
Note that not everything knows about POSIX paths, in which case you will need to coerce or specify it as in my example.
Saving directly to the Desktop works for me using the latest version of macOS Mojave
property outputPath : POSIX path of (((path to desktop as text) & "Script Doc") as alias)
property docNumber : 1
property docExtension : ".txt"
tell application "TextEdit"
set docName to (docNumber & docExtension) as text
set theText to "Your Desired Text Content"
set thisDoc to make new document with properties {name:docName, text:theText}
close thisDoc saving in POSIX file (outputPath & "/" & (name of thisDoc))
(* IF YOU WANT TO SAVE MULTIPLE FILES WITH CONSECUTIVE NAMES *)
set docNumber to docNumber + 1
set docName to (docNumber & docExtension) as text
set thisDoc2 to make new document with properties {name:docName} -- Removed Text Property This Time
close thisDoc2 saving in POSIX file (outputPath & "/" & (name of thisDoc2))
end tell
TextEdit is sandboxed. You cannot save documents in the standard desktop folder.
An alternative is to hard-code the path to the documents folder in the container of TextEdit.
tell application "TextEdit"
make new document with properties {name:"1.txt"}
end tell
set containerDocumentsFolder to (path to library folder from user domain as text) & "Containers:com.apple.TextEdit:Data:Documents:"
tell application "TextEdit"
close document 1 saving in containerDocumentsFolder & (n as string) & ".txt"
set n to n + 1
make new document with properties {name:(n as string) & ".txt"}
end tell

Move all files / folder within SmartFinderFolder to destination w/ serial / single consecutive operation with AppleScript MacOS Serria

Objective: Move all files and files in folders to destination folder and maintain the file structure [files and named folders]. Important for music files in albums.
Functional: Move all listed files in SmartFolder [named] to destinationFolder with serial / consecutive move operation and maintain the same file structure and copy of dataFiles listed in SmartFolder.
Key: All files were obtained for transfer. Normal CMD + A, CMD + C, CMD + V hangs up the computer and the transfer does not initiate. The AppleScript to move each dataObject to destinationPath is all.
Facts: How to reference objects [files, folders] and their proper reference format and accepted path syntax; path or POSIX, and use of alias. Basic operations. I ran an AppleScript to move filePath to pathDestination, and was otherwise successful, and would be nice to known the formalization syntax for path reference.
tell application "Finder"
move allFiles to destinationFolder
// recursive/repeat code to loop through all listed files and folder
end tell
Reference: Applescript, show all files with tag
[Moving / selecting listed files from 'smartfolder' containers as active windows and displayLists. It was an alt. solution since AppleScript will not reference the SmartFolder as an object, nor will it dynamically call the listProperty of the SmartFolder object unless called by an unknown or un-reference method or command.
Since your main issue, as far as I can tell, seems to be dealing with SmartFolders in AppleScript, which—as you said—cannot be referenced as folder objects, this little snippet might be of help:
set SmartFolder to "/Users/CK/My Smart Folder.savedSearch"
tell application "System Events" to get value of property list file SmartFolder
set {[Scope], Query} to {SearchScopes, RawQuery} of RawQueryDict of result
set AppleScript's text item delimiters to tab
set Command to {"mdfind -onlyin", ¬
quoted form of Scope as text, ¬
quoted form of Query as text} as text
set SearchResults to paragraphs of (do shell script Command)
--> returns a list of posix files
--> e.g. {"/Users/CK/Downloads/This is file one.txt", ...}
This will return a list of POSIX paths to files that match the search criteria.
I would recommend using System Events rather than Finder to deal with large numbers of files. It can also handle posix paths without the need to manually coerce them into aliases or whatever. So, given a posix path, such as the ones returned in the list using the above code snippet, you simply do this:
set myfile to item 1 of SearchResults
tell application "System Events" to move myfile to "/Users/CK/Desktop"
Without knowing more details of what your smart folder contains (since some searches could easily return a folder plus the contents of that folder, which you'd have to bear in mind when getting your AppleScript to recurse through the search results), I can't give you more than that. But, you said your main problems were being unable to handle SmartFolders and not knowing how to reference files/folders.
This works for me using the latest version of Sierra.
Set the value of property moveToNewFolderto the destination folder of your choice
This script creates a "Choose From List" Dialog, allowing you to choose any smart folder which resides on your system. It will then move all of these files and folders in the chosen smart folder, to your set destination folder.
property savedSearches : (path to home folder as string) & "Library" & ":Saved Searches"
property savedSearchesSubFolders : {}
property namesOfSavedSearchesSubFolders : {}
property selectedSearchFolder : ""
property selectedSearchFolderPath : missing value
property moveTheseItems : missing value
property moveToNewFolder : (path to desktop as text) & "untitled folder" -- change this value to your preferred destination folder
tell application "Finder"
activate
delay 0.1 -- may need to adjust delay time value
open savedSearches
delay 0.1 -- may need to adjust delay time value
reveal savedSearches
delay 0.1 -- may need to adjust delay time value
select savedSearches
delay 0.1 -- may need to adjust delay time value
set current view of Finder window 1 to column view
delay 0.1 -- may need to adjust delay time value
tell its Finder window (POSIX path of savedSearches)
delay 0.1 -- may need to adjust delay time value
set savedSearchesSubFolders to items
set namesOfSavedSearchesSubFolders to name of items
-- Allows to choose any smart folder from a list of all smart folders
set selectedSearchFolder to choose from list namesOfSavedSearchesSubFolders ¬
with title ¬
"Smart Search Folders" with prompt ¬
"Choose Your Folder" OK button name ¬
"OK" cancel button name "CANCEL"
set selectedSearchFolder to selectedSearchFolder as text
set selectedSearchFolderPath to savedSearches & ":" & selectedSearchFolder
set selectedSearchFolderPath to selectedSearchFolderPath as string
end tell
delay 0.2 -- may need to adjust delay time value
select selectedSearchFolderPath
tell Finder window 1
set defaultView to current view
set current view to list view
delay 0.1 -- may need to adjust delay time value
set current view to defaultView
delay 0.5 -- may need to adjust delay time value
tell application "System Events"
key code 0 using command down
end tell
end tell
set moveTheseItems to selection
end tell
tell application "Finder"
set resultObject to move moveTheseItems ¬
to moveToNewFolder ¬
with replacing
end tell

Applescript: Unable to make script into droplet

Please excuse my less-than-elegant scripting ability, but the script is working fine when invoked within the script editor itself. When I save it as an application however, the icon doesn't show that it's a droplet and does not work as such. Any help is greatly appreciated!
try
set destinationFolder to "Mercury:F1_PropertyLogos:"
tell application "Finder" to set logoFileName to name of item 1 of (get selection)
end try
set file_name to logoFileName
set file_name to remove_extension(file_name)
on remove_extension(this_name)
if this_name contains "." then
set this_name to ¬
(the reverse of every character of this_name) as string
set x to the offset of "." in this_name
set this_name to (text (x + 1) thru -1 of this_name)
set this_name to (the reverse of every character of this_name) as string
end if
return this_name
end remove_extension
tell application "Finder"
set selected_items to selection
set theFolder to "Mercury:F1_PropertyLogos:"
repeat with x in selected_items
move x to theFolder
end repeat
end tell
tell application "QuarkXPress"
set mypath to "Mercury:F1_Layouts:"
set myfile to file_name
set extension to ".qxp"
set logoFolderPath to "Mercury:F1_PropertyLogos:"
set myLogoFile to file_name
set myLogoExtension to ".psd"
set myLogo to (logoFolderPath & myLogoFile & myLogoExtension)
open file (mypath & myfile & extension)
set selected of picture box "Logo" of spread 1 of document 1 to true
set image 1 of picture box "Logo" of spread 1 of document 1 to file myLogo
set bounds of image 1 of picture box "Logo" of spread 1 of document 1 to proportional fit
end tell
end
To deal with items dropped onto the application, you will need to add an open handler that receives a list of the dropped items (even if there is only one), for example:
on open theDroppedItems
-- whatever
end open
You should probably rearrange your code to place your main statements into a handler (or handlers) that can be called from multiple places, since double-clicking on the application will call the run handler instead.

Resources