How to know if the file is open?

How can I find out with calc macro which files are currently open? is a specific file currently open? LO 6.3.6.2, Windows 10.

python code

def main():
    desktop = XSCRIPTCONTEXT.getDesktop()
    #dictionary of current open document with key=URL
    open_docs = { doc.URL: doc for doc in desktop.Components }
    my_url = 'file:///home/pi/Documents/example.ods'
    # doc is taken from open_docs if available else open…fromURL
    doc = open_docs.get(my_url, desktop.loadComponentFromURL(my_url,"_blanc", 0, (),))
    print(doc.Title)
    #to do: catch AttributeErrors for Components without URLs(eg.Dialogs …)
    # catch non existing File-URLS   

Thanks, but, sorry, could you translate it to LO Basic ?

Sorry for disturbance, I found solution

function fnIsFileOpen(sFileName$) as boolean
dim oComponents as object, oEnum as object, oComp as object
dim s$
fnIsFileOpen = false
oComponents = StarDesktop.Components
oEnum = oComponents.CreateEnumeration
Do While oEnum.HasMoreElements
oComp = oEnum.NextElement
s = oComp.Title
if oComp.Title = sFileName then
fnIsFileOpen = true
exit function
end if
Loop

End function

Is this OK ?

Sorry for nitpicking… its not ok…

It compares only the Filename not the full-qualified-URL. Imagine youre have:

C:\…\Downloads\documentname.ods
and
D:\…\Backup\dokumentname.ods

open at same time…??

Thank you very much, I will take it into account.

One of the possibilities.

' Is LO component open?
' - filePath File path. Can be specified in Native OS or URL format.
Function IsFileOpen(Byval filePath As String) as Boolean
 Dim oComp
 IsFileOpen = false
 filePath=ConvertToUrl(filePath)
 For Each oComp In StarDesktop.Components
   If HasUnoInterfaces(oComp, "com.sun.star.frame.XModel") Then  ' component which has URL
     If oComp.Url=filePath Then
       IsFileOpen=True
       Exit Function
     End If  
   End If
 Next oComp
End Function
2 Likes

Accepted with gratitude