Python : Memantau Acara Dokumen

Isi
Indeks 🔎︎

# Memantau Acara Dokumen

Di sampingmenugaskan makro ke acaraseseorang dapat memonitor acara yang diangkat oleh LibreOffice dokumen. Penyiar Application Programming Interface (API) bertanggung jawab untuk memanggil skrip acara. Tidak seperti pendengar yang perlu mendefinisikan semua metode yang didukung, bahkan jika tidak digunakan, monitor dokumen hanya membutuhkan dua metode di sebelah skrip acara yang dikaitkan.

## Mendengarkan Acara Dokumen

Pemantauan diilustrasikan dengan ini untuk bahasa-bahasa Basic dan Python menggunakan pemrograman berorientasi objek. MenugaskanSedang dimuatskrip, keBuka Dokumenacara, cukup untuk memulai dan mengakhiri pemantauan acara dokumen.Alat - Sesuaikan ...menuAcaratab digunakan untuk menetapkan kedua skrip.

Mencegah peristiwa membantu mengatur skrip sebelum dan sesudah kondisi seperti memuat dan menurunkan pustaka atau melacak pemrosesan skrip di latar belakang.Jejak Access2Basepenggunaan modul menggambarkan konteks kedua itu.

### Dengan menggunakan Python

Pemantauan peristiwa dimulai dari objek objek dan akhirnya berhenti ketika Python melepaskan objek. Acara yang dilaporkan dilaporkan menggunakanAccess2Basekonsol.

Sedang dimuatdanDi BongkarPeristiwa dapat digunakan untuk masing-masing mengatur dan menghapus jalur program Python. Mereka digambarkan sebagaiBuka dokumendanDokumen ditutup

             # -*- 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, Pattern Adapter):
                 """ Pantau kejadian dokumen """
                 '''
                 diadaptasi dari 'skrip Python untuk memantau peristiwa OnSave' pada
                 https://forum.openoffice.org/en/forum/viewtopic.php?t=68887
                 '''
                 def __init__(self):
                     """ Dokumentasikan monitor acara """
                     ''' laporkan menggunakan Access2Base.Trace console OR
                     laporan dalam lembar ke-1, kolom ke-1 untuk dokumen Calc '''
                     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):
                     """ Keluaran dokumen. acara di kolom pertama spreadsheet Calc '''
                     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
                     """ Mulai dokumen. pemantauan acara """
                     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 LibreOffice 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 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.

### With 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 controller.Events module
              Option Explicit
              Private _obj As Object ' controller.ConsoleLogger instance

              Sub OnLoad(evt As com.sun.star.document.DocumentEvent) ' >> 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

              ' CONSTRUCTOR/DESTRUCTOR
              Private Sub Class_Initialize()
              End Sub ' controller.ConsoleLogger.Initialize
              Private Sub Class_Terminate()
              End Sub ' controller.ConsoleLogger.Terminate

              ' MEMBERS
              Private _evtAdapter As Object ' com.sun.star.document.XDocumentEventBroadcaster

              ' 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
              Private Sub _documentEventOccured(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" : _Stop(evt)
                  End Select
              End Sub ' controller.ConsoleLogger._documentEventOccured

              Private Sub _disposing(evt As com.sun.star.lang.EventObject)
              End Sub ' controller.ConsoleLogger.disposing

              Public Sub Start(Optional evt As com.sun.star.document.DocumentEvent)
                  ''' Initialize document events logging '''
                  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", _
                      UI_PROMPT)

                  _evtAdapter = CreateUnoListener( "_", "com.sun.star.document.XDocumentEventListener" )
                  ThisComponent.addDocumentEventListener( _evtAdapter )
              End Sub ' controller.ConsoleLogger.Start

              Private Sub _Stop(Optional evt As com.sun.star.document.DocumentEvent)
                  ''' Terminate document events logging '''
                  ThisComponent.removeDocumentEventListener( _evtAdapter )
                  Access2Base.Trace.TraceLog("INFO", _
                      IIf(IsMissing(evt),"",evt.EventName & "-") & "Document events have been logged", _
                      UI_PROMPT)
                  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).

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

### With LibreOffice Basic

             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

Topik Terkait

Creating Event Listeners

Importing Python Modules

contoh pemrograman Python

Pemrograman dengan Skrip Python