Jump to content

マクロ/Pythonガイド/便利な関数

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.


目次に戻る


便利な関数

このガイドで紹介している多くのサンプルでは、以下の関数を使用しています。

インスタンスの生成

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

デスクトップの取得

  • 一つだけ

import uno

desktop = XSCRIPTCONTEXT.getDesktop()

  • インスタンスの生成

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

  • 他のマクロからの呼び出しの方がいい場合

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

ディスパッチの呼び出し

  • LibreOfficeの多くの機能は、ディスパッチでのみ実行できます

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

  • たとえば、コピーコマンド

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()

別のスレッドで実行する

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

  • これで、他のスレッドでも任意のマクロを実行できます

@run_in_thread
def main():

    return

辞書型からプロパティに反映する

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

色コードを取得

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

目次に戻る