Doc for call macros

This commit is contained in:
El Mau 2022-02-26 00:11:41 -06:00
parent 1557211070
commit 22ac697de1
3 changed files with 175 additions and 18 deletions

View File

@ -15,7 +15,9 @@
catch_exception catch_exception
create_instance create_instance
data_to_dict
debug debug
dict_to_property
error error
errorbox errorbox
get_app_config get_app_config
@ -23,6 +25,7 @@
mri mri
msgbox msgbox
question question
run_in_thread
save_log save_log
set_app_config set_app_config
sleep sleep
@ -37,8 +40,10 @@
.. autosummary:: .. autosummary::
Dates Dates
Json
LOServer LOServer
MBT MBT
Macro
MessageBoxType MessageBoxType
commands commands

View File

@ -303,13 +303,13 @@ Get star date in Calc configuration.
.. image:: _static/images/tools_22.png .. image:: _static/images/tools_22.png
Thread Thread
^^^^^^ ------
You can execute any macro in thread You can execute any macro in thread
* Normal execution Normal execution
^^^^^^^^^^^^^^^^
.. code-block:: python .. code-block:: python
@ -323,7 +323,8 @@ You can execute any macro in thread
app.msgbox('Finish...') app.msgbox('Finish...')
return return
* Run in thread Run in thread
^^^^^^^^^^^^^
.. code-block:: python .. code-block:: python
@ -339,8 +340,8 @@ You can execute any macro in thread
return return
Dictionary <-> properties Dictionary to/from Properties
^^^^^^^^^^^^^^^^^^^^^^^^^ -----------------------------
.. code-block:: python .. code-block:: python
@ -358,7 +359,7 @@ Dictionary <-> properties
Tuples or lists to dictionary Tuples or lists to dictionary
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -----------------------------
.. code-block:: python .. code-block:: python
@ -378,7 +379,10 @@ Tuples or lists to dictionary
Json Json
^^^^ ----
Dumps data
^^^^^^^^^^
.. code-block:: python .. code-block:: python
@ -387,19 +391,25 @@ Json
'Password': 'letmein', 'Password': 'letmein',
} }
json = app.json_dumps(data) json = app.json.dumps(data)
app.msgbox(json) app.msgbox(json)
data = app.json_loads(json)
Loads data
^^^^^^^^^^
.. code-block:: python
data = app.json.loads(json)
app.msgbox(data) app.msgbox(data)
Call Macros Call Macros
^^^^^^^^^^^ -----------
You can any macro, for default call macros Python. You can execute any macro, for default call macros Python.
.. code-block:: python .. code-block:: python

View File

@ -20,12 +20,14 @@
import datetime import datetime
import getpass import getpass
import json
import logging import logging
import os import os
import platform import platform
import socket import socket
import subprocess import subprocess
import sys import sys
import threading
import time import time
import traceback import traceback
@ -36,7 +38,7 @@ from typing import Any
import uno import uno
from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS
from com.sun.star.awt.MessageBoxResults import YES from com.sun.star.awt.MessageBoxResults import YES
from com.sun.star.beans import PropertyValue from com.sun.star.beans import PropertyValue, NamedValue
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s' LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
@ -389,13 +391,67 @@ def errorbox(message: Any, title: str=TITLE) -> int:
return msgbox(message, title, type_message_box=MessageBoxType.ERRORBOX) return msgbox(message, title, type_message_box=MessageBoxType.ERRORBOX)
def sleep(seconds): def sleep(seconds: int):
"""Sleep """Sleep
""" """
time.sleep(seconds) time.sleep(seconds)
return return
def run_in_thread(fn):
"""Run any function in thread
:param fn: Any Python function (macro)
:type fn: Function instance
"""
def run(*k, **kw):
t = threading.Thread(target=fn, args=k, kwargs=kw)
t.start()
return t
return run
def dict_to_property(values: dict, uno_any: bool=False):
"""Convert dictionary to array of PropertyValue
:param values: Dictionary of values
:type values: dict
:param uno_any: If return like array uno.Any
:type uno_any: bool
:return: Tuple of PropertyValue or array uno.Any
:rtype: tuples or uno.Any
"""
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 _property_to_dict(values):
d = {v.Name: v.Value for v in values}
return d
def data_to_dict(data) -> dict:
"""Convert tuples, list, PropertyValue, NamedValue to dictionary
:param data: Dictionary of values
:type data: array of tuples, list, PropertyValue or NamedValue
:return: Dictionary
:rtype: dict
"""
d = {}
if not isinstance(data, (tuple, list)):
return d
if isinstance(data[0], (tuple, list)):
d = {r[0]: r[1] for r in data}
elif isinstance(data[0], (PropertyValue, NamedValue)):
d = _property_to_dict(data)
return d
class _classproperty: class _classproperty:
def __init__(self, method=None): def __init__(self, method=None):
self.fget = method self.fget = method
@ -445,7 +501,7 @@ class Dates(object):
return e return e
@classmethod @classmethod
def date(cls, year, month, day): def date(cls, year: int, month: int, day: int):
"""Get date from year, month, day """Get date from year, month, day
:param year: Year of date :param year: Year of date
@ -463,7 +519,7 @@ class Dates(object):
return d return d
@classmethod @classmethod
def str_to_date(cls, str_date, template, to_calc=False): def str_to_date(cls, str_date: str, template: str, to_calc: bool=False):
"""Get date from string """Get date from string
:param str_date: Date in string :param str_date: Date in string
@ -483,7 +539,7 @@ class Dates(object):
return d return d
@classmethod @classmethod
def calc_to_date(cls, value): def calc_to_date(cls, value: float):
"""Get date from calc value """Get date from calc value
:param value: Float value from cell :param value: Float value from cell
@ -522,9 +578,95 @@ class Dates(object):
return result return result
class Json(object):
"""Class for json data
"""
@classmethod
def dumps(cls, data: Any) -> str:
"""Dumps
:param data: Any data
:type data: Any
:return: Return string json
:rtype: str
"""
return json.dumps(data, indent=4, sort_keys=True)
@classmethod
def loads(cls, data: str) -> Any:
"""Loads
:param data: String data
:type data: str
:return: Return any object
:rtype: Any
"""
return json.loads(data)
class Macro(object):
"""Class for call macro
`See Scripting Framework <https://wiki.openoffice.org/wiki/Documentation/DevGuide/Scripting/Scripting_Framework_URI_Specification>`_
"""
@classmethod
def call(cls, args: dict, in_thread: bool=False):
"""Call any macro
:param args: Dictionary with macro location
:type args: dict
:param in_thread: If execute in thread
:type in_thread: bool
:return: Return None or result of call macro
:rtype: Any
"""
result = None
if in_thread:
t = threading.Thread(target=cls._call, args=(args,))
t.start()
else:
result = cls._call(args)
return result
@classmethod
def _get_url_script(cls, args: dict):
library = args['library']
name = args['name']
language = args.get('language', 'Python')
location = args.get('location', 'user')
module = args.get('module', '.')
if language == 'Python':
module = '.py$'
elif language == 'Basic':
module = f".{module}."
if location == 'user':
location = 'application'
url = 'vnd.sun.star.script'
url = f'{url}:{library}{module}{name}?language={language}&location={location}'
return url
@classmethod
def _call(cls, args: dict):
url = cls._get_url_script(args)
args = args.get('args', ())
service = 'com.sun.star.script.provider.MasterScriptProviderFactory'
factory = create_instance(service)
script = factory.createScriptProvider('').getScript(url)
result = script.invoke(args, None, None)[0]
return result
def __getattr__(name): def __getattr__(name):
classes = { classes = {
'dates': Dates 'dates': Dates,
'json': Json,
'macro': Macro,
} }
if name in classes: if name in classes:
return classes[name] return classes[name]