3

Is it possible to check if a file or bundle is opened by any Application? For example, lets say that I know that /Users/Foo/AwesomeDocument.txt exists and its open in TextEdit, can I reliable check from my app that the document is open? I'm okay with solutions that only work with documents opened via NSDocumentController.

JustSid
  • 25,168
  • 7
  • 79
  • 97

4 Answers4

2

You could use an NSTask to run the shell command lsof | grep "Document.txt" and then parse the results, though that method is kind of slow. I don't know of a native Cocoa way to achieve this.

Francis McGrew
  • 7,264
  • 1
  • 33
  • 30
  • Sadly this doesn't work with files that are opened via `NSDocumentController` since it doesn't have the file handle open the whole time. – JustSid Nov 04 '11 at 15:00
1

Do you mean like this?

For example, in Applescript:

tell application "TextEdit"
    set theDocument to document of window 1
    return theDocument
end tell
gadgetmo
  • 3,058
  • 8
  • 27
  • 41
  • Not exactly, I want to check wether a known file is open, not what is currently open in TextEdit (so the reverse version of this would be awesome). It should also work across spaces =/ – JustSid Nov 19 '11 at 15:57
1
tell application "TextEdit"
    set theDocuments to every document
    repeat with aDocument in theDocuments
        if (path of aDocument) as string is equal to "/test.txt" then
            display dialog "found"
        end if
    end repeat
end tell
Yannick
  • 535
  • 4
  • 18
  • Sorry, but I still need it the other way around. Asking every app if the document is open is a bit of an overhead I don't really want, I would rather just use the path and know if the file is open somewhere. – JustSid Nov 23 '11 at 09:58
0

Starting from 10.7 you may want to try something with NSFileCoordinator. Bare in mind thath not every app is bound to have NSFilePresenter implemented and go the way with NSDocument.

mahal tertin
  • 3,239
  • 24
  • 41