マクロ/Python設計ガイド

    From The Document Foundation Wiki
    This page is a translated version of the page Macros/Python Design Guide and the translation is 55% complete.
    Outdated translations are marked like this.

    はじめに

    このページでは、LibreOfficeを使ったシステムの開発や設計を考えているPythonマクロ開発者を対象としています。このページの開発ガイドラインは、Pythonでプログラミングする初心者から経験豊富な方まで参考になるでしょう。LibreOffice上で実際にPythonを利用している例を知りたい方は、Pythonプログラマーズガイドを御覧ください。

    LibreOfficeプロジェクトに参加をしたい方は、このTDF Wikiを参考にしてください。

    このページでは、PythonのサンプルプログラムとLibreOffice拡張機能の利用について説明しています。ですので、PythonとLibreOfficeの使い方について、ある程度理解していることを前提としています。

    ドキュメント

    オンライン講座・ガイド

    電子文献

    統一モデリング言語 (UML)

    UML駆動のツールは数多くあります。ここでは、利用できる言語に注目した自由・オープンソースで相互運用可能なアプリケーションのリストを紹介します。

    • ArgoUML : ArgoUMLは、さまざまなJavaプラットフォーム上で動作し、10言語(アメリカ英語、イギリス英語、フランス語、ドイツ語、イタリア語、ポルトガル語、スペイン語、ロシア語、ノルウェー語、中国語)で提供されています。
    • StarUML : StarUMLは、macOS 10.6以上、Windows XP以上、Ubuntu (64または32ビット)向けに提供されています。StarUMLは豊富な機能を備えていますが、英語版のみの提供です。
    • Umbrello : Umbrelloは、多言語対応しています。GNU/Linuxディストリビューション、Windows(64または32ビット)、macOSに対応しています。

    UML(Unified Modeling Language (UML))ツールについての豊富なリストは、Wikipediaから入手できます。

    StarOffice Programmer's Tutorialでは、UMLダイアグラムを使ったLibreOfficeドキュメントの詳細を解説しています。

    Wikipediaにもソフトウェア・デザインパターンは掲載されており、Pythonの例もあります。

    前文

    Pythonスクリプトのライブラリ管理

    Basicマクロの開発は、Basicの編集やデバッグができる統合開発環境(IDE)がLibreOfficeに付属しています。 Pythonマクロを作成するには、自分が選んだIDEで開発するための設定をおこなう必要があります。 その代わり、あなたのPython開発の好みや習慣にもとづいた柔軟な開発環境が利用できます。ここでは、初心者から上級者まで使えるIDE設定ガイドラインを紹介します。

    Pythonは、Basicと同じライブラリやマクロを扱うことはできません。しかし、Pythonの伝統的なモジュールや関数を管理は可能で、Pythonのパッケージを作成することは、LibreOfficeの拡張機能やUNOパッケージの作成と部分的には似ています。このページでは、モジュールをライブラリ、関数をマクロと区別して使用しています。ですが、Pythonの文化に合わせて、Python用語を使うこともあります。

    LibreOfficeスクリプトには、個人用、共有用、文書埋め込みの3種類あります。スクリプトはタイプやプラットフォームにより、さまざまな場所に保存されます。詳細については、AOO wikiの記事「マクロ言語としてのPython」を参照してください。

    Pythonスクリプトの管理は、Windowsのライブラリを使うか、GNU/Linuxのファイルマネージャのショートカットを使うかのどちらかです。つまり、.pyファイルはドラッグ・アンド・ドロップで簡単に整理できます。ライブラリやファイルマネージャのショートカットを設定にも役立つ、環境に応じたフォルダの場所の説明は、AOO wiki記事「マクロ言語としてのPython」にあります。

    Pythonプロジェクトは、図で示されているようにIDEごとにWindowsライブラリに配置することができます。

    APSOメニュー

    APSO(Alternative Python Script Organizer)拡張機能はPythonスクリプトの管理に必要不可欠です。この拡張機能を使うと、PythonスクリプトをLibreOfficeに統合して利用できます。この拡張機能をインストールしてLibreOfficeを再起動するとメニューのツールのサブメニューマクロ - Pythonスクリプトの管理が表示されます。

    この拡張機能は、Pythonスクリプトを管理するための、さまざまな機能を提供します。 実行ボタンは、選択したマクロを実行します。メニューボタンから使用できる機能は、選択した機能により異なります。

    APSOダイアログ
    • 選択した個人、共有、文書コンテナーにマクロまたはライブラリを作成
    • マクロまたはライブラリの編集、リネーム、削除
    • マクロを個人、共有コンテナーから文書へ埋め込み
    • 文書にに埋め込まれたライブラリをプラットフォームのPythonモジュールで置換する
    • 文書に埋め込まれたライブラリをPythonモジュールとしてエクスポート
    • 選択したマクロのデバッグ
    • Pythonインタープリタとして知られるPython対話コンソールの実行

    スクリプトの構成やPythonパッケージに関する情報、その他の情報は、デバッギングにあります。

    LibreOfficeのスクリプトでは、LibreOfficeでスクリプトを使用する方法を詳しく説明しています。

    開発について

    Numerous applications make use of Python, either natively or specifically. LibreOffice embeds its own Python interpreter which permits to use the API through Universal Network Objects (UNO). Python language holds its own interpreter that can be used in parallel to that of LibreOffice. Both share a common base and are extensible, thus they provide identical features as well as they offer different ones. Native Python does not include the UNO interface to LibreOffice API. Reversely LibreOffice does not fully behave as native Python and does not extend its functionalities the exact same way as native Python. However, neither LibreOffice nor native Python facilitate application development with Python language for Writer, Calc, Impress, Draw, Base or Math.

    LibreOffice exists in 32- or 64-bit versions. The Integrated Development Environment (IDE) that accompany it requires to execute in the same context, both in 32- or 64-bit. Numerous IDEs exist from the easiest like IDLE, although disputable, to more elaborated ones like PyCharm or PyDev for Eclipse. The following list arbitrarily focuses on tools that are free, open source, multi platform and possibly multi lingual. Below Debugging chapter uses Pyzo and PyCharm solely for illustration. A list of IDEs for Python is available from Python.org site. A comparison of Integrated Development Environments (IDE) for numerous languages is available from Wikipedia.

    • Integrated Development and Learning Environment (IDLE) supports 32- and 64-bit. It is available on many platforms. IDLE is the recommended tool to learn Python.
    • Geany operates in 32- or 64-bit and is available in 43 different languages. It runs on GNU/Linux, *BSD, macOS, AIX v5.3, Solaris Express and Windows. Geany is light, fits small projects and supports LibreOffice Python interpreter.
    • PyCharm (free edition) supports Gnu/Linux, macOS and Windows platforms. It is available as 32bits, and apparently accommodates 64bits too. Along with numerous features accompanying Python development, PyCharm holds a Python debugger that's compatible with LibreOffice.
    • Pyzo is available for Linux, OS X and Windows in 10 different languages. Multiple Python interpreters can be configured, be they 32bits or 64bits. Pyzo offers debugging facilities.

    Here's a list of features available from these IDEs, LibreOffice Basic IDE does not offer some of them.

    ソースコード・エクスプローラー、構文ハイライト

    Source exploration and syntax highlighting within IDLE, Geany and PyCharm are facilitating script edition. Geany and PyCharm support code folding. IDLE class browser does not support inner or embedded classes.

    コード補完

    Code completion assists the edition of Python scripts in IDLE, Geany and PyCharm.

    デバッグ

    Debugging chapter below goes into this subject in more details.

    コーディング規約 (PEP)

    PyCharm IDEでは、Python Enhancement Proposal (PEP)に準拠しているかチェックして表示できます。

    PyCharm コーディング規約アシスタント

    エディタの右側でPythonのコーディング規約と推奨事項が確認できます。これは経験の浅いプログラマーにとって便利な機能です。

    テスト駆動開発 (TDD) - 草稿

    </Unit testing>

    バージョン管理

    A source code local history comes with PyCharm as illustrated below:

    Source code updates local history

    Two copies of apso.py Python module are jointly displayed and respectively labelled v0.8.3 and v0.8.7. Version differences are precisely highlighted.

    PyCharm supports other version control solutions (VCS) such as Git, GitHub, Mercurial, Perforce or Subversion.

    デバッグ

    LibreOffice内部

    Xray - Methods of a Writer text object
    MRI - Properties, methods, services and interfaces for a Writer document
    Object Inspector - 'StarDesktop' properties, methods, supported services and exported interfaces

    One can edit and debug Python macros directly within LibreOffice with the help of Alternative Python Script Organizer extension. Managing libraries and modules is possible, as well as selecting your preferred editor without leaving LibreOffice.

    Developing out of LibreOffice is equally feasible, thus debugging becomes possible. Remote coding and testing using an Integrated Development Environment (IDE) brings more features detailed hereafter.

    Here are three extensions for programmers to benefit from in those two contexts. They can be used regardless of the programming language, be it LibreOffice Basic, Python, JavaScript or BeanShell. All three extend the API's introspection from LibreOffice suite.

    便利な拡張機能

    It is not always clear at design time which services a UNO object actually supports. However extensions that help the developer to inspect arbitrary UNO-Objects exist, but are not made available from the extensions' catalog, with the exception of MRI. They're built upon LibreOffice API reflection ability.

    • X-Ray inspects LibreOffice API objects. It displays the properties, methods, services, interfaces which are provided by an object variable. X-Ray is available in french, english, german, spanish, czech, polish and russian. X-Ray is written in Basic.
    • MRI (My Reflection and Introspection) is an introspection tool of UNO objects, written in Python. Its features are similar to that of X-Ray. MRI is available in english only. Note: Extensions' catalog MRI copy is outdated.
    • Object Inspector The Object Inspector extension displays the total capabilities of an UNO-object such as all supported services, exported interfaces, and their respective methods and properties in a TreeView window. The Object Inspector is written in Java and is available only in english.
    • APSO The Alternate Python Script Organizer extension nicely integrates objects inspection in its debugger. It uses either X-Ray either MRI.

    Pythonマクロの使用方法

    Python macros in LibreOffice are stored in numerous locations and come in varied species as explained in Python as a macro language. Scripts can be personal, shared, stored in extensions, integrated in packages or embedded in documents. This diversity imply different uses or constraints.

    • In a document each module is autonomous, no module import.
    Refer to Python import online/local help in order to circumvent this
    • Calling a Basic or Python extension from an embedded Python module is possible.
    • Python scripts in <user>\python\pythonpath can be imported by embedded modules or by <user>\python scripts.
    • No Basic support from an IDE: No X-Ray
    Basic presence is depending on the bridge type established with the IDE.
    • Python and Java are supported when invoked from an IDE: MRI, Object Inspector can be used.

    import uno
    def mri(target):
        ctx = uno.getComponentContext()
        mri = ctx.ServiceManager.createInstanceWithContext(
            "mytools.Mri",ctx)
        mri.inspect(target)
        
    if __name__ == '__main__':
        def Mri_test():
            document = XSCRIPTCONTEXT.getDocument()
            mri(document)
     
        Mri_test()

    Stopping a running macro with X-Ray :

    import uno
    from com.sun.star.uno import RuntimeException as _rtex
    
    def xray(myObject):
      try:
        sm = uno.getComponentContext().ServiceManager
        mspf = sm.createInstanceWithContext("com.sun.star.script.provider.MasterScriptProviderFactory", uno.getComponentContext())
        scriptPro = mspf.createScriptProvider("")
        xScript = scriptPro.getScript("vnd.sun.star.script:XrayTool._Main.Xray?language=Basic&location=application")
        xScript.invoke((myObject,), (), ())
        return
      except:
         raise _rtex("\n<span lang="en" dir="ltr" class="mw-content-ltr">Basic library Xray is not installed</span>", uno.getComponentContext())
    
    # ___________  <span lang="en" dir="ltr" class="mw-content-ltr">example of use</span>  _______________ 
    
    def demoXray(): 
      """ <span lang="en" dir="ltr" class="mw-content-ltr">example : using xray in a Writer document</span> """ 
      
      xTextDoc = XSCRIPTCONTEXT.getDocument() 
      xText = xTextDoc.Text 
      xray(xText)
      xray("<span lang="en" dir="ltr" class="mw-content-ltr">Demo is finished</span>") 
    
    g_exportedScripts = demoXray,

    Displaying UNO objets in a tree view using Object Inspector :

    import uno
    def inspectObject( obj, title="<span lang="en" dir="ltr" class="mw-content-ltr">Object Inspector</span>" ):
    	ctx = uno.getComponentContext()
    	oi = ctx.ServiceManager.createInstanceWithContext("org.openoffice.InstanceInspector", ctx)
    	if oi is None:  # <span lang="en" dir="ltr" class="mw-content-ltr">i.e. InstanceInspector is not installed or deactivated</span>
    		return  # <span lang="en" dir="ltr" class="mw-content-ltr">exit silently</span>
    	oi.inspect( obj, title )
    def exObjInspector():
    	doc = XSCRIPTCONTEXT.getDocument()
    	dsk = XSCRIPTCONTEXT.getDesktop()
    	inspectObject(doc)
    	inspectObject(dsk, title="StarDesktop")

    IDEからLibreOfficeのPythonインタープリターを使う

    IDEを使ってPythonマクロを開発するには、LibreOfficeに組み込まれているPythonインタプリタを利用する必要があります。ネイティブPythonには、UNOオブジェクトと互換性のないIDLEインタープリタが付属しています。Python IDEを使うと、クラスブラウザ、構文ハイライト、コード補完、コーディング規約準拠のチェック、テスト駆動開発、デバッグ、バージョン管理など、多くの機能を利用できます。

    LibreOfficeのPythonインタプリタをGeany、PyCharm、Pyzoに設定する方法は、Python IDEの基本設定Python IDE Basicsで解説しています。

    In order to execute a script from <user>\python or from <user>\python\pythonpath, a communication must be established between the IDE and LibreOffice. UNO objects are not reachable without such a bridge. Once a communication is in place, the IDE and LibreOffice operate together. The following links document that process:

    IDE_utils module borrows from these resources and provides LibreOffice Python macro simple enablement for IDEs.

    Pythonスクリプトの使用方法

    • ...Pythonパッケージの呼び出し...

    Geanyで外部から実行

    Geany initiates the opening of a window within LibreOffice. Geany EDI invokes info() function, which utilizes ..awt.createMessageBox API method defined in the SDK. The user script is named SysInfo.py.

    Geany executes info() function that calls ..awt.createMessageBox() API method defined in SDK - Script name is <user>\SysInfo.py

    PyZo上でのデバッグ

    PyUNO Workspace is an object introspection Pyzo IDE plugin for PyUNO and LibreOffice UNO API:

    Pyzo runs and stops into <user>\..\IDE_utils.py
    Pyzo runs and stops into <user>\..\IDE_utils.py

    PyCharmでのデバッグ

    PyCharm's debugger displays UNO objects, Python classes or objects:

    Watching UNO objects UNO, Python classes or variables

    APSO上でのデバッグ

    The Alternative Python Script Organizer extension allows step by step execution, as well as stack trace display and UNO objects introspection, with xRay or MRI.

    APSO debug window

    コンソールへの出力

    Python scripts can be prototyped by use of the Python shell and its Read Execute Print Loop (REPL) process. The Alternative Python Script Organizer integrates this facility, which is part of LibreOffice Python.
    APSO console

    Python対話モード

    The Python interactive console, also known as Python interpreter or Python shell, provides programmers with a quick way to execute commands and try out and test code without creating a file. UNO objects introspection as well as LibreOfficeDev Python modules documentation can be obtained from the terminal. LibreOffice online/local details how to run Python interactive console.
    Python shell

    Windows上のコンソール

    By default, there is no default stdout on Windows. What is sent by function “print” will not be visible anywhere. To get a console to be used as stdout:

    • Start LibreOffice using soffice.com instead of soffice.exe:

    Python scripts print() statements appear in the console until LibreOffice closes. In the absence of the console, print() statements are silent.

    LibreOffice 6.3から利用可能です。それ以前のリリースでは以下の手順を実行してください。

    1. LibreOfficeを閉じる。
    2. Visual Studio Express 2010 C++ (ほかのバージョンでもおそらく大丈夫でしょう)をダウンロードしてインストールする。
    3. Visual Studioのコンソールを開く。
    4. 以下を入力:

    editbin.exe /subsystem:console "C:\Program Files\LibreOffice 5\program\soffice.exe"
    editbin.exe /subsystem:console "C:\Program Files\LibreOffice 5\program\soffice.bin"

    cf. EditBin reference at TechNet

    Now, a console will be shown when you open LibreOffice. It will be the stdout for the “print” command. And you can get Python errors while LO is running if you use traceback.

    import traceback
    […]
    try:
        […]
        except:
            traceback.print_exc()

    But syntax errors still won’t be reported there.

    例外処理 - 草稿

    ダイアログの構築 - 草稿

    cf. UNODiT UNO Dialog Tools 始めるための参考文献を上げておきます:

    ダイアログの設計

    イベント駆動マクロ

    地域化

    ディスパッチャー・コマンド - 草稿

    Interface-oriented programming in *Office, Christopher Bourez (2015)

    拡張機能の作成 - 草稿

    拡張機能

    拡張機能の開発

    UNOコンポーネントパッケージング - Pythonコンポーネントテスト

    サービスの構築

    Calcアドインの構築

    構築と拡張機能

    その他 - 草稿

    ドキュメントモジュールのインポート

    cf. Pythonモジュールのインポート(オンラインヘルプから)

    PythonパッケージとLibreOffice拡張機能の比較

    (cf. french draft version up to now)

    静的プロパティまたはメソッド

    問: Pythonのグローバル属性の動作について教えてください。

    PyCharmでGitを使う - 草稿