Monitorizar sucesos de documento

Además de asignar macros a sucesos, es posible monitorizar los sucesos emitidos por los documentos de LibreOffice. Los difusores de API (interfaz de programación de aplicaciones, por sus siglas en inglés) son responsables de llamar a las macros de los sucesos. A diferencia de los agentes de escucha que requieren que se definan todos los métodos admitidos incluso si estos no se utilizan, los monitores de documento únicamente requieren dos métodos junto a macros de sucesos conectadas.

Escucha a sucesos de documentos

Se ilustra a continuación la monitorización utilizando la programación orientada a objetos en los lenguajes Python y Basic. Basta con asignar la macro OnLoad al suceso Open Document para iniciar y terminar la monitorización de sucesos de documento. Vaya al menú Herramientas ▸ Personalizar y seleccione la pestaña Sucesos para asignar las macros.

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.

Con Python

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 import DocumentEvent, \
             XDocumentEventListener as AdapterPattern
         from import EventObject
         class UiDocument(unohelper.Base, AdapterPattern):
             """ Monitor de sucesos del documento """
             adapted from 'Python script to monitor OnSave event' at
             def __init__(self):
                 """ Monitor de sucesos del documento """
                 ''' crear informe con la consola Access2Base.Trace O
                 informe en 1.ª hoja, 1.ª columna para documentos de Calc '''
                 ctx = uno.getComponentContext()
                 smgr = ctx.getServiceManager()
                 desktop = smgr.createInstanceWithContext(
                 '' , ctx)
                 self.doc = desktop.CurrentComponent
                 #self.row = 0  # uncomment for Calc documents only
                 self.listen()  # Start monitoring doc. events
             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)
                 self.row = self.row + 1
             def listen(self, *args):  # OnLoad/OnNew at the earliest
                 """ Start doc. events monitoring """
                 Console.log("INFO", "Document events are being logged", True)
             def sleep(self, *args):  # OnUnload at the latest (optional)
                 """ Stop doc. events monitoring """
                 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
                     event.EventName+" in "+self.Filename,
             def disposing(self, event: EventObject):
                 """ Release all activities """
         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 import XScript
         class Console():
             (Back/Fore)ground console to report/log program execution.
             def trace(*args,**kwargs):
                 """ Print free item list to console """
                 scr = Console._a2bScript(script='DebugPrint', module='Compatible')
             def log(level: str, text: str, msgBox=False):
                 """ Append log message to console, optional user prompt """
                 scr = Console._a2bScript(script='TraceLog')
             def setLevel(logLevel: str):
                 """ Set log messages lower limit """
                 scr = Console._a2bScript(script='TraceLevel')
             def show():
                 """ Display console content/dialog """
                 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

Mind the misspelled documentEventOccured method that inherits a typo from LibreOffice Application Programming Interface (API).

Icono de consejo

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.

Con LibreOffice Basic

The Onload script is assigned to Open document event using Tools – Customise... menu Events tab. Events monitoring starts from the moment a ConsoleLogger object is instantiated and ultimately stops when Basic engine releases it. OnLoad event loads necessary Basic libraries, while caught events are reported using Access2Base.Trace module.

          REM Módulo controller.Events
          Option Explicit
          Private _obj As Object ' controller.ConsoleLogger instance
          Sub OnLoad(evt As ' >> Open Document <<
              _obj = New ConsoleLogger : _obj.Start(evt)
          End Sub ' controller.OnLoad
          ' ----
          REM controller.ConsoleLogger class module
          Option Explicit
          Option Compatible
          Option ClassModule
          ' ADAPTER design pattern object to be instantiated in « Open Document » event
          Private Const UI_PROMPT = True
          Private Const UI_NOPROMPT = False ' Set it to True to visualise documents events
          Private Sub Class_Initialize()
          End Sub ' controller.ConsoleLogger.Initialize
          Private Sub Class_Terminate()
          End Sub ' controller.ConsoleLogger.Terminate
          ' MIEMBROS
          Private _evtAdapter As Object '
          ' PROPERTIES
          Private Property Get FileName As String
              ''' nombre de archivo dependiente del sistema '''
              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
          ' MÉTODOS
          Private Sub _documentEventOccured(evt As
              ''' Monitorizar sucesos de documento '''
              Access2Base.Trace.TraceLog("DEBUG", _
                  evt.EventName &" in "& Filename(evt.Source.URL), _
              Select Case evt.EventName
                  Case "OnUnload" : _Stop(evt)
              End Select
          End Sub ' controller.ConsoleLogger._documentEventOccured
          Private Sub _disposing(evt As
          End Sub ' controller.ConsoleLogger.disposing
          Public Sub Start(Optional evt As
              ''' Iniciar registro de sucesos de documento '''
              Const _LIBRARY = "Access2Base" : With GlobalScope.BasicLibraries
                  If Not .IsLibraryLoaded(_LIBRARY) Then .LoadLibrary(_LIBRARY)
              End With : Access2Base.Trace.TraceLevel("DEBUG")
              Access2Base.Trace.TraceLog("INFO", _
                  IIf(IsMissing(evt),"",evt.EventName & "-") & "Document events are being logged", _
              _evtAdapter = CreateUnoListener( "_", "" )
              ThisComponent.addDocumentEventListener( _evtAdapter )
          End Sub ' controller.ConsoleLogger.Start
          Private Sub _Stop(Optional evt As
              ''' Terminate document events logging '''
              ThisComponent.removeDocumentEventListener( _evtAdapter )
              Access2Base.Trace.TraceLog("INFO", _
                  IIf(IsMissing(evt),"",evt.EventName & "-") & "Document events have been logged", _
              Access2Base.Trace.TraceConsole() ' Captured events dialog
          End Sub ' controller.ConsoleLogger._Stop
          ' EVENTS
          ' Your code for handled events goes here

Mind the misspelled _documentEventOccured method that inherits a typo from LibreOffice Application Programming Interface (API).

Descubrimiento de sucesos de documento

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

Con Python

         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
         import uno, apso_utils as ui
         def displayAvailableEvents():
             """ Mostrar sucesos de documento """
             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.

Con LibreOffice Basic

         Sub DisplayAvailableEvents
             ''' Mostrar sucesos de documento '''
             Dim geb As Object '
             Dim events() As String
             geb = CreateUnoService("")
             events = geb.Events.ElementNames()
             MsgBox Join(events, "; ")
         End Sub

¡Necesitamos su ayuda!