Arranging Icons in Finder Icon View

I have a situation where I would love to be able to automate the positioning of icons in a Finder window. I imagine that the same thing might be used on the Desktop, but that's a bonus, not my immediate requirement.

Are there any mechanisms, in KBM or AppleScript or ?? to do things like:

  • Select a file or folder icon and get its position within the window (or on the desktop).
  • Position an icon to a specific position (e.g., saved from the previous, etc.).
  • Iterate through all the icons in spatial order, without knowing how that was set (sort by modification, access, creation dates, name, manually, etc.). This could require running "Clean up" first to get icons onto the grid, keeping Snap to Grid on, etc.

I've started playing with grouping file icons two-dimensionally as part of my organizing and I would like to be able to save an arrangement and reset it. I'd also like, I think, to be able to determine my own "sort order" other than the canned sorts that the OS provides.

I imagine that if I could somehow iterate through them all in spatial order, then I could "touch" them or something that would allow me to restore that arrangement using a canned "Sort by access time" or something, but it wouldn't help the real issue of being able to visually arrange them in a way that I cannot generate by naming or sorting. It also doesn't help me automatically move an icon from one place in the Finder to another based on a change of status of some other kind.

Any ideas?

The following scripts work for items on the Desktop:

  • Select a file or folder icon and get its position within the window (or on the desktop).
tell application "Finder"
    set folderItem to item (POSIX file "<PATH>") as alias
    get desktop position of folderItem
end tell
tell application "Finder"
	set folderItem to item (POSIX file "<PATH>") as alias
	set desktop position of folderItem to {100, 100}
end tell
tell application "Finder"
    set desktopItems to every item of desktop
    set itemList to {}
    repeat with anItem in desktopItems
        set itemName to name of anItem
        set itemPos to get desktop position of anItem
        set end of itemList to {itemName, itemPos}
    end repeat
end tell

on isCloseEnough(y1, y2)
    return (y1 - y2 ≤ 25 and y1 - y2 ≥ -25)
end isCloseEnough

on sortList(theList)
    set theSortedList to theList
    set itemCount to count of theSortedList
    repeat with i from 1 to itemCount
        repeat with j from i + 1 to itemCount
            set item_i to item i of theSortedList
            set item_j to item j of theSortedList
            set pos_i to item 2 of item_i
            set pos_j to item 2 of item_j
            if (isCloseEnough((item 2 of pos_i), (item 2 of pos_j)) and (item 1 of pos_i > item 1 of pos_j)) or ((item 2 of pos_i) > (item 2 of pos_j)) then
                set item i of theSortedList to item_j
                set item j of theSortedList to item_i
            end if
        end repeat
    end repeat
    return theSortedList
end sortList

set sortedList to sortList(itemList)

set output to ""
repeat with anItem in sortedList
    set output to output & (item 1 of anItem) & ": " & (item 2 of anItem) & linefeed
end repeat

return output

1 Like

WOW! Thanks!

There's a lot there to understand and try out.

I was initially brainstorming on what info I would need to manage icons in a folder the way I was imagining that I might want to. I haven't gotten practical yet. Looks like that's the next step.

When I have an individual item selected during the iteration, can I then find out if it is, for instance, a TextEdit item, and if so, then examine the text to see if there are any specifically formatted To-Do items in it and collect those into another file?

Another thing I've been imagining is something like this: previously embedding a sequence number (specifically formatted in XML key format or something) into the text (I really don't want it in the filename), then when iterating through all the icons extracting the number from each file, and then using that sequence to reposition all the icons. It looks like the macros above handle the repositioning, which I wasn't sure how to do, so this is getting me started.

As I said, this is all imagination and brainstorming and will likely change once I actually try using it.

Again, thanks!

Positional analysis and control is a novel approach to folder analysis! Personally, I use a combination of Hazel, Smart Folders and Tags for this sort of thing, but I'm interested to see where you're heading with it.

Do you mean during the AppleScript that lists the desktop items by position? This seems like it could get awfully complex, and there are many simpler ways to keep track of files and folders. But then, I don't know what your ultimate vision is for it yet.

Have you considered using Tags or Comments? They're searchable in the Finder and can also be accessed by KM as file attributes. You could do something as simple as adding the intended coordinates for an item to its comments field and then position it there using Keyboard Maestro.

CleanShot 2023-09-23 at 00.19.12@2x

Position Files by Comment Coords.kmmacros (24 KB)

Macro screenshot

This will position all desktop items by the coordinates stored in their comments attribute in the format shown above (if any exist).

1 Like

Awesome idea!

Tags is too unwieldy because the same tags will be displayed as tagging possibilities for all files or folders as well as for items in various apps that all access the same Tags list, and that's just over the top clutter. Comments looks perfect.

Meta data like the display position doesn't belong in the filename and doesn't belong in the file text content either. In fact, I shouldn't really have to even see it unless I need it. In that sense it's at the same level as a file mod date or owner. I don't know if this was the intended use of Comments (I haven't found a use so far) but at least conceptually this is perfect.

And Yet Another Macro to try out. I'm not keeping up ... :wink:

Thanks, for both the idea and for the sample macro!

1 Like

Have you tried them on items in a folder? I'll get to it eventually (I'm still working on a test macro to invoke the first "get position" script), but not a lot time for that right now. Do you have any ideas about what it might take to make that transition?

Haven't managed that part yet. Had a go but hit a wall. I have an idea of how it might work but it's a quite a bit more difficult than the desktop.

I'm really interesting in understanding how you compose these scripts. Years of practice and an intuitive understanding of how AppleScript sees things, a comprehensive reference on a par with the KBM User Manual, or that's what ChatGPT suggested and it seems to work?

E.g., in the very first simple script, why do you need a POSIX path alias to get the position values? I would never have thought of that route to getting those values.

Foo. What seems to be the issue? (Not that I can probably help much.)

Unfortunately, a folder is what I need for what I'm working on.

I suppose, since I'm programmatically repositioning things, that I could take all the icons I need (currently over 25, I would like to be able to scale to 45 or 50 to have some headroom) and keep them at the left side of the Desktop while the usual Desktop clutter that I haven't dealt with yet stay at the right.

But would that organization get clobbered every time some random app decides that the appropriate place to save something is my Desktop (e.g., screen captures)? That's why I wanted this organization walled off in its own folder.

I am trying to test this script:

by running it from a KBM macro so that I can select an item and then trigger the macro with a hotkey.

Is there a better way to test it?

Here's my KBM macro:

And here's what I get when I select an icon on the Desktop and then press ⇧F1:

What am I missing? I'm on Catalina, if that makes a difference, running the latest KBM.

I just figured out the logic in my head and then prompt GPT very carefully and deliberately. Often, I'll prompt one basic step at a time rather than ask for too much at once. Honestly, I think the only thing I bring to things is the logic. All the scripting is GPT. Anyone who can clearly articulate what they want and can logically deduce what might be going wrong can do it. I know just enough about the scripting side to read through and (hopefully) understand when it's not quite what I asked for, or I prompted with an insufficient level of granular specificity. Although it must be said that GPT can sometimes surprise you and spit out a perfect result first time in response to a fairly casual natural language request. It's a revolution for automation in my view.

The Desktop dimensions are static; a window's aren't so some compensatory calculations may be necessary. Or maybe that idea won't work at all...

I used to use iCollections for this.

Well you need to replace <PATH>, which is just a placeholder, with an actual path, presumably using a variable.

It's late here so I'm off to bed but happy to help you set this up properly tomorrow. :zzz:

I gather from your concern that the positions of the icons inside a Finder window are actually screen positions, so they change if the window is moved.

For my purposes, it would work to set the Finder window to a specific size and position as part of the process of reorganizing the icons. If, when that is complete, I, the user, wants to move or resize the window, that wouldn't affect anything. Time to reorganize? Then the window gets resized and moved to its "standard" position first, then the icons get moved.

I do not need rearranging the icons to be fluid, ongoing, real time at all.

On further investigation, I don't think positioning items in a Finder window is even theoretically possible. The reason it works with the desktop is because we can use the desktop position property, which of course isn't available in a window.

Did you check out iCollections? I think it might be a better solution for you, although it won't solve your window issue.

Have you tried Hazel for monitoring folders instead? Seems like it might be of use in this instance.

I tried going to ChatGPT about the folder view vs the Desktop icons.

In a thread that already had lots of questions about AppleScript, I asked:

When I have a single icon selected, can I get AppleScript to retrieve the coordinates of the location of the icon in the Finder window?

And ChatGPT replied:

Unfortunately, AppleScript does not provide a straightforward way to directly retrieve the coordinates of a selected icon's location within a Finder window. AppleScript's capabilities for interacting with the Finder are somewhat limited in this regard.

However, if you have a specific use case where you need to determine the coordinates of icons within the Finder window, you might consider using other scripting or automation tools that can capture screen coordinates. For example, you could use a tool like Keyboard Maestro, which allows you to automate various tasks on your Mac, including capturing screen coordinates and performing actions based on them.

With Keyboard Maestro, you can create macros that trigger when you press a hotkey, and these macros can include actions to capture mouse coordinates or interact with specific UI elements on the screen, such as the icons in a Finder window. You can then use AppleScript within Keyboard Maestro to perform actions based on the captured coordinates.

Keep in mind that capturing screen coordinates may involve more advanced scripting and automation techniques, and it can be sensitive to changes in your system's resolution or the arrangement of icons in the Finder window.

So ChatGPT can't figure out how to do it and is punting to Keyboard Maestro. I find that amusing.

1 Like

I just found this, which apparently works for Finder windows:

However, I don't trust ChatGPT to have anything like the final word.

<rant> A few days ago I asked ChatGPT for help in how to script opening a TextEdit file with preset parameters. I asked:

What properties do I use, and how do I use them, to create a new TextEdit document with a blue background on the entire page and white text, with a size 600px wide and 300px high?

And what I got was:

To create a new TextEdit document with specific properties like a blue background, white text, and a specific size, you can use the following AppleScript:

tell application "TextEdit"
    set newDoc to make new document with properties {text:"", background color:{0, 0, 65535}, color:{65535, 65535, 65535}, width:600, height:300}
end tell

This script tells the TextEdit application to create a new document with the specified properties. Here's what each property does:

  • text: The initial text content of the document (empty in this case).
  • background color: Sets the background color to blue (RGB values: {0, 0, 65535}).
  • color: Sets the text color to white (RGB values: {65535, 65535, 65535}).
  • width and height: Set the dimensions of the document to 600 pixels wide and 300 pixels high.

You can adjust the RGB values and size to customize the appearance and dimensions of your new TextEdit document as needed.

That's a very nice answer, with a lovely, detailed explanation, and it's totally erroneous. It doesn't work. There is NO background color parameter and separate width and height parameters are not the way to set the window size, you have to use the size property instead which is a list of two values.

After five round trips of my reporting the error messages that I got and it tyring a slightly different script, it suggested changing background color to document color which didn't work either. Then it suggested trying page color. It was guessing in the dark no better than I could. Finally it admitted:

It seems that TextEdit does not provide direct AppleScript support for setting the page background color. You can set text style attributes such as font, size, and color for text, but not the overall page background color.

To set the page background color, you may need to resort to automating GUI interactions, which can be more complex. This involves using tools like System Events to simulate user actions, which is less straightforward than direct AppleScript commands.

If setting the page background color is crucial for your workflow, you might want to consider using a more scriptable text editor that provides better automation support for this specific task.

This is far from the first time that I have watched ChatGPT make guesses in the dark that all seemed reasonable, when the issue was that the task could not be done in the direction that it was trying to go.

For more of it's hand-waving appearance of expertise where there is little, I notice that for simulating user GUI interactions to get the page background color, it does not mention KBM, while for positioning icons it seems to think that KBM can do magic.</rant>

So please forgive me if I am mistrustful of ChatGPT's advice.


Looks like it works on my hardware and OS too. I'll try contacting the developer to ask how it works for Folders and to suggest being able to parametrically reposition icons instead of only saving and restoring.

Regarding GPT's propensity for confidently talking rubbish...

  1. Try Bing Chat or Chat GPT 4.

  2. If it does talk nonsense, try a new chat and you'll usually get a different answer.

It's not there yet for AS, as it's so app-dependent, but trust me when I say it's a game changer for shell scripts and html.

1 Like

That's what I'm hearing, from you and others. I suspect that there is a much, much larger volume of material, both source and discussion, for Shell and HTML than there is for AppleScript. It is pretty good with Regular Expressions, which can be hugely helpful when that's what you need, again probably because of the volume of material.

But any time you veer off the beaten path, as I tend to do, seeing what fringe situations I can exploit to do what I want to do and not be limited to the narrow vision of what the original engineers conceived, AI starts guessing. And it provides guesses with the same authoritative tone as things that work.

That's because it has no inherent understanding, no internal model of how Apple Script works, that it is drawing upon. It just puts out things that are syntactically correct, even if there is no semantics behind it. It's doing exactly the same thing with the English it puts out as it is doing with AppleScript. It looks and sounds right because it fits the patterns of what English or AppleScript look like. So it's non-specific suggestions are well worded because it has lots of instances of such suggestions to draw upon. That makes it sound like it knows what it's talking about, like it has the voice of experience. But it's really parroting other experienced voices and if there hasn't been a lot of discussion of exactly what it is that you are trying to do or talk about, you won't get a lot of real meaning out of it, just approximations that may or may not have anything to do with what you're really asking.

I'm glad it's working for you, and I would love to see some transcripts of your interactions because it sounds like you are learning how to compose better, more specific prompts than what I have been doing.

Maybe I can learn some patience. I know that I'm triggered by the authoritative tone that is flat out wrong. My Father used to speak with authority about things he knew little about and it was a huge sense of betrayal to me as a little kid when I discovered that he was like the Wizard of Oz. I didn't learn to see where that came from in his own life until after he was gone.

Thanks for all you efforts and brainstorming with me.

My opinion is simply that GPT can't contend with the interplay between scripting languages and applications. I've had much more success with AppleScripts that do, for example, self-contained tasks like text alteration or iterative calculations with various rules.

I've got a few macros that do a bit of the boring repetitive prompting for me. Nothing you're not already doing, I'm sure. The most involved thing I have is a macro that pastes long scripts in chunks with whole-line rounding. More than anything, I'm patient and diligent, mostly because I'm still in the honeymoon phase where it's thrilling to get a result that works; one I'd never achieve without AI help.

PS: Sorry to hear about your dad passing away without the resolution you would have found helpful in that relationship. My mother-in-law passed in December and it's brought my relationship with my own folks into focus somewhat. I'm very grateful to have both of them and I need to spend more time with them.