Transfert de Basic à Python

From Apache OpenOffice Wiki
< FR‎ | Documentation
Revision as of 17:57, 15 December 2016 by Jeanmi2403 (Talk | contribs)

Jump to: navigation, search
En cours de traduction

Translation Español

Si vous ressentez un certain mécontentement/manque avec OpenOffice Basic ou si vous souhaitez créer des composants UNO personnalisés, il est maintenant temps de transférer l'environnement de codage de Basic vers Python.

En Basic, le cadre d'exécution fournit des procédures/fonctions pour faire un certain nombre de choses. Mais en utilisant la passerelle Python-UNO , vous devrez faire cette tâche par des moyens API.

Commençons par le didacticiel Python et revenons à ce chapitre lorsque vous avez appris un peu sur le langage Python.

Emplacement des macros

Sur la version actuelle, l'organisateur de script pour Python ne fournit pas d'outil pour gérer les fichiers de script. Donc vous devez les gérer vous-même (où avec l'extension apso ). Les macros écrites en Python doivent être placées dans le répertoire spécifique sous le profil de votre utilisateur, le profil partagé ou le répertoire de script de votre document.

Le répertoire python (en minuscules) doit être créé dans le répertoire Scripts et vous pouvez y mettre vos scripts python contenant le code python.

chemin utilisateur /Scripts/python/votre_fichiere.py

Vous pouvez créer des sous-répertoires pour y mettre des fichiers de macro sous le répertoire Scripts / python

Vous devez ajouter l'extension de fichier "py" à votre nom de fichier.

Editeur Macro

Il n'existe pas d'éditeur intégré dédié au code en Python. Mais vous pouvez choisir votre éditeur de texte préféré pour modifier vos scripts Python.

Ceci est discuté dans une autre page.

Un court exemple

Voici un petit exemple écrit en Python.

def hello():
    XSCRIPTCONTEXT.getDocument().getText().setString("Bonjour !")

Chaque fonction appelable est une unité exécutable de la macro Python (vous pouvez choisir quelle fonction doit être listée dans l'interface graphique, voir autre document).

Vous pouvez accéder au document en cours via la méthode getDocument de la variable XSCRIPTCONTEXT du module. Cette macro change le contenu du document Writer à "Bonjour!" .

Utiliser des modules

 import uno
 
 import unohelper

Contexte de script

OoBasic est un runtime embarqué et il fonctionne toujours avec l'instance active du bureau. Donc le contexte est toujours couplé avec celui du bureau. Mais la passerelle Python-UNO fournit la façon de travailler en tant que client RPC (Remote Procedure Call). À ce moment, l'instance distante de Python a un contexte différent de l'instance de bureau. Par conséquent, vous devez utiliser le contexte de composant correct pour indiquer à la fabrique de composants multiples d'instancier un service.

Dans OoBasic, aucun objet correspondant n'a été fourni.

En macro Python,vous devez utiliser la variable de module XSCRIPTCONTEXT qui fournit l'interface com.sun.star.script.provider.XScriptContext.

Renvoie l'objet Document.
Renvoie l'objet dépendant de l'invocation.
Renvoie une instance du service com.sun.star.frame.Desktop.
Retourne le contexte de composant courant qui est utilisé pour indiquer le contexte.

Garder en tête que la variable XSCRIPTCONTEXT est définie au niveau du module et n'est pas fournie aux modules importés depuis votre script.

Contexte de composant

En OoBasic, vous pouvez obtenir le contexte de composant comme suit:

 ctx = GetDefaultContext()

Mais vous n'avez pas besoin d'y accéder jusqu'à ce que vous ayez besoin d'obtenir des singletons.

En Python, vous pouvez accéder au contexte du composant à travers le contexte du script.

 ctx = XSCRIPTCONTEXT.getComponentContext()

Vous avez besoin de cette valeur pour instancier les services.

Gestionnaire de services

En OoBasic, vous pouvez obtenir le gestionnaire de services comme suit:

 smgr = GetProcessServiceManager()

Mais peu de gens y ont accès.

En Python, cette instance est la valeur la plus importante pour instancier les services et travailler avec les API du bureau.

 ctx = XSCRIPTCONTEXT.getComponentContext()
 smgr = ctx.getServiceManager()

Vous avez besoin à la fois du contexte des composants et du gestionnaire de services pour instancier les services.

Instance de service

En OoBasic, vous pouvez instancier les services par fonction intégrée comme suit:

 sfa = CreateUnoService("com.sun.star.ucb.SimpleFileAccess")

ou avec les arguments d'initialisation:

 arg = com.sun.star.ui.dialogs.TemplateDescription.FILESAVE_SIMPLE
 file_picker = CreateUnoServiceWithArguments("com.sun.star.ui.dialogs.FilePicker", Array(arg))


IEn Python, vous devez travailler avec l'interface com.sun.star.lang.XMultiComponentFactory comme suit:

 ctx = XSCRIPTCONTEXT.getComponentContext()
 smgr = ctx.getServiceManager()
 sfa = smgr.createInstanceWithContext("com.sun.star.ucb.SimpleFileAccess", ctx)

Si vous devez initialiser l'instance, utilisez la méthode createInstanceWithArgumentsAndContext:

 from com.sun.star.ui.dialogs.TemplateDescription import FILESAVE_SIMPLE
 file_picker = smgr.createInstanceWithArgumentsAndContext("com.sun.star.ui.dialogs.FilePicker", (FILESAVE_SIMPLE,) ctx)

Ou initialiser après l'instanciation:

 file_picker = smgr.createInstanceWithContext("com.sun.star.ui.dialogs.FilePicker", ctx)
 file_picker.initialize((FILESAVE_SIMPLE,))

Service avec Constructeur

En OoBasic, vous pouvez appeler la construction de service à partir de son module:

 shell_execute = com.sun.star.system.SystemShellExecute.create()

Dans Python, vous devez l'instancier avec la méthode XMultiComponentFactory::createInstanceWithArgumentsAndContext avec des arguments initiaux ou affecter après l'instanciation.

L'appel du constructeur effectue la vérification de type avant de passer les arguments à la méthode createInstanceWithArgumentsAndContext.

Document en cours

En OoBasic, la fonction d'exécution ThisComponent fournit l'accès au document courant:

 doc = ThisComponent

Sa valeur de retour est liée à l'emplacement de macro. Si la macro stockée dans un document, le résultat de ThisComponent est le document auquel le stockage de la macro appartient. Et si votre macro est stockée dans l'application (au sens large, la valeur renvoyée est le modèle de document de la trame actuellement active, c'est le même résultat issu de StarDesktop. GetCurrentComponent (). En Python, vous pouvez accéder au document actuel à travers le contexte du script:

 doc = XSCRIPTCONTEXT.getDocument()

Si votre macro est incorporée dans le document, le modèle de document correspond au document dans lequel la macro est stockée. Si votre macro est stockée dans l'espace utilisateur ou l'emplacement partagé, l'objet de document vient du cadre actif.

Bureau (Desktop)

En OoBasic, la fonction runtime StarDesktop est fournie:

 desktop = StarDesktop()

En Python, Vous pouvez accéder au bureau via le contexte du script:

 desktop = XSCRIPTCONTEXT.getDesktop()

Instance de Structure

En Basic, l'instance de struct peut être instanciée de deux façons:

 Dim a As New com.sun.star.awt.Point
 a = CreateUnoStruct("com.sun.star.awt.Point")

Avec l'instruction Dim et le nouveau mot-clé, vous pouvez instancier une structure ou un tableau de structures. Ou la méthode CreateUnoStruct fournit la manière d'instancier une structure au moment de l'exécution. Vous ne pouvez pas initialiser l'instance lors de la création, vous devez définir la valeur de ses membres.

En Python, vous pouvez utiliser les méthodes suivantes pour instancier une structure. Importer la classe struct et l'appeler.

 from com.sun.star.awt import Point
 
 a = Point()         # Instancie avec les valeurs par défaut, X=0, Y=0
 b = Point(100, 200) # Initialiser avec les valeurs initiales, X=100, Y=200

En appelant la classe pour créer une nouvelle instance de la structure, vous pouvez vider ses arguments, ou bien vous devez passer des valeurs pour tous les champs. En d'autres termes, vous ne pouvez pas passer un nombre insuffisant d'arguments à initialiser. Et son ordre doit correspondre à la définition de la structure dans son IDL. Par exemple, instance de struct b ayant X = 100 et Y = 200 dans le code ci-dessus.

Vous pouvez initialiser sans importer la classe de votre structure cible avec la fonction uno.createUnoStruct comme suit:

 import uno
 
 a = uno.createUnoStruct("com.sun.star.awt.Point")
 b = uno.createUnoStruct("com.sun.star.awt.Point", 100, 200)

Cela donne le même résultat avec l'exemple ci-dessus. Le premier paramètre de la méthode createUnoStruct est le nom de la structure à initialiser. Les arguments suivants sont des valeurs initiales pour la nouvelle instance.

Enum

In Basic, you can access to the module of the enum as follows:

 ITALIC = com.sun.star.awt.FontSlant.ITALIC

In Python, the following ways can be used:

 import uno
 
 from com.sun.star.awt.FontSlant import ITALIC
 ITALIC = uno.getConstantByName("com.sun.star.awt.FontSlant.ITALIC")
 ITALIC = uno.Enum("com.sun.star.awt.FontSlant", "ITALIC")

All of the way results the instance of uno.Enum class.

Constants

In StarBasic, you can get access to constants through its module:

 BOLD = com.sun.star.awt.FontWeight.BOLD

In Python, the following ways are provided:

 import uno
 
 from com.sun.star.awt.FontWeight import BOLD
 BOLD = uno.getConstantsByName("com.sun.star.awt.FontWeight.BOLD")

Sequence

The sequence is sequential value of the same type.

In StarBasic, array is used.

In Python, tuple is chosen to represent UNO's sequence. Note, list is not allowed to pass as sequence value.

Boolean

In Python, True or False.

String

Python's string can contain over 64K bytes.

If you have to write non Ascii 7 bit characters in your script, write magic comment at the head of your file. This is standard Python instructions.

 # -*- coding: utf_8 -*-

Please read Python's documentation for more detail.

You have to use unicode string to write some unicode characters in Python 2.X. And strings coming from UNO is decoded in unicode in Python 2.X.

Char

There is no dedicated value for char type in StarBasic.

In Python, uno.Char class is defined for char type.

 import uno
 c = uno.Char("a")

Type

"Type" type is meta type of UNO that represents type of UNO. Since 3.4, if you pass string value to method as an argument that should be type, the bridge of Basic read it as type.

oMap = com.sun.star.container.EnumerableMap.create("string", "string")

In Python, the following ways can be used to create new valu of type.

 import uno
 t = uno.getTypeByName("string")
 t = uno.Type("string", uno.Enum("com.sun.star.uno.TypeClass", "STRING"))

Byte Sequence

The byte sequence is sequence of byte type.

In Basic, array of byte is used to represent it.

In Python, it is represented by str wrapped by uno.ByteSequence class. If you takes some byte sequences from UNO, they are the instance of uno.ByteSequence. If you need to get real value of them, refer its value instance variable.

Exception

In StarBasic, you get thrown exception as some error. And On Error statement is used to catch it.

 Sub ErrorExample
 
   On Error GoTo Handler
 
   ' ... error
 
   Exit Sub
 
   Handler: 
 
 End Sub

And you can not throw any exceptions from StarBasic.

In Python, the exception thrown in UNO world can be treated as normal Python's exception. Here is an example:

 from com.sun.star.container import IndexOutOfBoundsException
 
 try:
     obj.getByIndex(100) # raises IndexOutOfBoundsException
 except IndexOutOfBoundsException as e:
     print(e)

If getByIndex method raises IndexOutOfBoundsException, it can be caught in except statement because all exceptions inherit Python's Exception class.

And also you can throw UNO's exception from your Python code as follows:

 from com.sun.star.uno import RuntimeException
 raise RuntimeException("Some message", None)


Empty Value

In Basic, there are some situations to meet variables that they do not contain any value (this is not correct). Null, empty, missing, nothing and so on.

In Python, None is used. If a method defined as void return value in its IDL, it results None if you call it. If you need to pass invalid interface as an argument for the method that takes some interface, pass None for it. The result of this behavior is fully dependent to the implementation of the method.

Listener and Interface

In StarBasic, you can create new listener using CreateUnoListener runtime function with some subroutines or functions.

 Sub Add
 
   d = CreateUnoDialog(DialogLibraries.Standard.Dialog1)
   listener = CreateUnoListener("ActionListener", "com.sun.star.awt.XActionListener")
   d.getControl("CommandButton1").addActionListener(listener)
   d.execute()
   d.dispose()
 
 End Sub
 
 
 Sub ActionListener_actionPerformed(ev)
 
 End Sub
 
 Sub ActionListener_disposing(ev)
 
 End Sub

In Python, you have to define your own class with desired interfaces. With helper class, you can define easily as follows:

 import unohelper
 
 from com.sun.star.awt import XActionListener
 
 class ActionListener(unohelper.Base, XActionListener):
     def __init__(self):
         pass
 
     def disposing(self, ev):
         pass
 
     def actionPerformed(self, ev):
         pass

unohelper.Base class provides required interface for UNO components.

Containers

In StarBasic, container object provides the way to access to its contents in sequentially.

In Python, there is no shortcut provided.

If you need to access to elements of indexed container, use range function to generate sequential indexes.

 for i in range(container.getCount()):
     obj = container.getByIndex(i)

URL and System Path

If you work with a file stored in your local file system, you have to get its corresponding URL.

In StarBasic, ConvertToURL runtime function is prepared for this task. And there is ConvertFromURL runtime function for reverse conversion.

In Python, the following functions are defined in uno module for such task.

 import uno
 
 path = "/home/foo/Documents/file.odt"
 url = uno.systemPathToFileUrl(path)
 path = uno.fileUrlToSystemPath(url)

Arguments and Return Value

In StarBasic, mode of the first argument of parseStrict method is "inout" in the following code:

 aURL = CreateUnoStruct("com.sun.star.util.URL")
 aURL.Complete = ".uno:Paste"
 CreateUnoService("com.sun.star.util.URLTransformer").parseStrict(aURL)

The content of aURL variable is updated after calling the method.

In Python, out mode parameter is returned as part of return value.

 from com.sun.star.util import URL
 
 aURL = URL()
 aURL.Complete = ".uno:Paste"
 dummy, aURL = smgr.createInstanceWithContext("com.sun.star.util.URLTransformer", ctx).parseStrict(aURL)
 # Definition of com.sun.star.util.XURLTransformer::parseStrict method: 
 # void parseStrict([inout] com.sun.star.util.URL aURL);

If a method has out mode in its parameters, its return is always tuple that contains original return value and values for out parameters.

Here is a potential example:

 # boolean getSomeValue([in] string aName, [out] short aNum, [inout] long aNum2);
 result, num, num2 = obj.getSomeValue("foo", 100, 200)

In the above example, result variable takes original return value, num takes output value for second parameter and num2 takes output value for third parameter. The method takes 100 as the second parameter but it is not used as input of value. No entry in returned tuple for in mode parameter.

Functions to be Executed

In Basic, you can not choose routines to be executed by users.

In Python, define g_exportedScripts variable that contains tuple of callable in your macro file.

 def func_a(): pass
 def func_b(): pass
 def func_hidden(): pass # not shown in the UI
 
 g_exportedScripts = func_a, func_b

In the above code, func_hidden is not shown in execution dialog of macros.

Importing Modules

In Basic, you can call subroutines defined in other modules or other libraries that has been loaded.

BasicLibraries.loadLibrary("Library1")
Library1.Foo()

In Python, you can import some modules that can be found in sys.path list. If you want to import your own module placed inside Scripts/python directory, put your module in pythonpath directory nearby your script file.

 - Scripts/
   - python/
     - macro.py
     - pythonpath/  # this directory is added automatically before your macro executed
       - your_module.py  # this module can be found

When you execute the macro from your script file, the internal executor adds the pythonpath/ directory to sys.path list to be used as one of lookup location.

Please keep in mind, the name of module conflict each other if you have the same named module in the some location, this is the standard python mechanism of importing modules, put your each modules in differently named library to avoid the name conflict.

Dialog

In Basic, there is CreateUnoDialog runtime function to instantiate the dialog.

 DialogLibraries.loadLibrary("Standard")
 dialog = CreateUnoDialog(DialogLibraries.Standard.Dialog1)
 dialog.execute()
 dialog.dispose()

In Python, such shortcut function is not provided but you can easily instantiate your dialog using com.sun.star.awt.DialogProvider service.

 def dialog_example():
     ctx = XSCRIPTCONTEXT.getComponentContext()
     smgr = ctx.getServiceManager()
     dp = smgr.createInstanceWithContext("com.sun.star.awt.DialogProvider", ctx)
     dialog = dp.createDialog("vnd.sun.star.script:Standard.Dialog1?location=user")
     dialog.execute()
     dialog.dispose()

Message Box

In Basic, you can use MsgBox runtime function to show some message to the users.

  Msgbox "Hello."

In Python, no shortcut function is provided but you can use com.sun.star.awt.XMessageBoxFactory interface through the toolkit.

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

Input Box

No function provided for Python, you have to make your own one. Here is an example:

def inputbox(message, title="", default="", x=None, y=None):
    """ Shows dialog with input box.
        @param message message to show on the dialog
        @param title window title
        @param default default value
        @param x dialog positio in twips, pass y also
        @param y dialog position in twips, pass y also
        @return string if OK button pushed, otherwise zero length string
    """
    WIDTH = 600
    HORI_MARGIN = VERT_MARGIN = 8
    BUTTON_WIDTH = 100
    BUTTON_HEIGHT = 26
    HORI_SEP = VERT_SEP = 8
    LABEL_HEIGHT = BUTTON_HEIGHT * 2 + 5
    EDIT_HEIGHT = 24
    HEIGHT = VERT_MARGIN * 2 + LABEL_HEIGHT + VERT_SEP + EDIT_HEIGHT
    import uno
    from com.sun.star.awt.PosSize import POS, SIZE, POSSIZE
    from com.sun.star.awt.PushButtonType import OK, CANCEL
    from com.sun.star.util.MeasureUnit import TWIP
    ctx = uno.getComponentContext()
    def create(name):
        return ctx.getServiceManager().createInstanceWithContext(name, ctx)
    dialog = create("com.sun.star.awt.UnoControlDialog")
    dialog_model = create("com.sun.star.awt.UnoControlDialogModel")
    dialog.setModel(dialog_model)
    dialog.setVisible(False)
    dialog.setTitle(title)
    dialog.setPosSize(0, 0, WIDTH, HEIGHT, SIZE)
    def add(name, type, x_, y_, width_, height_, props):
        model = dialog_model.createInstance("com.sun.star.awt.UnoControl" + type + "Model")
        dialog_model.insertByName(name, model)
        control = dialog.getControl(name)
        control.setPosSize(x_, y_, width_, height_, POSSIZE)
        for key, value in props.items():
            setattr(model, key, value)
    label_width = WIDTH - BUTTON_WIDTH - HORI_SEP - HORI_MARGIN * 2
    add("label", "FixedText", HORI_MARGIN, VERT_MARGIN, label_width, LABEL_HEIGHT, 
        {"Label": str(message), "NoLabel": True})
    add("btn_ok", "Button", HORI_MARGIN + label_width + HORI_SEP, VERT_MARGIN, 
            BUTTON_WIDTH, BUTTON_HEIGHT, {"PushButtonType": OK, "DefaultButton": True})
    add("btn_cancel", "Button", HORI_MARGIN + label_width + HORI_SEP, VERT_MARGIN + BUTTON_HEIGHT + 5, 
            BUTTON_WIDTH, BUTTON_HEIGHT, {"PushButtonType": CANCEL})
    add("edit", "Edit", HORI_MARGIN, LABEL_HEIGHT + VERT_MARGIN + VERT_SEP, 
            WIDTH - HORI_MARGIN * 2, EDIT_HEIGHT, {"Text": str(default)})
    frame = create("com.sun.star.frame.Desktop").getCurrentFrame()
    window = frame.getContainerWindow() if frame else None
    dialog.createPeer(create("com.sun.star.awt.Toolkit"), window)
    if not x is None and not y is None:
        ps = dialog.convertSizeToPixel(uno.createUnoStruct("com.sun.star.awt.Size", x, y), TWIP)
        _x, _y = ps.Width, ps.Height
    elif window:
        ps = window.getPosSize()
        _x = ps.Width / 2 - WIDTH / 2
        _y = ps.Height / 2 - HEIGHT / 2
    dialog.setPosSize(_x, _y, 0, 0, POS)
    edit = dialog.getControl("edit")
    edit.setSelection(uno.createUnoStruct("com.sun.star.awt.Selection", 0, len(str(default))))
    edit.setFocus()
    ret = edit.getModel().Text if dialog.execute() else ""
    dialog.dispose()
    return ret

This function can be called as follows:

inputbox("Please input some value", "Input", "Default value")

Executing Macros from Toolbar Buttons

In Basic, you can call any subroutines or functions through toolbar buttons.

Sub WriteHello()
  ThisComponent.getText().getEnd().setString("Hello!")
End Sub

In Python, you have to define your Python function with an argument (or variable length arguments) to take an argument passed when the function executed through assigned toolbar button.

def writeHello(*args):
    # writeHello(arg): is also ok but if you want to call this function 
    # by some ways, define your function takes variable arguments.
    XSCRIPTCONTEXT.getDocument().getText().getEnd().setString("Hello!")
Personal tools