Add get/set original properties

This commit is contained in:
El Mau 2023-12-29 16:36:40 -06:00
parent 5a02f50cc6
commit 74a781044c
8 changed files with 214 additions and 76 deletions

View File

@ -1,13 +1,13 @@
!!! tip "Atención"
!!! tip "Attention"
La fecha inicial en Calc y en Python son diferentes.
Start date in Calc and Python are different.
<br>
### **today**
Obtener la fecha actual.
Get current date.
```py
d = app.dates
@ -18,7 +18,7 @@ Obtener la fecha actual.
### **now**
Obtener la fecha y hora actuales.
Get current date and time.
```py
d = app.dates
@ -29,7 +29,7 @@ Obtener la fecha y hora actuales.
### **time**
Obtener la hora actual.
Get current time.
```py
d = app.dates
@ -40,7 +40,7 @@ Obtener la hora actual.
### **epoch**
Obtener el [tiempo Unix][1]
Get [Unix time][1]
```py
d = app.dates
@ -51,7 +51,7 @@ Obtener el [tiempo Unix][1]
### **date**
Devolver una fecha
Get a date.
```py
d = app.dates
@ -64,7 +64,7 @@ Devolver una fecha
### **time**
Devolver una hora
Get a time.
```py
d = app.dates
@ -77,7 +77,7 @@ Devolver una hora
### **datetime**
Devolver fecha y hora
Get date and time.
```py
d = app.dates
@ -90,67 +90,68 @@ Devolver fecha y hora
### **str_to_date**
Convertir una cadena en fecha. Mira este [excelente recurso][2]
String to date. Look this [excellent info][2]
```py
d = app.dates
cadena = '1974-01-15'
plantilla = '%Y-%m-%d'
fecha = d.str_to_date(cadena, plantilla)
app.msgbox(fecha)
app.msgbox(type(fecha))
str_date = '1974-01-15'
template = '%Y-%m-%d'
obj_date = d.str_to_date(str_date, template)
app.msgbox(obj_date)
app.msgbox(type(obj_date))
```
Para obtener un valor válido para establecer en una celda de Calc.
Get a valid date for insert in a Calc cell.
```py
d = app.dates
cadena = '1974-01-15'
plantilla = '%Y-%m-%d'
fecha = d.str_to_date(cadena, plantilla, True)
app.msgbox(fecha)
app.msgbox(type(fecha))
str_date = '1974-01-15'
template = '%Y-%m-%d'
obj_date = d.str_to_date(str_date, template, True)
app.msgbox(obj_date)
app.msgbox(type(obj_date))
```
<br>
### **calc_to_date**
Convierte el valor de una celda en una fecha Python, por ejemplo, la fecha inicial configurada en Calc.
Converts a value to Python date, for example, the initial date set in Calc.
```py
d = app.dates
valor_en_celda = 0
fecha = d.calc_to_date(valor_en_celda)
app.msgbox(fecha)
app.msgbox(type(fecha))
value = 0
obj_date = d.calc_to_date(value)
app.msgbox(obj_date)
app.msgbox(type(obj_date))
```
<br>
### **sleep**
Pausar la ejecución por X segundos.
Pause execution for X seconds.
!!! tip inline end "Atención"
!!! tip inline end "Attention"
La pausa es bloqueante.
The pause is blocking.
```py
d = app.dates
app.sleep(3)
app.msgbox('Fin')
app.msgbox('End')
```
<br>
### **start** y **end**
### **start** and **end**
Medir tiempo en segundos.
Measure time in seconds.
```py
d = app.dates
@ -161,7 +162,7 @@ Medir tiempo en segundos.
app.msgbox(seconds)
```
Regresar timedelta en vez de segundos.
Get timedelta instead of seconds
```py
d = app.dates
@ -173,5 +174,5 @@ Regresar timedelta en vez de segundos.
```
[1]: https://es.wikipedia.org/wiki/Tiempo_Unix
[1]: https://en.wikipedia.org/wiki/Unix_time
[2]: https://strftime.org

View File

@ -330,6 +330,10 @@ class LODocument(BaseObject):
def replace_ext(self, new_ext):
return Paths.with_suffix(self.path, new_ext)
def deselect(self):
LOMain.dispatch(self.frame, 'Deselect')
return
class LODrawImpress(LODocument):

View File

@ -2,6 +2,7 @@
from .easydoc import LODrawImpress
from .easydrawpage import LODrawPage
from .easymain import LOMain
class LODraw(LODrawImpress):
@ -17,3 +18,13 @@ class LODraw(LODrawImpress):
page = self.obj.DrawPages.getByName(index)
return LODrawPage(page)
@property
def active(self):
"""Get active page"""
return LODrawPage(self._cc.CurrentPage)
def paste(self):
"""Paste"""
LOMain.dispatch(self.frame, 'Paste')
return

View File

@ -146,6 +146,12 @@ class LODrawPage(BaseObject):
break
return result
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __len__(self):
"""Count shapes"""
return self.count
@ -177,6 +183,13 @@ class LODrawPage(BaseObject):
def _create_instance(self, name):
return self.doc.createInstance(name)
def select(self, shape):
if hasattr(shape, 'obj'):
shape = shape.obj
controller = self.doc.CurrentController
controller.select(shape)
return
def add(self, type_shape, options={}):
properties = options.copy()
"""Insert a shape in page, type shapes:

View File

@ -223,9 +223,13 @@ def set_properties(model, properties):
def get_properties(obj):
properties = obj.PropertySetInfo.Properties
values = {p.Name: getattr(obj, p.Name) for p in properties}
return values
# ~ properties = obj.PropertySetInfo.Properties
# ~ values = {p.Name: getattr(obj, p.Name) for p in properties}
data = obj.PropertySetInfo.Properties
keys = [p.Name for p in data]
values = obj.getPropertyValues(keys)
properties = dict(zip(keys, values))
return properties
# ~ https://github.com/django/django/blob/main/django/utils/functional.py#L61

View File

@ -1,8 +1,26 @@
#!/usr/bin/env python3
from typing import Any
from com.sun.star.awt import Size, Point
from .easymain import BaseObject, Paths, create_instance, dict_to_property, set_properties
from .easyuno import IOStream, get_input_stream
from .easymain import (
BaseObject, Paths,
create_instance, dict_to_property, set_properties, get_properties
)
from .easyuno import BaseObjectProperties, IOStream, get_input_stream
IMAGE = 'com.sun.star.drawing.GraphicObjectShape'
MIME_TYPE = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/svg': 'svg',
}
TYPE_MIME = {
'svg': 'image/svg',
'png': 'image/png',
'jpg': 'image/jpeg',
}
class LOShapes(object):
@ -42,24 +60,14 @@ class LOShapes(object):
return self._obj
class LOShape(BaseObject):
IMAGE = 'com.sun.star.drawing.GraphicObjectShape'
MIME_TYPE = {
'image/png': 'png',
'image/jpeg': 'jpg',
}
class LOShape(BaseObjectProperties):
def __init__(self, obj):
self._obj = obj
super().__init__(obj)
def __str__(self):
return f'Shape: {self.name}'
@property
def obj(self):
"""Get original UNO object"""
return self._obj
@property
def anchor(self):
"""Get anchor object"""
@ -83,11 +91,7 @@ class LOShape(BaseObject):
@property
def properties(self):
"""Get all properties"""
data = self.obj.PropertySetInfo.Properties
keys = [p.Name for p in data]
values = self.obj.getPropertyValues(keys)
data = dict(zip(keys, values))
return data
return get_properties(self.obj)
@properties.setter
def properties(self, values):
set_properties(self.obj, values)
@ -96,6 +100,9 @@ class LOShape(BaseObject):
def shape_type(self):
"""Get type shape"""
return self.obj.ShapeType
@property
def type(self):
return self.shape_type
@property
def name(self):
@ -107,11 +114,11 @@ class LOShape(BaseObject):
@property
def is_image(self):
return self.shape_type == self.IMAGE
return self.shape_type == IMAGE
@property
def is_shape(self):
return self.shape_type != self.IMAGE
return self.shape_type != IMAGE
@property
def size(self):
@ -212,9 +219,9 @@ class LOShape(BaseObject):
self.obj.LayerID = value
@property
def type(self):
def mime_type(self):
mt = self.obj.GraphicURL.MimeType
mime_type = self.MIME_TYPE.get(mt, mt)
mime_type = MIME_TYPE.get(mt, mt)
return mime_type
@property
@ -238,24 +245,76 @@ class LOShape(BaseObject):
def doc(self):
return self.obj.Parent.Forms.Parent
@property
def text_box(self):
return self.obj.TextBox
@text_box.setter
def text_box(self, value):
self.obj.TextBox = value
@property
def text_box_content(self):
return self.obj.TextBoxContent
# ~ @property
# ~ def text_box_content(self):
# ~ controller = self.doc.CurrentController
# ~ vc = controller.ViewCursor
# ~ tbx = self.obj.TextBoxContent
# ~ vc.gotoRange(tbx.Start, False)
# ~ vc.gotoRange(tbx.End, True)
# ~ text = controller.getTransferable()
# ~ return text
def get_path(self, path: str='', name: str='', mime_type: str=''):
if not path:
path = Paths(self.doc.URL).path
if not name:
name = self.name.replace(' ', '_')
if mime_type:
file_name = f'{name}.{mime_type}'
else:
if self.is_image:
file_name = f'{name}.{self.mime_type}'
else:
file_name = f'{name}.svg'
path = Paths.join(path, file_name)
return path
def select(self):
controller = self.doc.CurrentController
controller.select(self.obj)
return
def remove(self):
"""Auto remove"""
self.obj.Parent.remove(self.obj)
return
def save(self, path: str='', name: str=''):
"""Save image"""
def export(self, path: str=''):
if not path:
path = Paths(self.doc.URL).path
if not name:
name = self.name.replace(' ', '_')
path = self.get_path()
mime_type = Paths(path).ext
options = {
'URL': Paths.to_url(path),
'MimeType': TYPE_MIME.get(mime_type, mime_type)}
args = dict_to_property(options)
export = create_instance('com.sun.star.drawing.GraphicExportFilter')
export.setSourceDocument(self.obj)
export.filter(args)
return path
path_img = Paths.join(path, f'{name}.{self.type}')
data = IOStream.to_bin(self.obj.GraphicStream)
Paths.save_bin(path_img, data)
def save(self, path: str=''):
"""Save image"""
if not path:
path = self.get_path()
return path_img
if self.is_image:
data = IOStream.to_bin(self.obj.GraphicStream)
Paths.save_bin(path, data)
else:
self.export(path)
return path
def _get_graphic(self):
stream = self.obj.GraphicStream
@ -267,14 +326,12 @@ class LOShape(BaseObject):
graphic = gp.queryGraphic(properties)
return graphic
def clone(self, draw_page=None):
def clone(self, draw_page: Any=None, x: int=1000, y: int=1000):
"""Clone image"""
image = self.doc.createInstance('com.sun.star.drawing.GraphicObjectShape')
image.Graphic = self._get_graphic()
plus = 0
if draw_page is None:
draw_page = self.obj.Parent
plus = 1000
else:
if hasattr(draw_page, 'obj'):
draw_page = draw_page.obj
@ -282,9 +339,8 @@ class LOShape(BaseObject):
draw_page.add(image)
image.Size = self.size
position = self.position
position.X += plus
position.Y += plus
position.X += x
position.Y += y
image.Position = position
return LOShape(image)

View File

@ -65,3 +65,34 @@ def get_input_stream(data):
stream = create_instance('com.sun.star.io.SequenceInputStream', True)
stream.initialize((data,))
return stream
class BaseObjectProperties():
def __init__(self, obj):
self._obj = obj
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def __contains__(self, item):
return hasattr(self.obj, item)
def __setattr__(self, name, value):
if name == '_obj':
super().__setattr__(name, value)
else:
if name in self:
setattr(self.obj, name, value)
else:
object.__setattr__(self, name, value)
def __getattr__(self, name):
return self.obj.getPropertyValue(name)
@property
def obj(self):
return self._obj

View File

@ -2,6 +2,8 @@
from .easymain import log, BaseObject
from .easydoc import LODocument
from .easydrawpage import LODrawPage
from .easystyles import LOStyleFamilies
class LOWriterTextPortion(BaseObject):
@ -151,3 +153,19 @@ class LOWriter(LODocument):
@property
def string(self):
return self._obj.Text.String
@property
def styles(self):
ci = self.obj.createInstance
return LOStyleFamilies(self.obj.StyleFamilies, ci)
@property
def draw_page(self):
"""Get draw page"""
return LODrawPage(self.obj.DrawPage)
@property
def dp(self):
return self.draw_page
@property
def shapes(self):
return self.draw_page