Python Guide - Useful functions
< Macros | Python Guide
TDF LibreOffice Document Liberation Project Community Blogs Weblate Nextcloud Redmine Ask LibreOffice Donate
Useful functions
In many examples show in this guide, we can used one or more the next functions.
Create instances
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
Get desktop
- One way
import uno
desktop = XSCRIPTCONTEXT.getDesktop()
- Create instance
desktop = create_instance('com.sun.star.frame.Desktop', True)
- Better for called from others macros
def get_desktop():
return create_instance('com.sun.star.frame.Desktop', True)
Call dispatch
- Many functions of LibreOffice, only can execute with 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
- For example, command copy
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()
Execute in other 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
- Now, you can execute any macro in other thread
@run_in_thread
def main():
return
Dictionary to properties
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
Get color
def get_color(red, green, blue):
color = (red << 16) + (green << 8) + blue
return color