LibreOffice 25.2 žinynas
Listening to document events can help in the following situations:
Identify a new document at opening time, as opposed to existing ones, and perform a dedicated setup.
Control the processing of document save, document copy, print or mailmerge requests.
Recalculate table of contents, indexes or table entries of a Writer document when document is going to be closed
Import math Python packages before opening a Calc document. Release these packages when the document closes.
Šalia makrokomandų priskyrimas įvykiams galima stebėti įvykius, kuriuos generuoja „%{PRODUCTNAME}“ dokumentai. Programų sąsajos (API) transliuotojai yra atsakingi už įvykių scenarijų iškvietimą. Skirtingai nuo kūrėjų, kuriems reikia apibrėžti visus palaikomus metodus, net jei jie nenaudojami, dokumentų stebėjimo priemonėms šalia įjungtų įvykių scenarijų reikia tik dviejų būdų.
Monitoring is illustrated herewith for Basic and Python languages using object-oriented programming. Assigning OnLoad script, to the event, suffices to initiate and terminate document event monitoring. menu 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.
Įvykių stebėjimas prasideda nuo objekto inicijavimo ir galiausiai sustoja, kai Pitonas paskelbia objektą. Apie esamus įvykius pranešama naudojant konsolę Access2Base.
OnLoad and OnUnload events can be used to respectively set and unset Python programs path. They are described as and .
         # -*- 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):
             """ Dokumentinių įvykių stebėjimas """
             '''
             adaptuota pagal 'Pitono skriptas OnSave įvykiams' at
             https://forum.openoffice.org/en/forum/viewtopic.php?t=68887
             '''
             def __init__(self):
                 """ Dokumentinių įvykių stebėjimas """
                 ''' ataskaita naudojant „Access2Base.Trace“ konsolę OR
                 pranešamas apie „Calc docs“ 1-ojo lakšto 1-ąjį stulpelį  '''
                 ctx = uno.getComponentContext()
                 smgr = ctx.getServiceManager()
                 desktop = smgr.createInstanceWithContext(
                 'com.sun.star.frame.Desktop' , ctx)
                 self.doc = desktop.CurrentComponent
                 #self.row = 0  # tik „Calc“ documentams nėra komentarų
                 Console.setLevel("DEBUG")
                 self.listen()  # pradedama stebėti 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):
                 """ Rezultato doc. įvykiai „Calc“ skaičiuoklės 1-ame stulpelyje """
                 sheet = calcDoc.getSheets().getByIndex(0)
                 sheet.getCellByPosition(0,self.row).setString(txt)
                 self.row = self.row + 1
             
             def listen(self, *args):  # OnLoad/OnNew anksčiausiai
                 """ Pradėkite stebėti doc. įvykius ""
                 self.doc.addDocumentEventListener(self)
                 Console.log("INFO", "Dokumentų įvykiai registruojami", True)
             
             def sleep(self, *args):  # OnUnload vėliausiai (pasirinktinai)
                 """ Stabdykite stebėti doc. įvykius ""
                 self.doc.removeDocumentEventListener(self)
                 Console.log("INFO", "Dokumentų įvykiai registruojami", True)
             
             def documentEventOccured(self, event: DocumentEvent):
                 """ Perima visus doc. įvykius """
                 #self.setCell(event.Source, event.EventName) # tik Calc docs
                 Console.log("DEBUG",
                     event.EventName+" in "+self.Filename,
                     False)
             
             def disposing(self, event: EventObject):
                 """ Išleisti visas veiklas """
                 self.sleep()
                 Console.show()
             
         def OnLoad(*args):  # 'Atverti dokumentą' įvykis
             listener = UiDocument()  # Initiates listening
             
         def OnUnload(*args):  # 'Dokumentas užvertas' įvykis
             pass  # (pasirinktinai) atliekama pašalinus
             
         g_exportedScripts = (OnLoad,)
             
         from com.sun.star.script.provider import XScript
         class Console():
             """
             (Back/Fore) antžeminė konsolė, skirta pranešti ar registruoti programos vykdymą.
             """
             @staticmethod
             def trace(*args,**kwargs):
                 """ Spausdinkite elementų sąrašą į konsolę """
                 scr = Console._a2bScript(script='DebugPrint', module='Compatible')
                 scr.invoke((args),(),())
             @staticmethod
             def log(level: str, text: str, msgBox=False):
                 """ Pridėkite žurnalo pranešimą prie konsolės, pasirinktinis vartotojo raginimas """
                 scr = Console._a2bScript(script='TraceLog')
                 scr.invoke((level,text,msgBox),(),())
             @staticmethod
             def setLevel(logLevel: str):
                 """ Nustatykite žurnalo pranešimų apatinę ribą """
                 scr = Console._a2bScript(script='TraceLevel')
                 scr.invoke((logLevel,),(),())
             @staticmethod
             def show():
                 """ Rodyti konsolės turinį ar 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
      Turėkite omenyje klaidingai parašytą metodą documentEventOccured, kuris perima rašybos klaidą iš „LibreOffice“ taikomųjų programų sąsajos (API).
and 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 and events. Refer to Importing Python Modules for more information.
Using menu tab, the event fires a ConsoleLogger initialisation. _documentEventOccured routine - set by ConsoleLogger - serves as a unique entry point to trap all document events.
        Option Explicit
        
        Global _obj As Object ' controller.ConsoleLogger instance
        
        Sub OnLoad(evt As com.sun.star.document.DocumentEvent) ' >> Atverti dokumentą <<
            _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
      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 dizaino modelio objektas, kuris bus paruoštas įvykiui „Atverti dokumentą“
          Private Const UI_PROMPT = True
          Private Const UI_NOPROMPT = False ' Set it to True to visualise documents events
              
          ' NARIAI
          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
              ''' Nuo sistemos priklausomas failo vardas '''
              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
              
          ' METODAI
          Public Sub DocumentEventOccurs(evt As com.sun.star.document.DocumentEvent)
              ''' Dokumentinių įvykių stebėjimas '''
              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)
              ''' Inicializuokite dokumento įvykių registravimą '''
              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)
              ''' Nutraukite dokumento įvykių registravimą '''
              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
          ' Čia nurodomas jūsų tvarkomų įvykių kodas
      Turėkite omenyje klaidingai parašytą metodą _documentEventOccured, kuris perima rašybos klaidą iš „LibreOffice“ taikomųjų programų sąsajos (API).
Transliuotojo API objektas pateikia įvykių, už kuriuos yra atsakingas, sąrašą:
         # -*- coding: utf-8 -*-
         from __future__ import unicode_literals
             
         import uno, apso_utils as ui
             
         def displayAvailableEvents():
             """ Rodyti dokumento įvykius """
             '''
             DisplayAvailableEvents() adaptavo 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,)
      Alternatyvus „Python“ skripto organizacijos (APSO) plėtinys naudojamas įvykių informacijai pateikti ekrane.
         Sub DisplayAvailableEvents
             ''' Rodyti dokumentinius įvykius '''
             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