Listening to Document Events

Listening to document events can help in the following situations:

Next to assigning macros to events, one can monitor events raised by LibreOffice 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 Document Events

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 - Customize 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.

Dengan menggunakan Python

Pemantauan kejadian dimulai ketika objek diinstansiasi dan akhirnya diberhentikan ketika Python melepaskan objek. Kejadian yang dibangkitkan dilaporkan menggunakan konsol Access2Base.


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 import DocumentEvent, \
             XDocumentEventListener as AdapterPattern
         from import EventObject
         class UiDocument(unohelper.Base, AdapterPattern):
             """ Memantau kejadian dalam dokumen """
             diadaptasi dari 'skrip Python untuk memantau peristiwa OnSave' pada
             def __init__(self):
                 """ Pemantau kejadian dalam dokumen """
                 ''' laporkan menggunakan konsol Access2Base.Trace ATAU
                 laporkan dalam sheet pertama, kolom pertama untuk dokumen Calc '''
                 ctx = uno.getComponentContext()
                 smgr = ctx.getServiceManager()
                 desktop = smgr.createInstanceWithContext(
                 '' , ctx)
                 self.doc = desktop.CurrentComponent
                 #self.row = 0  # hilangkan komentar hanya untuk dokumen Calc
                 self.listen()  # Mulai memonitor kejadian dalam dok.
             def Filename(self) -> str:
                 sys_filename = uno.fileUrlToSystemPath(self.doc.URL)
                 return os.path.basename(sys_filename)
             def setCell(self, calcDoc, txt: str):
                 """ Keluaran kejadian dokumen dalam kolom pertama dari lembar sebar Calc """
                 sheet = calcDoc.getSheets().getByIndex(0)
                 self.row = self.row + 1
             def listen(self, *args):  # OnLoad/OnNew saat paling awal
                 """ Mulai memantau kejadian dalam dok. """
                 Console.log("INFO", "Kejadian dokumen sedang dicatat", True)
             def sleep(self, *args):  # OnUnload at the latest (opsional)
                 """ Berhenti memonitor kejadian dalam dokumen """
                 Console.log("INFO", "Kejadian dokumen telah dicatat", True)
             def documentEventOccured(self, event: DocumentEvent):
                 """ Menangkap semua kejadian dokumen """
                 #self.setCell(event.Source, event.EventName) # hanya untuk dokumen Calc
                     event.EventName+" in "+self.Filename,
             def disposing(self, event: EventObject):
                 """ Lepas semua aktivitas """
         def OnLoad(*args):  # peristiwa 'Buka Dokumen'
             listener = UiDocument()  # Initiates listening
         def OnUnload(*args):  # peristiwa 'Dokumen telah ditutup'
             pass  # (opsional) dilakukan ketika state-nya disposed
         g_exportedScripts = (OnLoad,)
         from import XScript
         class Console():
             Konsol latar depan/belakang untuk melaporkan/mencatat eksekusi program.
             def trace(*args,**kwargs):
                 """ Cetak daftar item bebas ke konsol """
                 scr = Console._a2bScript(script='DebugPrint', module='Compatible')
             def log(level: str, text: str, msgBox=False):
                 """ Tambahkan log pesan ke konsol, prompt pengguna opsional """
                 scr = Console._a2bScript(script='TraceLog')
             def setLevel(logLevel: str):
                 """ Setel batas bawah log pesan """
                 scr = Console._a2bScript(script='TraceLevel')
             def show():
                 """ Tampilkan konten/dialog konsol """
                 scr = Console._a2bScript(script='TraceConsole')
             def _a2bScript(script: str, library='Access2Base',
                 module='Trace') -> XScript:
                 ''' Grab application-based Basic script '''
                 sm = uno.getComponentContext().ServiceManager
                 mspf = sm.createInstanceWithContext(
                 scriptPro = mspf.createScriptProvider("")
                 scriptName = ""+library+"."+module+"."+script+"?language=Basic&location=application"
                 xScript = scriptPro.getScript(scriptName)
                 return xScript

Perhatikan kesalahan ejaan metode documentEventOccured yang membawa kesalahan ketik dari LibreOffice Application Programming Interface (API).

Ikon Tip

Start application and Close application events can respectively be used to set and to unset Python path for user scripts or LibreOffice 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.

Dengan Basic LibreOffice

Using Tools - Customize 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.

controller.Events module

        Option Explicit
        Global _obj As Object ' controller.ConsoleLogger instance
        Sub OnLoad(evt As ' >> Open Document <<
            _obj = New ConsoleLogger : _obj.StartAdapter(evt)
        End Sub ' controller.OnLoad
        Sub _documentEventOccured(evt As
            ''' ConsoleLogger unique entry point '''
        End Sub ' controller._documentEventOccured

controller.ConsoleLogger class module

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 '
          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
              ''' Monitor document events '''
              Access2Base.Trace.TraceLog("DEBUG", _
                  evt.EventName &" in "& Filename(evt.Source.URL), _
              Select Case evt.EventName
                  Case "OnUnload" : _StopAdapter(evt)
              End Select
          End Sub ' controller.ConsoleLogger.DocumentEventOccurs
          Public Sub StartAdapter(Optional evt As
              ''' Initialize 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( "_", "" )
              ThisComponent.addDocumentEventListener( _evtAdapter )
          End Sub ' controller.ConsoleLogger.StartAdapter
          Private Sub _StopAdapter(Optional evt As
              ''' 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 LibreOffice Application Programming Interface (API).

Discovering Documents Events

The broadcaster API object provides the list of events it is responsible for:

With Python

         # -*- 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
             ctx = XSCRIPTCONTEXT.getComponentContext()
             smgr = ctx.ServiceManager
             geb = smgr.createInstanceWithContext(
                 "", 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.

With LibreOffice Basic

         Sub DisplayAvailableEvents
             ''' Display document events '''
             Dim geb As Object '
             Dim events() As String
             geb = CreateUnoService("")
             events = geb.Events.ElementNames()
             MsgBox Join(events, "; ")
         End Sub

Mohon dukung kami!