Listening to Document Events

Listening to document events can help in the following situations:

将宏分配给事件旁边,可以监视 LibreOffice 文档所引发的事件。应用程序编程接口 (API) 广播器负责调用事件脚本。与需要定义所有支持的方法 (即使未使用) 的监听器不同, 文档监视器对已挂钩的事件脚本只需要两个方法。

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.

使用 Python

事件监视从对象实例化开始, 并在 Python 释放对象时最终停止。引发的事件通过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):
             """ 监视文档事件 """
             改编自「用于监视 OnSave 事件的 Python 脚本」,见于
             def __init__(self):
                 """ 文档事件监视器 """
                 ''' 使用 Access2Base.Trace 控制台报告,*或*
                 在 Calc 文档的第一个工作表的第一列报告 '''
                 ctx = uno.getComponentContext()
                 smgr = ctx.getServiceManager()
                 desktop = smgr.createInstanceWithContext(
                 '' , ctx)
                 self.doc = desktop.CurrentComponent
                 #self.row = 0  # 仅对 Calc 文档取消注释
                 self.listen()  # 开始监视文档事件
             def Filename(self) -> str:
                 sys_filename = uno.fileUrlToSystemPath(self.doc.URL)
                 return os.path.basename(sys_filename)
             def setCell(self, calcDoc, txt: str):
                 """ 在 Calc 电子表格的第一列输出文档事件 """
                 sheet = calcDoc.getSheets().getByIndex(0)
                 self.row = self.row + 1
             def listen(self, *args):  # 尽可能早执行 OnLoad/OnNew
                 """ 开始文档事件监视 """
                 Console.log("INFO", "正在记录文档事件", True)
             def sleep(self, *args):  # 最后执行 OnUnload (可选)
                 """ 停止文档事件监视 """
                 Console.log("INFO", "文档事件已记录", True)
             def documentEventOccured(self, event: DocumentEvent):
                 """ 截取所有文档事件 """
                 #self.setCell(event.Source, event.EventName) # 仅适用于 Calc 文档
                     event.EventName+" in "+self.Filename,
             def disposing(self, event: EventObject):
                 """ 释放所有活动 """
         def OnLoad(*args):  #「文档打开」事件
             listener = UiDocument()  # Initiates listening
         def OnUnload(*args):  # '文档已关闭' 事件
             pass  # (可选) 销毁时执行
         g_exportedScripts = (OnLoad,)
         from import XScript
         class Console():
             def trace(*args,**kwargs):
                 """ 向控制台打印空闲项目列表 """
                 scr = Console._a2bScript(script='DebugPrint', module='Compatible')
             def log(level: str, text: str, msgBox=False):
                 """ 日志消息追加到控制台,可选用户提示 """
                 scr = Console._a2bScript(script='TraceLog')
             def setLevel(logLevel: str):
                 """ 设置日志消息下限 """
                 scr = Console._a2bScript(script='TraceLevel')
             def show():
                 """ 显示控制台内容/对话框 """
                 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

注意拼写错误的 documentEventOccured 方法, 该错误继承自 LibreOffice 应用程序编程接口 (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.

使用 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 ' >> 文档打开 <<
            _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
          ' 成员
          Private _evtAdapter As Object '
          Private _txtMsg As String ' text message to log in console
          ' PROPERTIES
          Private Property Get FileName As String
              ''' 受系统影响的文件名 '''
              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
          ' 方法
          Public Sub DocumentEventOccurs(evt As
              ''' 监视文档事件 '''
              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
              ''' 初始化文档事件记录 '''
              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
              ''' 终止文档事件记录 '''
              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
          ' 用于已处理事件的代码放在这里

注意拼写错误的 _documentEventOccured 方法, 该错误继承自 LibreOffice 应用程序编程接口 (API)。


广播器 API 对象提供了它所负责的事件列表:

使用 Python

         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
         import uno, apso_utils as ui
         def displayAvailableEvents():
             """ 显示文档事件 """
             改编自 DisplayAvailableEvents(),作者为 A. Pitonyak
             ctx = XSCRIPTCONTEXT.getComponentContext()
             smgr = ctx.ServiceManager
             geb = smgr.createInstanceWithContext(
                 "", ctx)
             events = geb.Events.getElementNames()
             ui.msgbox('; '.join(events))
         g_exportedScripts = (displayAvailableEvents,)

替代 Python 脚本管理器 (APSO)」扩展程序用于在屏幕上渲染事件信息。

使用 LibreOffice Basic

         Sub DisplayAvailableEvents
             ''' 显示文档事件 '''
             Dim geb As Object '
             Dim events() As String
             geb = CreateUnoService("")
             events = geb.Events.ElementNames()
             MsgBox Join(events, "; ")
         End Sub