Listening to Document Events

Listening to document events can help in the following situations:

Accanto all'assegnazione di macro agli eventi, un utente può monitorare gli eventi generati dai documenti LibreOffice. Le emittenti API (Application Programming Interface) sono responsabili delle chiamate degli script degli eventi. A differenza dei listener, che richiedono di definire tutti i metodi supportati, anche se non utilizzati, i monitor degli eventi richiedono solo due metodi accanto agli script degli eventi collegati.

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.

L'intercettazione degli eventi aiuta a impostare le pre- e post-condizioni degli script, come il caricamento o il rilascio di librerie o la tracciatura in sottofondo dell'elaborazione degli script. L'uso del modulo Access2Base.Trace illustra questo secondo contesto.

Con Python

Il monitoraggio degli eventi parte dall'istanziazione dell'oggetto e si ferma quando Python lo pubblica. Gli eventi generati vengono riportati utilizzando la console Access2Base.

note

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):
             """ Monitora gli eventi del documento """
             '''
             adattato da 'Python script to monitor OnSave event' in
             https://forum.openoffice.org/en/forum/viewtopic.php?t=68887
             '''
             def __init__(self):
                 """ Monitor degli eventi del documento """
                 ''' rapporto utilizzando la console Access2Base.Trace OR
                 rapporto nel 1° foglio, 1^ colonna per i documenti Calc '''
                 ctx = uno.getComponentContext()
                 smgr = ctx.getServiceManager()
                 desktop = smgr.createInstanceWithContext(
                 'com.sun.star.frame.Desktop' , ctx)
                 self.doc = desktop.CurrentComponent
                 #self.row = 0  # decommenta solo per i documenti Calc
                 Console.setLevel("DEBUG")
                 self.listen()  # Avvia il monitoraggio degli eventi dei doc.
             
             @property
             def Filename(self) -> str:
                 sys_filename = uno.fileUrlToSystemPath(self.doc.URL)
                 return os.path.basename(sys_filename)
             
             def setCell(self, calcDoc, txt: str):
                 """ Mostra il risultato degli eventi dei doc. sulla 1^ colonna di un foglio elettronico Calc """
                 sheet = calcDoc.getSheets().getByIndex(0)
                 sheet.getCellByPosition(0,self.row).setString(txt)
                 self.row = self.row + 1
             
             def listen(self, *args):  # OnLoad/OnNew al più presto
                 """ Avvia il monitoraggio degli eventi del doc. """
                 self.doc.addDocumentEventListener(self)
                 Console.log("INFO", "Si stanno registrando gli eventi del documento", True)
             
             def sleep(self, *args): # OnUnload al più tardi (opzionale)
                 """ Ferma il monitoraggio degli eventi del doc. """
                 self.doc.removeDocumentEventListener(self)
                 Console.log("INFO", "Gli eventi del documento sono stati registrati", True)
             
             def documentEventOccured(self, event: DocumentEvent):
                 """ Intercetta tutti gli eventi del doc. """
                 #self.setCell(event.Source, event.EventName) # solo per i documenti Calc
                 Console.log("DEBUG",
                     event.EventName+" in "+self.Filename,
                     False)
             
             def disposing(self, event: EventObject):
                 """ Pubblica tutte le attività """
                 self.sleep()
                 Console.show()
             
         def OnLoad(*args):  # Evento 'Open Document'
             listener = UiDocument()  # Initiates listening
             
         def OnUnload(*args):  # Evento 'Document has been closed'
             pass  # (facoltativo) eseguito durante la cancellazione
             
         g_exportedScripts = (OnLoad,)
             
         from com.sun.star.script.provider import XScript
         class Console():
             """
             Console in primo/secondo piano per riportare/registrare l'esecuzione del programma.
             """
             @staticmethod
             def trace(*args,**kwargs):
                 """ Stampa elenco degli elementi liberi nella console """
                 scr = Console._a2bScript(script='DebugPrint', module='Compatible')
                 scr.invoke((args),(),())
             @staticmethod
             def log(level: str, text: str, msgBox=False):
                 """ Allega messaggio di registro alla console, richiesta utente facoltativa """
                 scr = Console._a2bScript(script='TraceLog')
                 scr.invoke((level,text,msgBox),(),())
             @staticmethod
             def setLevel(logLevel: str):
                 """ Imposta limite inferiore per messaggi registro """
                 scr = Console._a2bScript(script='TraceLevel')
                 scr.invoke((logLevel,),(),())
             @staticmethod
             def show():
                 """ Mostra finestra di dialogo/contenuto console """
                 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
      
warning

Tenete presente il metodo documentEventOccured ortograficamente errato che eredita un errore dall'API (Application Programming Interface) di LibreOffice.


Icona di suggerimento

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

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 com.sun.star.document.DocumentEvent) ' >> Apri documento <<
            _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
      

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
              
          ' oggetto del modello di progettazione ADAPTER da istanziarsi nell'evento "Open Document"
          Private Const UI_PROMPT = True
          Private Const UI_NOPROMPT = False ' Set it to True to visualise documents events
              
          ' MEMBRI
          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
              ''' Nome file dipendente dal 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
              
          ' METODI
          Public Sub DocumentEventOccurs(evt As com.sun.star.document.DocumentEvent)
              ''' Monitora gli eventi del documento '''
              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)
              ''' Inizializza il registro degli eventi del documento '''
              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)
              ''' Termina la registrazione degli eventi del documento '''
              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
          ' Il vostro codice per gli eventi gestiti va qui
      
warning

Tenete presente il metodo _documentEventOccured ortograficamente errato che eredita un errore dall'API (Application Programming Interface) di LibreOffice.


Scoperta degli eventi del documento

L'oggetto API emittente fornisce l'elenco degli eventi di cui è responsabile:

Con Python


         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
             
         import uno, apso_utils as ui
             
         def displayAvailableEvents():
             """ Mostra gli eventi del documento """
             '''
             adattato da DisplayAvailableEvents() di 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,)
      
note

L'estensione Alternative Python Script Organizer (APSO) viene utilizzata per restituire le informazioni degli eventi sullo schermo.


Con LibreOffice Basic


         Sub DisplayAvailableEvents
             ''' Mostra gli eventi del documento '''
             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