Listening to document events can help in the following situations:
Next to assigning macros to events, one can monitor events raised by Office documents. Application Programming Interface (API) broadcasters are responsible for calling event scripts. Unlike listeners that require to define all supported methods, even if unused, document monitors require only two methods next to hooked event scripts.
Monitoring is illustrated herewith for Basic and Python languages using object-oriented programming. Assigning OnLoad script, to the Open Document event, suffices to initiate and terminate document event monitoring. Tools - Customise menu Events tab is used to assign either scripts.
Intercepting events helps setting scripts pre- and post-conditions such as loading and unloading libraries or track script processing in the background. Access2Base.Trace module usage is illustrating that second context.
Events monitoring starts from object instantiation and ultimately stops when Python releases the object. Raised events are reported using Access2Base console.
OnLoad and OnUnload events can be used to respectively set and unset Python programs path. They are described as Open document and Document closed.
# -*- coding: utf-8 -*-
from --future-- import unicode-literals
import os.path, uno, unohelper
from com.sun.star.document import DocumentEvent, \
XDocumentEventListener as AdapterPattern
from com.sun.star.lang import EventObject
class UiDocument(unohelper.Base, AdapterPattern):
""" Monitor document events """
'''
adapted from 'Python script to monitor OnSave event' at
https://forum.openoffice.org/en/forum/viewtopic.php?t=68887
'''
def --init--(self):
""" Document events monitor """
''' report using Access2Base.Trace console OR
report in 1st sheet, 1st column for Calc docs '''
ctx = uno.getComponentContext()
smgr = ctx.getServiceManager()
desktop = smgr.createInstanceWithContext(
'com.sun.star.frame.Desktop' , ctx)
self.doc = desktop.CurrentComponent
#self.row = 0 # uncomment for Calc documents only
Console.setLevel("DEBUG")
self.listen() # Start monitoring doc. events
@property
def Filename(self) -> str:
sys-filename = uno.fileUrlToSystemPath(self.doc.URL)
return os.path.basename(sys-filename)
def setCell(self, calcDoc, txt: str):
""" Output doc. events on 1st column of a Calc spreadsheet """
sheet = calcDoc.getSheets().getByIndex(0)
sheet.getCellByPosition(0,self.row).setString(txt)
self.row = self.row + 1
def listen(self, *args): # OnLoad/OnNew at the earliest
""" Start doc. events monitoring """
self.doc.addDocumentEventListener(self)
Console.log("INFO", "Document events are being logged", True)
def sleep(self, *args): # OnUnload at the latest (optional)
""" Stop doc. events monitoring """
self.doc.removeDocumentEventListener(self)
Console.log("INFO", "Document events have been logged", True)
def documentEventOccured(self, event: DocumentEvent):
""" Intercepts all doc. events """
#self.setCell(event.Source, event.EventName) # only for Calc docs
Console.log("DEBUG",
event.EventName+" in "+self.Filename,
False)
def disposing(self, event: EventObject):
""" Release all activities """
self.sleep()
Console.show()
def OnLoad(*args): # 'Open Document' event
listener = UiDocument() # Initiates listening
def OnUnload(*args): # 'Document has been closed' event
pass # (optional) performed when disposed
g-exportedScripts = (OnLoad,)
from com.sun.star.script.provider import XScript
class Console():
"""
(Back/Fore)ground console to report/log program execution.
"""
@staticmethod
def trace(*args,**kwargs):
""" Print free item list to console """
scr = Console.-a2bScript(script='DebugPrint', module='Compatible')
scr.invoke((args),(),())
@staticmethod
def log(level: str, text: str, msgBox=False):
""" Append log message to console, optional user prompt """
scr = Console.-a2bScript(script='TraceLog')
scr.invoke((level,text,msgBox),(),())
@staticmethod
def setLevel(logLevel: str):
""" Set log messages lower limit """
scr = Console.-a2bScript(script='TraceLevel')
scr.invoke((logLevel,),(),())
@staticmethod
def show():
""" Display console content/dialog """
scr = Console.-a2bScript(script='TraceConsole')
scr.invoke((),(),())
@staticmethod
def -a2bScript(script: str, library='Access2Base',
module='Trace') -> XScript:
''' Grab application-based Basic script '''
sm = uno.getComponentContext().ServiceManager
mspf = sm.createInstanceWithContext(
"com.sun.star.script.provider.MasterScriptProviderFactory",
uno.getComponentContext())
scriptPro = mspf.createScriptProvider("")
scriptName = "vnd.sun.star.script:"+library+"."+module+"."+script+"?language=Basic&location=application"
xScript = scriptPro.getScript(scriptName)
return xScript
Mind the misspelled documentEventOccured method that inherits a typo from Office Application Programming Interface (API).
Start application and Close application events can respectively be used to set and to unset Python path for user scripts or Office scripts. In a similar fashion, document based Python libraries or modules can be loaded and released using Open document and Document closed events. Refer to Importing Python Modules for more information.
Using Tools - Customise menu Events tab, the Open document event fires a ConsoleLogger initialisation. -documentEventOccured routine - set by ConsoleLogger - serves as a unique entry point to trap all document events.
Option Explicit
Global -obj As Object ' controller.ConsoleLogger instance
Sub OnLoad(evt As com.sun.star.document.DocumentEvent) ' >> Open Document <<
-obj = New ConsoleLogger : -obj.StartAdapter(evt)
End Sub ' controller.OnLoad
Sub -documentEventOccured(evt As com.sun.star.document.DocumentEvent)
''' ConsoleLogger unique entry point '''
-obj.DocumentEventOccurs(evt)
End Sub ' controller.-documentEventOccured
Events monitoring starts from the moment a ConsoleLogger object is instantiated and ultimately stops upon document closure. StartAdapter routine loads necessary Basic libraries, while caught events are reported using Access2Base.Trace module.
Option Explicit
Option Compatible
Option ClassModule
' ADAPTER design pattern object to be instantiated in the "Open Document" event
Private Const UI-PROMPT = True
Private Const UI-NOPROMPT = False ' Set it to True to visualise documents events
' MEMBERS
Private -evtAdapter As Object ' com.sun.star.document.XDocumentEventBroadcaster
Private -txtMsg As String ' text message to log in console
' PROPERTIES
Private Property Get FileName As String
''' System-dependent filename '''
Const -LIBRARY = "Tools" : With GlobalScope.BasicLibraries
If Not .IsLibraryLoaded(-LIBRARY) Then .LoadLibrary(-LIBRARY)
End With
Filename = Tools.Strings.FilenameOutofPath(ThisComponent.URL)
End Property ' controller.ConsoleLogger.Filename
' METHODS
Public Sub DocumentEventOccurs(evt As com.sun.star.document.DocumentEvent)
''' Monitor document events '''
Access2Base.Trace.TraceLog("DEBUG", -
evt.EventName &" in "& Filename(evt.Source.URL), -
UI-NOPROMPT)
Select Case evt.EventName
Case "OnUnload" : -StopAdapter(evt)
End Select
End Sub ' controller.ConsoleLogger.DocumentEventOccurs
Public Sub StartAdapter(Optional evt As com.sun.star.document.DocumentEvent)
''' Initialise document events logging '''
Const -LIBRARY = "Access2Base" : With GlobalScope.BasicLibraries
If Not .IsLibraryLoaded(-LIBRARY) Then .LoadLibrary(-LIBRARY)
End With : Access2Base.Trace.TraceLevel("DEBUG")
If IsMissing(evt) Then -txtMsg = "" Else -txtMsg = evt.EventName & "-"
Access2Base.Trace.TraceLog("INFO", -txtMsg & "Document events are being logged", UI-PROMPT)
-evtAdapter = CreateUnoListener( "-", "com.sun.star.document.XDocumentEventListener" )
ThisComponent.addDocumentEventListener( -evtAdapter )
End Sub ' controller.ConsoleLogger.StartAdapter
Private Sub -StopAdapter(Optional evt As com.sun.star.document.DocumentEvent)
''' Terminate document events logging '''
ThisComponent.removeDocumentEventListener( -evtAdapter )
If IsMissing(evt) Then -txtMsg = "" Else -txtMsg = evt.EventName & "-"
Access2Base.Trace.TraceLog("INFO", -txtMsg & "Document events have been logged", UI-PROMPT)
Access2Base.Trace.TraceConsole() ' Captured events dialog
End Sub ' controller.ConsoleLogger.-StopAdapter
' EVENTS
' Your code for handled events goes here
Mind the misspelled -documentEventOccured method that inherits a typo from Office Application Programming Interface (API).
The broadcaster API object provides the list of events it is responsible for:
# -*- coding: utf-8 -*-
from --future-- import unicode-literals
import uno, apso-utils as ui
def displayAvailableEvents():
""" Display document events """
'''
adapted from DisplayAvailableEvents() by A. Pitonyak
https://forum.openoffice.org/en/forum/viewtopic.php?&t=43689
'''
ctx = XSCRIPTCONTEXT.getComponentContext()
smgr = ctx.ServiceManager
geb = smgr.createInstanceWithContext(
"com.sun.star.frame.GlobalEventBroadcaster", ctx)
events = geb.Events.getElementNames()
ui.msgbox('; '.join(events))
g-exportedScripts = (displayAvailableEvents,)
The Alternative Python Script Organizer (APSO) extension is used to render events information on screen.
Sub DisplayAvailableEvents
''' Display document events '''
Dim geb As Object ' com.sun.star.frame.GlobalEventBroadcaster
Dim events() As String
geb = CreateUnoService("com.sun.star.frame.GlobalEventBroadcaster")
events = geb.Events.ElementNames()
MsgBox Join(events, "; ")
End Sub