Manually Change File Name use Clipboard Text (if available) plus...

Hello everyone,

I have spent many evenings, and weekends, trying to make the code below work, and I have hit a wall. Can someone please help?

The code has been based on a post found on Noodlesoft Forums - https://www.noodlesoft.com/forums/viewtopic.php?f=4&t=921#

The code seems to work fine when ‘Quit’ or ‘Clear Cache’ are selected. I need to ensure that apart from accepting the ‘Quit’ option the user input screen is always returned until the rules in Hazel are met - see below.

For example, I select continue and the cache is not as desired. In this instance I select Cancel and I am returned to the Continue, Quit or Clear Cache buttons. I select Clear Cache and the cache is cleared. I am returned back to the Continue, Quit or Clear Cache button options again, or even directly back to the user input dialog box with current name of the file ready to enter the new name details.

In another example, If I select Quit and then select Cancel, as Quit was selected in error, I should be returned to the Continue, Quit or Clear Cache buttons . The only Time the code should stop is if I have completed the new name, selected OK and the Hazel conditions are met, or if I select Quit and confirm by selecting OK.

My code currently opens the dialog box, as expected, upon selecting Continue. The dialog box shows either the Current Name or the Cached name plus Current Name. However, these details are not saved when selecting OK. The code seems to loop. This has happened in every version of the code used (including the base from the forum) not just the version of the code below.

The code does add the Green label when selecting OK under the rename dialog box, however, the file is NOT given the new name details entered. In this instance Hazel moves the file in error believing all is well, because it has a Green label.

One other glitch I have noted is a doubling of the cached name, which I would rather didn’t happen. I believe this is because the file is not saving as intended, does not have the relevant colour label and is being re-run by Hazel.

I am using Hazel to manually rename files after they have been from a remote location to a monitored folder and other rules have been processed. At present the code is run as an embedded script within Hazel, although it could run as a droplet if easier to work with or solve the problems I am experiencing.

Core objectives:


--tell application "Finder" to activate
tell application "Finder"
	
	
	set currentName to name of theFile
	set the clipboard to «class ktxt» of ((the clipboard as text) as record) # remove styles from the clipboard
	set theCaption to the clipboard
	copy length of theCaption to theCaptionlength # test the length of theCaption
	if theCaptionlength > 100 then
		set theCaption to text 1 thru 100 of theCaption # respect the maximum filename-length of 255. Some characters obviously don't count so the limit is set low here
	else
		set theCaption to theCaption # do nothing
	end if
	repeat
		
		display dialog "Add New Details to the current file?" buttons {"Continue", "Quit", "Clear Cache"} default button 3
		
		
		if the button returned of the result is "Continue" then
			
			-- action for 1st button goes here
			(display dialog "Add New Details:" default answer theCaption & currentName buttons {"Cancel", "OK"})
			
			if button returned of (result) = "OK" then
				
				set name of theFile to theCaption & currentName
				# None = 0 | Orange = 1 | Red = 2 | Yellow = 3 | Blue = 4 | Purple = 5 | Green = 6 | Gray = 7
				set label index of theFile to 6
				display alert "All done! Image has been renamed  for you."
				
				
				return
			else
				return input
			end if
			return
			
		else if the button returned of the result is "Quit" then
			
			-- action for Quit 2nd Action button goes here
			
			display dialog ("Quit current application?" & return & "(" & theFile & ")") buttons {"Cancel", "OK"} default button 2
			
			
			if button returned of (result) = "ok" then
				
				--set currentName to name of theFile
				set label index of theFile to 4
				tell application "System Events" to quit
				
				return
			end if
			return
		else
			
			-- action for 3rd button goes here
			
			tell application "System Events" to set the clipboard to ""
			
			return input
			return
			
			
		end if
		return
	end repeat
end tell


My coding skills are very poor, but I am trying to learn as I go, so any changes you guys make please highlight, and explain what they do.This will help me learn where I have gone wrong, and hopefully get better over time.

Many thanks in advance for any help in making this work. :slight_smile:

I’ll try to help, but 1) I will not use Hazel, because I do not want to install an extra software 2) we will go step by step

Step 1. Create one HOT folder on your Mac. As say, folder with name “Newspapers_Folder”
Step 2. Attack to it this handler:


on adding folder items to this_folder after receiving added_items
	set currentFile to item 1 of added_items -- getting new added file to AppleScript
	-- open file in Preview
	tell application "Preview"
		activate
		open currentFile
	end tell
	
	do shell script "printf %s \"\" | pbcopy" -- clear clipboard
	display dialog "Now COPY desired article header"
	
	-- getting copied header to AppleScript
	set copied_Header to ""
	repeat while (copied_Header = "")
		try
			set copied_Header to (the clipboard as string)
			delay 0.5
		end try
	end repeat
	
	-- restrict max length of text
	if length of copied_Header > 100 then set copied_Header to text 1 thru 100 of copied_Header
	
	-- rename recieved file
	tell application "System Events" to set name of currentFile to copied_Header
	display alert "All done! Image has been renamed for you."
	
end adding folder items to

Now download or drag your file to HOT folder one by one.
NOTE: I don’t check how this handler works. If has errors, play with it to find problem solution yourself.

Thanks KniazidisR for your help. I will explore your code, and update you on my findings.

EDIT: I have tried your code and can’t make it work for me! However, I have made some progress, which I will post the code used in another post.

Updated code below works, after a fashion, with one small irritation.

The name is set along with the right colour label after the second Continue button is displayed, and selected. However, if using cached names the file name doubles-up.

For example, the name of the original file is ‘main stage.jpg’ and the cached name is 'Headliners on the - ’ which makes the new name ‘Headliners on the - main stage.jpg’.

However, as the new name is not set/saved until the second Continue button is used, the name displayed becomes ’ Headliners on the - Headliners on the - main stage.jpg’. I can delete the dup before continuing but would like to find a way to stop the duplications.



tell application "Finder"
	
	set currentName to name of theFile
	set the clipboard to «class ktxt» of ((the clipboard as text) as record) # remove styles from the clipboard
	set theCaption to the clipboard
	copy length of theCaption to theCaptionlength # test the length of theCaption
	if theCaptionlength > 100 then
		set theCaption to text 1 thru 100 of theCaption # respect the maximum filename-length of 255. Some characters obviously don't count so the limit is set low here
	else
		set theCaption to theCaption # do nothing
	end if
	
	
	display dialog "Add New Details to the current file?" buttons {"Continue", "Quit", "Clear Cache"} default button 3
	
	repeat
		
		if the button returned of the result is "Continue" then
			
			-- action for 1st button goes here
			(display dialog "Add New Details:" default answer theCaption & currentName buttons {"Cancel", "OK"})
			
			if button returned of (result) = "ok" then
				
				
				tell application "System Events" to set name of theFile to text returned of result
				
				# None = 0 | Orange = 1 | Red = 2 | Yellow = 3 | Blue = 4 | Purple = 5 | Green = 6 | Gray = 7
				set label index of theFile to 6
				
				
				
				
				display alert "All done! Image has been renamed  for you."
				
			else
				return
			end if
			return
			
		else if the button returned of the result is "Quit" then
			
			-- action for Quit 2nd Action button goes here
			
			display dialog ("Quit current application?" & return & "(" & theFile & ")") buttons {"Cancel", "OK"} default button 2
			
			
			if button returned of (result) = "ok" then
				
				--set currentName to name of theFile
				set label index of theFile to 4
				tell application "System Events" to quit
				
				return
			end if
			return
		else if the button returned of the result is "Clear Cache" then
			
			-- action for 3rd button goes here
			
			tell application "System Events" to set the clipboard to ""
			
			return input
			return
			
			
		end if
		return
	end repeat
end tell


THIS WORKS FINE FOR HOT FOLDER:


on adding folder items to this_folder after receiving added_items
	set currentFile to item 1 of added_items -- getting new added file to AppleScript
	-- open file in Preview
	tell application "Preview"
		activate
		open currentFile
	end tell
	
	do shell script "printf %s \"\" | pbcopy" -- clear clipboard
	
	tell me to activate
	display dialog "If YOU WANT RENAME PDF, THEN COPY ONE ARTICLE HEADER NOW!!!
	ELSE PRESS \"CANCEL\" BUTTON"
	tell application "Preview" to activate
	
	-- getting copied header to AppleScript
	set copied_Header to ""
	repeat while (copied_Header = "")
		try
			set copied_Header to (the clipboard as string)
			delay 0.5
		end try
	end repeat
	
	-- restrict max length of text
	if length of copied_Header > 100 then set copied_Header to text 1 thru 100 of copied_Header
	
	-- rename recieved file
	tell application "System Events" to set name of currentFile to (copied_Header & "." & (name extension of currentFile))
	display alert "All done! Image has been renamed for you."
	
end adding folder items to

NOW I WILL EXPLAIN YOU STEPS FOR:

  1. How to create HOT folder
  2. How to attack this actions handler to new HOT folder

So:
STEP 1): SAVE this script (as compiled script) at special directory of each MAC machine:
/Library/Workflows/Applications/Folder Actions
STEP 2): Create usual new folder and name it
STEP 3): Right Click on this folder, pop ups menu
STEP 4): Move mouse pointer to item “Services”, pop ups other menu
STEP 5): Click “Folder Actions Setup…”, pop ups “Confirm Service” dialog
STEP 6): Click “Run Service”, opens “Folder Actions Setup” dialog window
STEP 7): On left side of dialog window add your folder (with “+” button)
STEP 8): On right side of dialog window add saved handler script (with “+” button)
STEP 9): Close dialog. Just now you have created HOT folder!!! USE IT !!!

NOTE: You can rename file again and again, without exiting from action. You should select button “Cancel” to terminate loop. Loop is created because HOT folder see renamed file as new, other added file

Hi KniazidisR, my apology. I have not set a HOT folder before and have just learned something useful this morning.

I followed your instructions and the code you provided works, as you intended.

It doesn’t achieve my requirements at this stage. However, I believe from your original post you plan to work in stages through this request, as I am working with images that need to retain the original name, and will not always have cached data added.

Thank you for your patience with me and the step by step guide below, which helped. I now know what a HOT folder relates to.

  1. Why do you believe that this handler does not allow to you to keep for certain files its original names? You have only to choose “Cancel” in dialog box… when you add dragging or downloading that files to HOT folder for first time… If you need to keep both original name and new name, then you can set to new name only displayed name property of this file. Just replace code line:
tell application "System Events" to set name of currentFile to (copied_Header & "." & (name extension of currentFile))

with this:

tell application "System Events" to set displayed name of currentFile to (copied_Header & "." & (name extension of currentFile))
  1. “Cached data” and “clipboard data” are different things. Cached data is data, which system stores on hard disk, or at special cache memory of processor, and clipboard data is data, stored by system in RAM memory. It is always better not to confuse the terms so that others understand you correctly.

  2. Also, you can slightly change my display dialog choices to label files too.

  3. You have in your hands the flexibility that someone else’s application will never give you, and even let it be Hazel. You have AppleScript. You can fantasize a bunch of your own rules in your script handler. I would risk even saying this: ready-made solutions, even the most professional, have their limitations. And your fantasy is infinite. For example only, I could write such fast optimized code in hexadecimal numbers (using Macro Assembler. My God, how it was long ago…) that xCode would never give… And yes, in order for some application to take up space on my computer, it needs to work seriously. It should do better than me for something that I myself cannot.

I looked through the internet. People are so stupid with ready-made solutions with hot folders that they have already forgotten how to create a hot folder yourself. I’m sorry, but Hazel is… one of them.

Hi KniazidisR,

Thanks for responding. I am not a coder, just a guy trying to find a way to do something using AppleScript and hoping to learn a little along the way. I simply want to create a solution that will help with my challenge :expressionless:

We can take Hazel out of the equation and ignore the link from my very first post. If you are still willing to help me with your HOT folder version, can you code something to help me with my code objectives, which I have updated below?

Code Objectives [REVISED]:

1 - Manually change [add or delete new text via the keyboard] to the existing name of an IMAGE file, or add additional text [Manually] via copy and paste.

I’d like a dialog box to appear when an image file is sent to the HOT folder. I like the way you currently preview the image. I would also like buttons with Continue, Quit or Clear Clipboard upon receiving and image to process.

If selecting Continue, a dialog box should appear with the current image name. Here I can change the name details, On this screen I can accept ‘OK’ or I can Cancel. If I Cancel I am returned back to the top level menu - Continue, Quit or Clear Clipboard to run the process again. The current image name (the one that arrived into the folder) is re-presented to me to change. This is unlikely to be a frequent requirement. However, there could be instances where I need to start over on the same file and will want to ensure the original name is my start point.

For example an image named ’Main Stage IMG_1234.jpg’ is received in the HOT folder. Preview opens so we see can see it is the correct image to be processed.

The original file name is presented in a dialog box and now I can add or make changes to it. The only time the current name changes is if via manual input I make a change, and only after confirmation to complete the change has been presented and accepted will an image name change.

For the image named above I might choose to delete the text ‘Main’ and replace it with ’New 2019 Talent on’ making the new image name ’New 2019 Talent on Stage IMG_1234.jpg’ at this time if I select ‘OK’ the updated name is created and a new colour label is added to the file. I.e. Green

However, if I select Cancel before committing to the change the original name ‘Main Stage IMG_1234.jpg’ will persist and I be represented to me in the change name option dialog box re-appears.

If I select Quit. Upon confirming I wish to Quit a new colour label should be added to the image I.e. Blue and the process quits ready for the next image file.

Upon completing any confirmed change or if I confirm Quit, the Preview image screen should close for the current image.

2 - Clear Clipboard option - I have decided not to use the clipboard as an automated method for adding new details. However, I’d like to have an option to clear the clipboard if any text has been copied to it.

3 - Quit button - not the same as Cancel in a step. A confirmation screen should appear with Cancel or OK. If I select OK the file colour label should be changed to Blue and the process should then Quit. The Blue colour label will allow another process to remove the file from the HOT folder.

Quit is used when a file has been sent by mistake to the HOT folder. This should be a rare occurrence.

4 - Confirmation Screen(s). I’d like these before any changes are committed on any step. Also, I’d like to keep the confirmation banner you have for each process where it results in a final outcome or to confirm the clipboard cache has been reset.

Your code works in a way that I never intended. It is missing some key steps from my objectives, which I need for my automated workflow. I really like the code you have crafted because it is smart, fast, and works. However, I just need it to cover my core requirements and don’t know how to do this.

In your current code ‘Quit’ literally does just that, and if I copy text from the clipboard it overwrites all of the original name of the image file. I might hit Quit by mistake and so I need a Cancel / OK option presented to confirm the step. If Cancel is selected the process should repeat again until a new name is accepted or Quit is confirmed. Likewise with the clipboard. I would prefer an option to clear the clipboard cache and simply add (if needed) via copy and paste.

Part 2 of your first point above:

Using the code above I get no response from the HOT folder. if I remove the displayed element from the revised code it works.

With regards to cached data and clipboard data I get the point. For over 40 years now I have understood the difference and should have known not everyone works within context - sorry for the confusion.

I have already amended this label to say IMAGE and not PDF. I am not working with PDF files!

As far as I remember, we are not free to define the displayed name.

If the Finder is set to display names without extension, displayed name must match the full name minus its extension.
If the Finder is set to always display the extension, displayed name is identical to the full name.

When we ask System Events for the displayed name we may see an other feature at work.
If a file name defined in the Finder contains a slash ( not a good idea but Apple itself use that), System Events replaces the slash by a colon in the name while displayed name keeps the original slash (as well as the full path).

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 12 mai 2019 21:27:49

All right, but not all at once. To test and to debug script while building it, we will start it without creating a hot folder for now. Here are the first sketches, and now I have to go to work. We’ll continue tomorrow:


set added_items to (choose file of type {"public.image"} with multiple selections allowed)
set this_folder to path to desktop
adding folder items to this_folder after receiving added_items


on adding folder items to this_folder after receiving added_items
	set processedImages to 0
	repeat with theImage in added_items
		tell me to activate
		display dialog "Process with next image?" buttons {"YES", "QUIT APPLICATION"} default button "YES"
		if the button returned of the result is "QUIT APPLICATION" then
			quit_Application(theImage, processedImages)
			exit repeat
		end if
		tell application "Preview"
			activate
			open theImage
		end tell
		main_Handler(theImage)
		tell application "Preview"
			activate
			close front document saving no
		end tell
		set processedImages to processedImages + 1
	end repeat
	tell application "Preview" to quit
	display notification ("Application quits.
	Prosessed images:  " & (processedImages as string)) with title "My Image Processing Script" sound name "Frog"
end adding folder items to


on main_Handler(theImage)
	tell me to activate --bring display dialog to the front
	display dialog "Add New Details to the current file?" buttons {"Continue", "Quit", "Clear Clipboard"} default button "Clear Clipboard"
	if the button returned of the result is "Continue" then
		process_Image(theImage)
	else if the button returned of the result is "Clear Clipboard" then
		clear_Clipboard()
		my main_Handler(theImage)
	else
		quit_ProcessingImage(theImage)
	end if
end main_Handler


on clear_Clipboard()
	do shell script "pbcopy < /dev/null"
	display notification "Clipboard is cleaned" with title "My Image Processing Script" sound name "Frog"
end clear_Clipboard


on quit_ProcessingImage(theImage)
	tell application "Finder" to set label index of theImage to 4
	display notification "The image is labeled blue" with title "My Image Processing Script" sound name "Frog"
end quit_ProcessingImage


on process_Image(theImage)
	tell application "Finder"
		set originalName to name of theImage
		display dialog "Add New Details:" default answer originalName buttons {"Cancel", "OK"}
		if button returned of result = "OK" then
			set name of theImage to the text returned of result
			set label index of theImage to 6
		end if
	end tell
	display notification "All done! Image has been renamed for you." with title "My Image Processing Script" sound name "Frog"
end process_Image


on quit_Application(theImage, processedImages)
	tell application "Preview" to quit
	display notification ("Application quits.
	Prosessed images:  " & (processedImages as string)) with title "My Image Processing Script" sound name "Frog"
end quit_Application

Okay, it seems now the script is working correctly. It seems… If you find a mistake, feel free to show me. Now you can remove the first 3 lines of code, save script at needed directory, create a hot folder and attach a script to it (as I describe above). Or… you can use it as is, without creating HOT folder.

NOTE: I added batch processing future for you. (You can now drag to HOT folder multiply images at once and process all of them). Or… you can choose multiply images in usual folder and process all of them… without creating HOT folder

Hi KniazidisR,

Thank you for your help.

I am away from home on business until the weekend. I will test when back, and let you know if I find anything.

UPDATED 17 - May - 2019:

This works exactly as needed. Thank you very much for your time.