LoginSignup
2
3

More than 5 years have passed since last update.

LibreOffice Pythonマクロ 「メッセージボックスの表示」

Last updated at Posted at 2018-02-20

注意)
このページのマクロは、Libreofficeの「マクロの実行」で動作させます。

LibreOfficeでPythonマクロを実行するには、
UbuntuのLibreOffice(MS Office互換性あり)でPythonマクロを使用する方法(超初級者向け)
https://qiita.com/ty21ky/items/2c8b001363c8293198e2
を参照ください。

実行した環境

  Ubuntu Studio 17.10
  LibreOffice6.0 Writer,Calc,Math,Base,Draw,Impress

参考にしたサイト

試験運用中なLinux備忘録
http://d.hatena.ne.jp/kakurasan/20100305/p1

コードの説明等は上記のサイトを参照してください。

上記のサイトのコードのままではエラーが出て実行できませんでした。
2010年の古い記事ですので、この間に仕様が変更されたのではないでしょうか?

変更箇所

msgbox = self._toolkit.createMessageBox(self._window,
#uno.createUnoStruct('com.sun.star.awt.Rectangle'), #この行を削除、コメント等に変更します。
# ダイアログの種類を指定する文字列
# infobox,warningbox,errorbox,
# querybox,messboxのいずれか
'infobox',
1,
title,
message)

DialogTest.py
# -*- mode: python; coding: utf-8 -*-

import uno

class Bridge(object):

  def __init__(self):
    self._context = XSCRIPTCONTEXT.getComponentContext()
    self._desktop = XSCRIPTCONTEXT.getDesktop()
    self._frame = self._desktop.CurrentFrame
    self._window = self._frame.ContainerWindow
    self._toolkit = self._window.Toolkit

  def run_infodialog(self, title='', message=''):
    msgbox = self._toolkit.createMessageBox(self._window,
                                            'infobox',
                                            1,
                                            title,
                                            message)
    msgbox.execute()
    msgbox.dispose()

def hello():
  pyuno = Bridge()
  pyuno.run_infodialog(title='Test テスト', message='Python UNO Test\nパイソン ユーノウ テスト')

g_exportedScripts = (hello,)

dialog.jpg

参考URL

Apache OpenOffice 4.1.5 released
Developer's Guide
http://www.openoffice.org/api/docs/common/ref/com/sun/star/awt/XMessageBoxFactory.html

メッセージボックス(その2)

実行した環境

  Ubuntu Studio 17.10
  LibreOffice6.0 Writer,Calc,Math,Base,Draw,Impress

参考URLはコードしか無いので不明(海外のような気がする)

MessageBox.py
import uno

from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE

from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX


def TestMessageBox():
  doc = XSCRIPTCONTEXT.getDocument()
  parentwin = doc.CurrentController.Frame.ContainerWindow

  s = "This a message"
  t = "Title of the box"
  res = MessageBox(parentwin, s, t, QUERYBOX, BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_NO)

  s = res
  MessageBox(parentwin, s, t, "infobox")

# Show a message box with the UNO based toolkit
def MessageBox(ParentWin, MsgText, MsgTitle, MsgType=MESSAGEBOX, MsgButtons=BUTTONS_OK):

  ctx = uno.getComponentContext()
  sm = ctx.ServiceManager
  sv = sm.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx) 
  myBox = sv.createMessageBox(ParentWin, MsgType, MsgButtons, MsgTitle, MsgText)
  return myBox.execute()

g_exportedScripts = TestMessageBox,

MessageBox1.png

MessageBox2.png

ボタン 戻り値
はい 2
いいえ 3
キャンセル 0

メッセージボックス(その3)

実行した環境

  Ubuntu Studio 17.10
  LibreOffice6.0 Writer,Calc,Math,Base,Draw,Impress

メッセージタイプ「infobox」を「messbox」に変更すると何故かエラーになります。infobox,warningbox,errorbox,queryboxは問題ありません。

MsgBox.py
def msgBox():
  win = XSCRIPTCONTEXT.getDesktop().getCurrentFrame().getContainerWindow()
  toolkit = win.getToolkit()
  type='infobox'
  button=1
  title='Title'
  msg='メッセージ'
  msgbox=toolkit.createMessageBox(win, type, button, title, msg)
  msgbox.execute()
  msgbox.dispose()

MsgBox.png

メッセージボックス(その4)LibreOffice4.2以降

http://openoffice3.web.fc2.com/Python_Macro_General_No6.html#OOoGW02a
Macroの杜( Python編 )【 General No.6 】

GDPi-)[General]Version of LibreOffice( Apache OpenOffice )

MessageBox
#!
#coding: utf-8
# python Marco
import uno
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
from com.sun.star.beans import PropertyValue
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
    """shows message."""
    desktop = XSCRIPTCONTEXT.getDesktop()
    frame = desktop.getCurrentFrame()
    window = frame.getContainerWindow()
    toolkit = window.getToolkit()
    msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
    return msgbox.execute()
def createUnoService(service_name):
    """Create a UNO Service By this name"""
    ctx = XSCRIPTCONTEXT.getComponentContext()
    try:
        service = ctx.ServiceManager.createInstanceWithContext(service_name, ctx)
    except:
        service = NONE
    return service
def PyGetSolar():
    try:
        oProvider = 'com.sun.star.configuration.ConfigurationProvider'
        oAccess   = 'com.sun.star.configuration.ConfigurationAccess'
        oConfigProvider = createUnoService(oProvider)
        oProp = PropertyValue()
        oProp.Name = 'nodepath'
        oProp.Value = '/org.openoffice.Setup/Product'
        properties = (oProp,)
        oSet = oConfigProvider.createInstanceWithArguments(oAccess, properties)
        OOoVer = oSet.getByName('ooSetupVersion')
        oDisp = u'[ Version of LibreOffice ]\n\t ver.' + str(OOoVer)
    except Exception as er:
        oDisp = ''
        oDisp = str(traceback.format_exc()) + '\n' + str(er)
    finally:
        omsgbox(oDisp)

メッセージボックス(その5)参考

http://openoffice3.web.fc2.com/Python_Macro_General_No1.html#OOoGM0a
のマクロの中で説明していますが、下記のコードは古いLibreOffice 4.1 までのコードのようです。

https://wiki.openoffice.org/wiki/Python/Transfer_from_Basic_to_Python
Apache OpenOffice wiki
Transfer from Basic to Python

Message Box
Pythonでは、ショートカット機能は提供されていませんが、ツールキットを通してcom.sun.star.awt.XMessageBoxFactoryインタフェースを使用することができます。

MessageBox
def messagebox(ctx, parent, message, title, message_type, buttons):
    """ Show message in message box. """
    toolkit = parent.getToolkit()
    older_imple = check_method_parameter(
        ctx, "com.sun.star.awt.XMessageBoxFactory", "createMessageBox", 
        1, "com.sun.star.awt.Rectangle")
    if older_imple:
        msgbox = toolkit.createMessageBox(
            parent, Rectangle(), message_type, buttons, title, message)
    else:
        message_type = uno.getConstantByName("com.sun.star.awt.MessageBoxType." + {
            "messbox": "MESSAGEBOX", "infobox": "INFOBOX", 
            "warningbox": "WARNINGBOX", "errorbox": "ERRORBOX", 
            "querybox": "QUERYBOX"}[message_type])
        msgbox = toolkit.createMessageBox(
            parent, message_type, buttons, title, message)
    n = msgbox.execute()
    msgbox.dispose()
    return n


def check_method_parameter(ctx, interface_name, method_name, param_index, param_type):
    """ Check the method has specific type parameter at the specific position. """
    cr = create_service(ctx, "com.sun.star.reflection.CoreReflection")
    try:
        idl = cr.forName(interface_name)
        m = idl.getMethod(method_name)
        if m:
            info = m.getParameterInfos()[param_index]
            return info.aType.getName() == param_type
    except:
        pass
    return False
2
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3