New class for cell ranges

This commit is contained in:
Mauricio Baeza 2019-09-08 00:25:30 -05:00
parent 5b2870cc30
commit 9f6868e91b
2 changed files with 160 additions and 2 deletions

View File

@ -169,11 +169,17 @@ URL_OXT = ''
# ~ PATH_DEV = '-env:UserInstallation=file:///home/mau/.temp/develop' # ~ PATH_DEV = '-env:UserInstallation=file:///home/mau/.temp/develop'
# ~ unopkg not support (or I not know how) other user profile # ~ unopkg not support (or I not know how) other user profile
PATH_DEV = '' PATH_DEV = ''
# ~ Default program for test: --calc, --writer, --draw
PROGRAM = '--calc'
# ~ Path to file for test
FILE_TEST = ''
PATHS = { PATHS = {
'idlc': '/usr/lib/libreoffice/sdk/bin/idlc', 'idlc': '/usr/lib/libreoffice/sdk/bin/idlc',
'include': '/usr/share/idl/libreoffice', 'include': '/usr/share/idl/libreoffice',
'regmerge': '/usr/lib/libreoffice/program/regmerge', 'regmerge': '/usr/lib/libreoffice/program/regmerge',
'soffice': ('soffice', '--calc'), 'soffice': ('soffice', PROGRAM, FILE_TEST),
'install': ('unopkg', 'add', '-v', '-f', '-s'), 'install': ('unopkg', 'add', '-v', '-f', '-s'),
} }

View File

@ -22,6 +22,7 @@ import getpass
import logging import logging
import platform import platform
import sys import sys
import tempfile
import threading import threading
import time import time
from functools import wraps from functools import wraps
@ -31,6 +32,9 @@ import uno
from com.sun.star.beans import PropertyValue from com.sun.star.beans import PropertyValue
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.awt.PosSize import POSSIZE, SIZE
from com.sun.star.awt import Size
from com.sun.star.table.CellContentType import EMPTY, VALUE, TEXT, FORMULA
FILE_NAME_DEBUG = 'debug.log' FILE_NAME_DEBUG = 'debug.log'
@ -44,13 +48,20 @@ MSG_LANG = {
FORMAT = '%(asctime)s - %(levelname)s - %(message)s' FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
DATE = '%d/%m/%Y %H:%M:%S' DATE = '%d/%m/%Y %H:%M:%S'
LEVEL_ERROR = logging.getLevelName(logging.ERROR) LEVEL_ERROR = logging.getLevelName(logging.ERROR)
LEVEL_DEBUG = logging.getLevelName(logging.DEBUG)
LEVEL_INFO = logging.getLevelName(logging.INFO) LEVEL_INFO = logging.getLevelName(logging.INFO)
logging.addLevelName(logging.ERROR, f'\033[1;41m{LEVEL_ERROR}\033[1;0m') logging.addLevelName(logging.ERROR, f'\033[1;41m{LEVEL_ERROR}\033[1;0m')
logging.addLevelName(logging.DEBUG, f'\x1b[33m{LEVEL_DEBUG}\033[1;0m')
logging.addLevelName(logging.INFO, f'\x1b[32m{LEVEL_INFO}\033[1;0m') logging.addLevelName(logging.INFO, f'\x1b[32m{LEVEL_INFO}\033[1;0m')
logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE) logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE)
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
OBJ_CELL = 'ScCellObj'
OBJ_RANGE = 'ScCellRangeObj'
OBJ_RANGES = 'ScCellRangesObj'
CTX = uno.getComponentContext() CTX = uno.getComponentContext()
SM = CTX.getServiceManager() SM = CTX.getServiceManager()
@ -102,6 +113,16 @@ def mri(obj):
return return
def debug(info):
log.debug(info)
return
def error(info):
log.error(info)
return
def catch_exception(f): def catch_exception(f):
@wraps(f) @wraps(f)
def func(*args, **kwargs): def func(*args, **kwargs):
@ -151,6 +172,137 @@ def warning(message, title=TITLE):
return msgbox(message, title, type_msg='warningbox') return msgbox(message, title, type_msg='warningbox')
def error(message, title=TITLE): def errorbox(message, title=TITLE):
return msgbox(message, title, type_msg='errorbox') return msgbox(message, title, type_msg='errorbox')
def get_temp_file():
return tempfile.NamedTemporaryFile()
def _path_url(path):
if path.startswith('file://'):
return path
return uno.systemPathToFileUrl(path)
# ~ Custom classes
class LOCellRange(object):
def __init__(self, obj):
self._obj = obj
self._init_values()
def __enter__(self):
return self
def __exit__(self, *args):
pass
def _init_values(self):
self._type_obj = self._obj.ImplementationName
self._type_content = EMPTY
if self._type_obj == OBJ_CELL:
self._type_content = self._obj.getType()
return
@property
def obj(self):
return self._obj
@property
def type_content(self):
return self._type_content
@property
def value(self):
v = None
if self._type_content == VALUE:
v = self.obj.getValue()
elif self._type_content == TEXT:
v = self.obj.getString()
elif self._type_content == FORMULA:
v = self.obj.getFormula()
return v
@value.setter
def value(self, data):
if isinstance(data, str):
if data.startswith('='):
self.obj.setFormula(data)
else:
self.obj.setString(data)
elif isinstance(data, (int, float)):
self.obj.setValue(data)
def offset(self, col=1, row=0):
a = self.address
col = a.Column + col
row = a.Row + row
return LOCellRange(self.obj.Spreadsheet[row,col])
@property
def sheet(self):
return self.obj.Spreadsheet
@property
def draw_page(self):
return self.sheet.getDrawPage()
@property
def name(self):
return self.obj.AbsoluteName
@property
def address(self):
if self._type_obj == OBJ_CELL:
a = self.obj.getCellAddress()
elif self._type_obj == OBJ_RANGE:
a = self.obj.getRangeAddress()
else:
a = self.obj.getRangeAddressesAsString()
return a
def add_image(self, path, **kwargs):
s = self.obj.Size
w = kwargs.get('width', s.Width)
h = kwargs.get('Height', s.Height)
doc = get_document()
img = doc.createInstance('com.sun.star.drawing.GraphicObjectShape')
img.GraphicURL = _path_url(path)
self.draw_page.add(img)
img.Anchor = self.obj
img.setSize(Size(w, h))
return
# ~ Python >= 3.7
# ~ def __getattr__(name):
def get_document():
doc = None
try:
doc = DESKTOP.getCurrentComponent()
except Exception as e:
log.error(e)
return doc
def get_selection():
obj = None
try:
obj = get_document().getCurrentSelection()
except Exception as e:
log.error(e)
return obj
def get_cell(*args):
sel = get_selection()
if sel.ImplementationName == OBJ_RANGE:
sel = sel[0,0]
elif sel.ImplementationName == OBJ_RANGES:
sel = sel[0][0,0]
return LOCellRange(sel)