“Name these stencil shapes” AppleScript

Attached script is far from perfect, but helped a customer earlier this week, so figured I’d post it here in case it helps someone else down the line. :-)

The customer had created a stencil document that contained 200+ shapes, but had not supplied names to them in the Object Data inspector pane as they went. Script attempts to make the process of filling them in after the fact a little easier than doing it completely by hand.

Intended workflow: with the stencil open in edit mode, select the shapes you want to name, then press play on the script. It will walk through each shape and present a text input box. Enter the desired name, then hit Return or click OK. (If the shape already has a name, it will appear in the box; just hit Return to keep it.) When the walk through the shapes is complete, the original selection should be restored.

tell application "OmniGraffle"
	-- possibly unnecessary, but helps when running in Script Editor if nothing else?
	tell front window
		activate
	end tell
	
	set selectedGraphics to selection of the front window as list
	if length of selectedGraphics is 0 then
		display alert "No shapes selected." message "Please select the shapes you want to name, then run this script again." buttons {"OK"} default button 1
		return
	end if
	
	set oldSelectedGraphics to selectedGraphics
	
	-- loop through the selected shapes, getting user input and setting each shape's name.
	repeat with anObject in selectedGraphics
		
		-- OG to user: which shape?
		set selection of the front window to anObject as list
		
		-- without the delay, the screen won't redraw to update the changed selection
		delay 1.5
		
		-- user supplies input
		display dialog "What name should appear on the stencil for the shape that's currently selected?" default answer (user name of anObject as text)
		set newName to text returned of result
		
		-- and then we apply it.
		set user name of anObject to newName
	end repeat
	
	-- restore the original selection as we finish
	set selection of the front window to oldSelectedGraphics
end tell