Jump to content

Macro/Guida a Python/Funzioni utili

From The Document Foundation Wiki
This page is a translated version of the page Macros/Python Guide/Useful functions and the translation is 100% complete.


⇐ Ritorna all'indice


Funzioni utili

In molti degli esempi illustrati in questa guida, viene fatto uso di una o più delle prossime funzioni.

Creare istanze

import uno


CTX = uno.getComponentContext()
SM = CTX.getServiceManager()


def create_instance(name, with_context=False):
    if with_context:
        instance = SM.createInstanceWithContext(name, CTX)
    else:
        instance = SM.createInstance(name)
    return instance

Impostare il desktop

  • Primo modo

import uno

desktop = XSCRIPTCONTEXT.getDesktop()

  • Creazione di un'istanza

desktop = create_instance('com.sun.star.frame.Desktop', True)

  • funzione migliore al fine di poter essere richiamata da altre macro

def get_desktop():
    return create_instance('com.sun.star.frame.Desktop', True)

Richiamare dispatch

  • Molte funzioni di LibreOffice possono essere eseguite solamente con dispatch

def call_dispatch(doc, url, args=()):
    frame = doc.getCurrentController().getFrame()
    dispatch = create_instance('com.sun.star.frame.DispatchHelper')
    dispatch.executeDispatch(frame, url, '', 0, args)
    return

  • Per esempio il comando copia

doc = XSCRIPTCONTEXT.getDocument()
call_dispatch(doc, '.uno:Copy')

MsgBox

from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS


def msgbox(message, title='LibreOffice', buttons=MSG_BUTTONS.BUTTONS_OK, type_msg='infobox'):
    """ Create message box
        type_msg: infobox, warningbox, errorbox, querybox, messbox
        https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1awt_1_1XMessageBoxFactory.html
    """
    toolkit = create_instance('com.sun.star.awt.Toolkit')
    parent = toolkit.getDesktopWindow()
    mb = toolkit.createMessageBox(parent, type_msg, buttons, title, str(message))
    return mb.execute()

Esecuzione in un altro thread

import threading


def run_in_thread(fn):
    def run(*k, **kw):
        t = threading.Thread(target=fn, args=k, kwargs=kw)
        t.start()
        return t
    return run

Ora potete eseguire la macro in un altro thread

@run_in_thread
def main():

    return

da Dizionario a proprietà

from com.sun.star.beans import PropertyValue

def dict_to_property(values, uno_any=False):
    ps = tuple([PropertyValue(Name=n, Value=v) for n, v in values.items()])
    if uno_any:
        ps = uno.Any('[]com.sun.star.beans.PropertyValue', ps)
    return ps

Ottieni il colore

def get_color(red, green, blue):
    color = (red << 16) + (green << 8) + blue
    return color

⇐ Ritorna all'indice