Editing Finder Comments

I am having some trouble doing this, so I have to ask - is it permissible to modify Finder Comments for files from an App Store app, written in xCode?


If so, is it best to try and do it with SwiftUI or execute an Apple Script?


All of the Swift I have tried does not seem to actually save the Comment to be able to retrieve it in Finder.


Edit: my goal is to be able to search for files with Finder/Spotlight and have them show up based off of this metadata that I want to add - if you have another suggested way of doing this, I am all ears.


TIA!

Mac mini

Posted on Apr 10, 2024 12:50 PM

Reply
Question marked as Top-ranking reply

Posted on Apr 13, 2024 12:31 PM

Jay in Detroit wrote:

I like your suggestion, but I really want to know how to do this. I know it is possible because Metamer does it and now I need to know what the secret is.


What was linked earlier discusses the two types of comments, and which of the two to use for most applications. And particularly which to use, given the mess around .DS_Store. Use com.apple.metadata:kMDItemComment, not com.apple.metadata:kMDItemFinderComment. Put differently, your Swift code seems to have fallen directly into the .DS_Store problem that the article warned about.


AppleScript is useful for scripting GUI apps and when no alternatives or APIs exist, but too often tends show its limits for other uses.

18 replies
Question marked as Top-ranking reply

Apr 13, 2024 12:31 PM in response to Jay in Detroit

Jay in Detroit wrote:

I like your suggestion, but I really want to know how to do this. I know it is possible because Metamer does it and now I need to know what the secret is.


What was linked earlier discusses the two types of comments, and which of the two to use for most applications. And particularly which to use, given the mess around .DS_Store. Use com.apple.metadata:kMDItemComment, not com.apple.metadata:kMDItemFinderComment. Put differently, your Swift code seems to have fallen directly into the .DS_Store problem that the article warned about.


AppleScript is useful for scripting GUI apps and when no alternatives or APIs exist, but too often tends show its limits for other uses.

Apr 11, 2024 5:48 PM in response to MrHoffman

The files are mostly png files, which don't have much metadata support natively, but even so, the metadata is not indexed by Finder/Spotlight so wouldn't work for me for this anyway.


Specifically, I am looking to add OCR text from my images into the comment field so that they are searchable. I have tried the methods in the links mentioned, and more.


I don't love the AppleScript method from xCode so am trying to do it "natively." I have gotten half way there with this:

func saveFinderComment(fileURL: URL, comment: String) -> Bool {
        do {
            let plistData = try PropertyListSerialization.data(fromPropertyList: comment, format: .binary, options: 0)
            try fileURL.setExtendedAttribute(data: plistData, forName: "com.apple.metadata:kMDItemFinderComment")
        } catch {
            print("Error saving Finder comment: \(error)")
            return false
        }
        return true
    }
extension URL {

    /// Get extended attribute.
    func extendedAttribute(forName name: String) throws -> Data  {

        let data = try self.withUnsafeFileSystemRepresentation { fileSystemPath -> Data in

            // Determine attribute size:
            let length = getxattr(fileSystemPath, name, nil, 0, 0, 0)
            guard length >= 0 else { throw URL.posixError(errno) }

            // Create buffer with required size:
            var data = Data(count: length)

            // Retrieve attribute:
            let result =  data.withUnsafeMutableBytes { [count = data.count] in
                getxattr(fileSystemPath, name, $0.baseAddress, count, 0, 0)
            }
            guard result >= 0 else { throw URL.posixError(errno) }
            return data
        }
        return data
    }

    /// Set extended attribute.
    func setExtendedAttribute(data: Data, forName name: String) throws {

        try self.withUnsafeFileSystemRepresentation { fileSystemPath in
            let result = data.withUnsafeBytes {
                setxattr(fileSystemPath, name, $0.baseAddress, data.count, 0, 0)
            }
            guard result >= 0 else { throw URL.posixError(errno) }
        }
    }

    /// Remove extended attribute.
    func removeExtendedAttribute(forName name: String) throws {

        try self.withUnsafeFileSystemRepresentation { fileSystemPath in
            let result = removexattr(fileSystemPath, name, 0)
            guard result >= 0 else { throw URL.posixError(errno) }
        }
    }

    /// Get list of all extended attributes.
    func listExtendedAttributes() throws -> [String] {

        let list = try self.withUnsafeFileSystemRepresentation { fileSystemPath -> [String] in
            let length = listxattr(fileSystemPath, nil, 0, 0)
            guard length >= 0 else { throw URL.posixError(errno) }

            // Create buffer with required size:
            var namebuf = Array<CChar>(repeating: 0, count: length)

            // Retrieve attribute list:
            let result = listxattr(fileSystemPath, &namebuf, namebuf.count, 0)
            guard result >= 0 else { throw URL.posixError(errno) }

            // Extract attribute names:
            let list = namebuf.split(separator: 0).compactMap {
                $0.withUnsafeBufferPointer {
                    $0.withMemoryRebound(to: UInt8.self) {
                        String(bytes: $0, encoding: .utf8)
                    }
                }
            }
            return list
        }
        return list
    }

    /// Helper function to create an NSError from a Unix errno.
    private static func posixError(_ err: Int32) -> NSError {
        return NSError(domain: NSPOSIXErrorDomain, code: Int(err),
                       userInfo: [NSLocalizedDescriptionKey: String(cString: strerror(err))])
    }
}

It sets the extended attribute but not the .ds_store part. The data does become searchable, but I don't want to cut the corner - yet. Still working on it.


I am not the best developer, still learning.


Thank you MrHoffman, VikingOSX, and etresoft for your help - you have given me the hope to keep trying.

Apr 10, 2024 1:33 PM in response to Jay in Detroit

The two sorts of comments are constructs of Finder. One with some issues, so choose wisely.


For background: https://eclecticlight.co/2020/11/06/finder-comments-worth-avoiding/


The Metamer and xattred tools mentioned in that writeup are available here:


https://eclecticlight.co/free-software-menu/


Xcode is seemingly unrelated, as is SwiftUI, as you’re unlikely building or rebuilding any apps from the app store.


Or maybe you’re considering building your own version of Metamer, xattred, or the xattr command?

Apr 10, 2024 2:37 PM in response to Jay in Detroit

Jay in Detroit wrote:

is it permissible to modify Finder Comments for files from an App Store app, written in xCode?

Perhaps.

If so, is it best to try and do it with SwiftUI or execute an Apple Script?

I don't know if AppleScript can do it. AppleScript does what it does. If it can do it, then it does. If not, then no. SwiftUI is something different. Technically I suppose it would be no different than anything else, but it's just something different.

All of the Swift I have tried does not seem to actually save the Comment to be able to retrieve it in Finder.

What Swift have you tried?

Edit: my goal is to be able to search for files with Finder/Spotlight and have them show up based off of this metadata that I want to add - if you have another suggested way of doing this, I am all ears.

Comments appear to be searchable if you manually add that as a criteria. I'm not sure that is the best approach. It sounds like you are trying to cobble together some custom indexing scheme using Finder metadata. From an information management perspective, that's probably going to be a poor solution.


Here's a good example, when I went to try this search, I added a unique comment to a known file. Then I tried to search for it. At first, I couldn't find it. That's was simply because I had misspelled it. That's a typical problem when people try to invent their own indexing schemes. You could at least eliminate the chances of misspellings by building a front end. SwiftUI would help with that, but then it would hinder the lower-level work to actually make the change to the file system. They ain't kidding about the "UI" part. It's a react-style architecture that would be tricky to use with the Spotlight API.


It would be best to explain a little more about the project. It sounds like something that is really tricky to do because it sits right between consumer-level and professional levels apps. Microsoft Access is great for these kinds of things, but there is no Mac version of Access.

Apr 10, 2024 3:33 PM in response to Jay in Detroit

Jay in Detroit wrote:

Good points - I am familiar with the issues and the tools - I am looking to do part of what they do - add Finder Comments for files that I would like users to be able to search for using Finder or Spotlight given this metadata that I would like to add.


What sorts of files? Some have integrated metadata support, such as most image and video formats.

Apr 11, 2024 6:01 PM in response to Jay in Detroit

PNG supports an eXIf extension.


If i were perversely minded, I’d also see if a zip containing the necessary data could be appended onto the PNG without disrupting the other uses of the PNG; operating as a polyglot configuration. A zip can be pulled off the end with minimal issues and some chatter about extra bytes at the front, as this is how self-extracting zip archives work.


And recent Apple platforms already automatically OCR and index images at least in Photos, too.

Apr 11, 2024 7:44 PM in response to MrHoffman

And recent Apple platforms already automatically OCR and index images at least in Photos, too.

If you take a screenshot of this comment, are you able to search for it in Finder? Here is some unique text to search: asdfjkl


It does not work on any of my Macs - is this just me?


etresoft: Interesting concept to put it in a PDF. I may look into this, but it isn't as elegant as just having images searchable in their native format

Apr 13, 2024 9:17 AM in response to Jay in Detroit

One of the side effects of using the Vision frameworks to extract text from images is that if the text is nicely formatted in the image, line feeds will be replaced with a space and your captured text will be one long string of concatenated text.


For instance, I have a JPG that contains the following:



but what is captured to text ( an actual result from VNImageRequestHandler results for this image):


"66There is nothing wrong with your television set. Do not attempt to adjust thepicture. We are controlling transmission. If we wish to make it louder, we willbring up the volume. If we wish to make it softer, we will tune it to a whisper.We will control the horizontal. We will control the vertical. We can roll theimage, make it flutter. We can change the focus to a soft blur or sharpen it tocrystal clarity. For the next hour, sit quietly and we will control all that you seeand hear. We repeat: there is nothing wrong with your television set. You areabout to participate in a great adventure. You are about to experience theawe and mystery which reaches from the inner mind to - The Outer Limits.99"



It even attempts to convert the stylish quotes as number representations. The image file's comment box will wrap the resulting captured text which is the only blessing here.



Apr 13, 2024 2:28 PM in response to Jay in Detroit

One thing at a time… 😉 I just converted an AppleScript/Objective-C app that did the image text scaping to pure Swift today. That was enough milestone for my Saturday. Time permitting, I may eventually add additional functionality to write the captured text back to the image's comment.


As far as I know, the .DS_Store file is Finder's black box enigma and I have no motivation to manipulate it, if that is even possible. I have found in practice that manually adding a comment to a file's Finder Get Info panel is sufficient to allow Spotlight to automatically index and allow one to access unique wording in that comment.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Editing Finder Comments

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.