/
props.py
1550 lines (1301 loc) · 56.1 KB
/
props.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
"""make/get/set properties in an array"""
# Python conversion of Props.java by Andrew Davison, ad@fivedots.coe.psu.ac.th
# See Also: https://fivedots.coe.psu.ac.th/~ad/jlop/
# region Imports
from __future__ import annotations
import contextlib
from typing import Any, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING, cast, overload
import uno
from com.sun.star.beans import PropertyAttribute # const
from com.sun.star.beans import PropertyVetoException
from com.sun.star.beans import UnknownPropertyException
from com.sun.star.beans import XFastPropertySet
from com.sun.star.beans import XPropertySet
from com.sun.star.beans import XPropertyState
from com.sun.star.container import XIndexAccess
from com.sun.star.container import XNameAccess
from com.sun.star.document import XTypeDetection
from com.sun.star.ui import ItemStyle # const
from com.sun.star.ui import ItemType # const
from ooo.dyn.beans.property_value import PropertyValue
from ooo.dyn.beans.property import Property
if TYPE_CHECKING:
from com.sun.star.beans import XPropertySetInfo
from com.sun.star.beans import XMultiPropertySet
# import module and not module content to avoid circular import issue.
# https://stackoverflow.com/questions/22187279/python-circular-importing
#
# using lazy loading: https://snarky.ca/lazy-importing-in-python-3-7/
from . import gen_util as gUtil
from . import info as mInfo
from . import lo as mLo
from ..events.args.key_val_args import KeyValArgs
from ..events.args.key_val_cancel_args import KeyValCancelArgs
from ..events.args.event_args import EventArgs
from ..events.args.cancel_event_args import CancelEventArgs
from ..events.event_singleton import _Events
from ..events.props_named_event import PropsNamedEvent
from ..exceptions import ex as mEx
# endregion Imports
class Props:
"""make/get/set properties in an array"""
# region ------------------- make properties -----------------------
@staticmethod
def make_prop_value(name: Optional[str] = None, value: Optional[Any] = None) -> PropertyValue:
"""
Makes a Uno Property Value and assigns name and value if present.
Args:
name (Optional[str], optional): Property name
value (Optional[Any], optional): Property value
Returns:
PropertyValue: com.sun.star.beans.PropertyValue
See Also:
`LibreOffice API PropertyValue <https://api.libreoffice.org/docs/idl/ref/structcom_1_1sun_1_1star_1_1beans_1_1PropertyValue.html>`_
"""
p = cast(PropertyValue, uno.createUnoStruct("com.sun.star.beans.PropertyValue"))
if name is not None:
p.Name = name
if value is not None:
p.Value = value
return p
@classmethod
def make_bar_item(
cls, cmd: str, item_name: str
) -> Tuple[PropertyValue, PropertyValue, PropertyValue, PropertyValue, PropertyValue]:
"""
Properties for a toolbar item using a name and an image
problem: image does not appear next to text on toolbar
Args:
cmd (str): Value of CommandURL
item_name (str): Label assigned to bar
Returns:
Tuple[PropertyValue, PropertyValue, PropertyValue, PropertyValue, PropertyValue]: Tuple of properties. (CommandURL, Label, Type, Visible, Style)
"""
p1 = cls.make_prop_value(name="CommandURL", value=cmd)
p2 = cls.make_prop_value(name="Label", value=item_name)
p3 = cls.make_prop_value(name="Type", value=ItemType.DEFAULT)
p4 = cls.make_prop_value(name="Visible", value=True)
p5 = cls.make_prop_value(name="Style")
p5.Value = ItemStyle.DRAW_FLAT + ItemStyle.ALIGN_LEFT + ItemStyle.AUTO_SIZE + ItemStyle.ICON + ItemStyle.TEXT
return (p1, p2, p3, p4, p5)
@classmethod
def make_props(cls, **kwargs) -> Tuple[PropertyValue, ...]:
"""
Make Properties
Keyword Args:
kwargs (Dict[str, Any]): Each key, value pair is assigned to a PropertyValue.
Returns:
Tuple[PropertyValue, ...]: Tuple of Properties
Note:
String properties such as ``Zoom.Value`` can be pass by constructing a dictionary
and passing dictionary via expansion.
Example Expansion
.. code-block:: python
p_dic = {
"Zoom.Value": 0,
"Zoom.ValueSet": 28703,
"Zoom.Type": 1
}
props = Props.make_props(**p_dic)
"""
lst = [cls.make_prop_value(name=k, value=v) for k, v in kwargs.items()]
return tuple(lst)
# endregion ---------------- make properties -----------------------
# region ------------------- uno -----------------------------------
@staticmethod
def any(*elements: object) -> uno.Any: # type: ignore
"""
Gets a uno.Any object for elements.
The first element determines the type for the uno.Any object.
Raises:
ValueError: if unable to create uno.Any object.
Returns:
uno.Any: uno.Any Object
Note:
uno.Any is usually constructed in the following manor.
``uno.Any("[]com.sun.star.table.TableSortField", (sort_one, sort_two)``
This method is a shortcut.
``Props.any(sort_one, sort_two)``
"""
if not elements:
raise ValueError("No args to create unn.Any object")
obj = elements[0]
if isinstance(obj, uno.Type):
type_name = obj.typeName
return uno.Any(obj, [*elements]) # type: ignore
elif isinstance(obj, str):
type_name = "string"
elif isinstance(obj, int):
type_name = "short"
else:
type_name = mInfo.Info.get_type_name(obj)
if type_name is None:
raise ValueError("Unable to get type name to create uno.Any object")
return uno.Any(f"[]{type_name}", [*elements]) # type: ignore
# endregion ---------------- uno -----------------------------------
# region ------------------- set properties ------------------------
@staticmethod
def set_prop(props: Iterable[PropertyValue], name: str, value: object) -> bool:
"""
Sets property value for the first property that has matching name.
Args:
props (Iterable[PropertyValue]): Property Values
name (str): Property name
value (object): Property Value
Raises:
TypeError: if props is None.
Returns:
bool: True if property matching name has been updated; Otherwise, False
"""
if props is None:
TypeError(f"Property array is null; cannot set {name}")
for prop in props:
if prop.Name == name:
prop.Value = value
return True
print(f"{name} not found")
return False
@staticmethod
def get_xproperty_set(obj: object) -> XPropertySet:
"""
Gets Property Set
Args:
obj (object): object that implements ``XPropertySet``
Raises:
MissingInterfaceError: if ``obj`` does not implement ``XPropertySet``.
Returns:
XPropertySet: Property Set
"""
return mLo.Lo.qi(XPropertySet, obj, True)
@staticmethod
def get_xproperty_set_fast(obj: object) -> XFastPropertySet:
"""
Gets Fast Property Set
Args:
obj (object): object that implements ``XFastPropertySet``
Raises:
MissingInterfaceError: if ``obj`` does not implement ``XFastPropertySet``.
Returns:
XFastPropertySet: Property Set
"""
return mLo.Lo.qi(XFastPropertySet, obj, True)
# region get_xproperty_fast_value()
@overload
@classmethod
def get_xproperty_fast_value(cls, *, handle: int, fps: XFastPropertySet) -> Any:
...
@overload
@classmethod
def get_xproperty_fast_value(cls, *, prop: Property, fps: XFastPropertySet) -> Any:
...
@overload
@classmethod
def get_xproperty_fast_value(cls, *, handle: int, obj: object) -> Any:
...
@classmethod
def get_xproperty_fast_value(cls, *args, **kwargs) -> Any:
"""
Gets a fast property value via ``XFastPropertySet``
Arguments:
handle (int): handle of the property.
fps (XFastPropertySet): property set that contains the property for matching handle.
prop (Property): Property that handle can be obtained from.
obj (object): an object that ``XFastPropertySet`` can be obtained from.
Raises:
PropertyGeneralError: If an error occurs.
Returns:
Any: Property Value
"""
if args:
raise TypeError(f"get_xproperty_fast_value() takes 0 positional arguments but {len(args)} was given")
count = len(kwargs)
if count != 2:
raise TypeError("get_xproperty_fast_value() got an invalid number of arguments")
try:
handle = cast(int, kwargs.get("handle", None))
if handle is None:
handle = cast(Property, kwargs.get("prop")).Handle
fps = cast(XFastPropertySet, kwargs.get("fps", None))
if fps:
return fps.getFastPropertyValue(handle)
fps = cls.get_xproperty_set_fast(kwargs.get("obj"))
return fps.getFastPropertyValue(handle)
except Exception as e:
raise mEx.PropertyGeneralError("Error getting fast property value") from e
# endregion get_xproperty_fast_value()
@classmethod
def get_property_set_info(cls, obj: object) -> XPropertySetInfo:
"""
Gets property set info
Args:
obj (object): Object that implements ``XPropertySet``.
Raises:
PropertyGeneralError: If error occurs
Returns:
XPropertySetInfo: Property Set Info
"""
try:
x_set = cls.get_xproperty_set(obj)
result = x_set.getPropertySetInfo()
if result is None:
raise mEx.NoneError("None Value: x_set.getPropertySetInfo() returned None")
return result
except Exception as e:
raise mEx.PropertyGeneralError("Error getting property set info") from e
@classmethod
def get_property_by_name(cls, obj: object, name: str) -> Property:
"""
Gets a property by name.
Property instances do not contain a value.
Args:
obj (object): Object to get a property from
name (str): Property name to lookup in ``obj``.
Raises:
PropertyError: If error occurs
Returns:
Property: Property instance.
"""
try:
info = cls.get_property_set_info(obj)
return info.getPropertyByName(name) # type: ignore
except Exception as e:
raise mEx.PropertyError(name) from e
@classmethod
def has_property(cls, obj: object, name: str) -> bool:
"""
Gets is an object contains a Property
Args:
obj (object): object that implements ``XPropertySet``
name (str): _description_
Returns:
bool: ``True`` if object contains property with name; Otherwise, ``False``.
"""
with contextlib.suppress(Exception):
x_set = cls.get_property_set_info(obj)
return x_set.hasPropertyByName(name)
return False
@staticmethod
def get_prop(props: Iterable[PropertyValue], name: str) -> object | None:
"""
Gets property value for property that matches name.
Args:
props (Iterable[PropertyValue]): Properties to search
name (str): Property name to find.
Raises:
TypeError: if props is None.
Returns:
object | None: Property value if found; Otherwise; None
"""
if props is None:
TypeError(f"Property array is null; cannot get {name}")
for prop in props:
if prop.Name == name:
return prop.Value
print(f"{name} not found")
return None
# region set_property()
@overload
@classmethod
def set_property(cls, obj: object, name: str, value: object) -> None:
...
@overload
@classmethod
def set_property(cls, prop_set: XPropertySet, name: str, value: object) -> None:
...
@classmethod
def set_property(cls, *args, **kwargs) -> None:
"""
Sets the value of the property with the specified name.
Args:
obj (object): object that implements XPropertySet interface
prop_set (XPropertySet): Property set
name (str): Name of property to set value of
value (object): property value
:events:
.. cssclass:: lo_event
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SETTING` :eventref:`src-docs-props-event-setting`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SET` :eventref:`src-docs-props-event-set`
Raises:
MissingInterfaceError: If required interface cannot be obtained.
PropertySetError: If unable to set property value
Returns:
None:
Note:
If a Event is canceled then property is not set. No error occurs.
"""
ordered_keys = (1, 2, 3)
kargs_len = len(kwargs)
count = len(args) + kargs_len
def get_kwargs() -> dict:
ka = {}
if kargs_len == 0:
return ka
valid_keys = ("obj", "prop_set", "name", "value")
check = all(key in valid_keys for key in kwargs)
if not check:
raise TypeError("set_property() got an unexpected keyword argument")
keys = ("obj", "prop_set")
for key in keys:
if key in kwargs:
ka[1] = kwargs[key]
break
ka[2] = kwargs.get("name", None)
ka[3] = kwargs.get("value", None)
return ka
if count != 3:
raise TypeError("set_property() got an invalid number of arguments")
kargs = get_kwargs()
for i, arg in enumerate(args):
kargs[ordered_keys[i]] = arg
try:
cls.set(kargs[1], **{kargs[2]: kargs[3]})
except mEx.MissingInterfaceError:
raise
except mEx.MultiError as me:
err = me.errors[0]
if isinstance(err, (mEx.PropertyNotFoundError, mEx.PropertySetError)):
raise err
raise mEx.PropertySetError(f"Could not set property '{kargs[2]}'") from err
# endregion set_property()
# region set_properties()
@overload
@classmethod
def set_properties(cls, obj: object, names: Sequence[str], vals: Sequence[object]) -> None:
"""
Set Properties
Args:
obj (object): Object that implements XPropertySet interface
names (Sequence[str]): Property Names
vals (Sequence[object]): Property Values
Raises:
MissingInterfaceError: if obj does not implement XPropertySet interface
MultiError: If unable to set a property
"""
...
@overload
@classmethod
def set_properties(cls, prop_set: XPropertySet, names: Sequence[str], vals: Sequence[object]) -> None:
"""
Set Properties
Args:
prop_set (XPropertySet): Property Set
names (Sequence[str]): Property Names
vals (Sequence[object]): Property Values
Raises:
MultiError: If unable to set a property
"""
...
@overload
@classmethod
def set_properties(cls, obj: object, from_obj: object) -> None:
"""
Set properties
Properties of ``from_obj`` are assigned to ``obj``
Args:
obj (object): Object that implements XPropertySet interface
from_obj (object): Other object that implements XPropertySet interface
Raises:
MissingInterfaceError: if obj does not implement XPropertySet interface
MissingInterfaceError: if from_obj does not implement XPropertySet interface
MultiError: If unable to set a property
"""
...
@overload
@classmethod
def set_properties(cls, prop_set: XPropertySet, from_props: XPropertySet) -> None:
"""
Set properties
Properties of ``from_props`` are assigned to ``prop_set``
Args:
prop_set (XPropertySet): Property set
from_props (XPropertySet): Property set
Raises:
MultiError: If unable to set a property
"""
...
@classmethod
def set_properties(cls, *args, **kwargs) -> None:
"""
Set Properties
Args:
obj (object): Object that implements XPropertySet interface
prop_set (XPropertySet): Property set
from_props (XPropertySet): Property set
from_obj (object): Other object that implements XPropertySet interface
names (Sequence[str]): Property Names
vals (Sequence[object]): Property Values
Raises:
MissingInterfaceError: if obj does not implement XPropertySet interface
MissingInterfaceError: if from_obj does not implement XPropertySet interface
MultiError: If unable to set a property
Returns:
None:
:events:
.. cssclass:: lo_event
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SETTING` :eventref:`src-docs-props-event-setting`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SET` :eventref:`src-docs-props-event-set`
Note:
If a Event is canceled then that property is not set. No error occurs.
If ``MultiError`` occurs only the properties that raised an error is part of the error object.
The remaining properties will still be set.
"""
ordered_keys = (1, 2, 3)
kargs_len = len(kwargs)
count = len(args) + kargs_len
def get_kwargs() -> dict:
ka = {}
if kargs_len == 0:
return ka
valid_keys = ("obj", "prop_set", "names", "from_obj", "from_props", "vals")
check = all(key in valid_keys for key in kwargs)
if not check:
raise TypeError("set_properties() got an unexpected keyword argument")
keys = ("obj", "prop_set")
for key in keys:
if key in kwargs:
ka[1] = kwargs[key]
break
keys = ("names", "from_obj", "from_props")
for key in keys:
if key in kwargs:
ka[2] = kwargs[key]
break
if count == 2:
return ka
ka[3] = kwargs.get("vals", None)
return ka
if count not in (2, 3):
raise TypeError("set_properties() got an invalid number of arguments")
kargs = get_kwargs()
for i, arg in enumerate(args):
kargs[ordered_keys[i]] = arg
if mInfo.Info.is_type_interface(kargs[1], "com.sun.star.beans.XPropertySet"):
# set_properties(cls, prop_set: XPropertySet, names: Sequence[str], vals: Sequence[object]) -> None
# set_properties(cls, prop_set: XPropertySet, from_props: XPropertySet) -> None
prop_set = cast(XPropertySet, kargs[1])
else:
# set_properties(cls, obj: object, names: Sequence[str], vals: Sequence[object]) -> None
# set_properties(cls, obj: object, from_obj: object) -> None
prop_set = mLo.Lo.qi(XPropertySet, kargs[1])
if prop_set is None:
raise mEx.MissingInterfaceError(XPropertySet)
if count == 3:
# set_properties(cls, prop_set: XPropertySet, names: Sequence[str], vals: Sequence[object]) -> None
# set_properties(cls, obj: object, names: Sequence[str], vals: Sequence[object]) -> None
cls._set_properties_by_vals(prop_set=prop_set, names=kargs[2], vals=kargs[3])
return
elif count == 2:
if mInfo.Info.is_type_interface(kargs[2], "com.sun.star.beans.XPropertySet"):
# set_properties(cls, prop_set: XPropertySet, from_props: XPropertySet) -> None
from_props = cast(XPropertySet, kargs[2])
else:
# set_properties(cls, obj: object, from_obj: object) -> None
from_props = mLo.Lo.qi(XPropertySet, kargs[1], True)
cls._set_properties_from_props(prop_set=prop_set, from_props=from_props)
@classmethod
def _set_properties_by_vals(cls, prop_set: XPropertySet, names: Sequence[str], vals: Sequence[object]) -> None:
errs = []
for i, name in enumerate(names):
has_error = False
cargs = None
try:
cargs = KeyValCancelArgs(Props.set_properties.__qualname__, name, vals[i])
cargs.event_data = prop_set
_Events().trigger(PropsNamedEvent.PROP_SETTING, cargs)
if cargs.cancel:
continue
prop_set.setPropertyValue(cargs.key, cargs.value)
except PropertyVetoException as e:
has_error = True
errs.append(mEx.PropertySetError(f'Could not set readonly-property "{name}"', e))
except UnknownPropertyException as e:
has_error = True
errs.append(mEx.PropertyNotFoundError(name, e))
except Exception as e:
has_error = True
errs.append(Exception(f'Could not set property "{name}"', e))
if not has_error and cargs:
_Events().trigger(PropsNamedEvent.PROP_SET, KeyValArgs.from_args(cargs))
if errs:
raise mEx.MultiError(errs)
@classmethod
def _set_properties_from_props(cls, prop_set: XPropertySet, from_props: XPropertySet) -> None:
errs = []
if prop_set is None:
print("Property set is null; cannot set properties")
return
if from_props is None:
print("Source property set is null; cannot set properties")
return
nms = cls.get_prop_names(from_props)
for itm in nms:
has_error = False
cargs = None
try:
cargs = KeyValCancelArgs(Props.set_properties.__qualname__, itm, cls.get_property(from_props, itm))
cargs.event_data = prop_set
_Events().trigger(PropsNamedEvent.PROP_SETTING, cargs)
if cargs.cancel:
continue
prop_set.setPropertyValue(cargs.key, cargs.value)
except PropertyVetoException as e:
has_error = True
errs.append(mEx.PropertySetError(f'Could not set readonly-property "{itm}"', e))
except UnknownPropertyException as e:
has_error = True
errs.append(mEx.PropertyNotFoundError(itm, e))
except Exception as e:
has_error = True
errs.append(Exception(f'Could not set property "{itm}"', e))
if not has_error and cargs:
_Events().trigger(PropsNamedEvent.PROP_SET, KeyValArgs.from_args(cargs))
if errs:
raise mEx.MultiError(errs)
# endregion set_properties()
@staticmethod
def _set_by_attribute(obj: object, name: str, value: Any) -> bool:
# there is a bug in LibreOffice that in some cases getting XPropertySet
# returns the interface but it is missing setPropertyValue and or getPropertySetInfo
# this is the case with XChartDocument.getPageBackground() and XChartDocument.getFirstDiagram().getWall()
# See Chart2.set_background_colors()
#
# the same issue (ct is XChartType) with:
# white_day_ps = mLo.Lo.qi(XPropertySet, mProps.Props.get(ct, "WhiteDay"), True)
# black_day_ps = mLo.Lo.qi(XPropertySet, mProps.Props.get(ct, "BlackDay"), True)
# see Chart2.color_stock_bars()
# Even though the interface is missing setPropertyValue and or getPropertySetInfo the
# properties are still there.
# That is why this method. It is a fallback when bug is found to set value by attribute.
# see Props.set()
if not hasattr(obj, name):
return False
with contextlib.suppress(AttributeError):
setattr(obj, name, value)
return True
return False
@staticmethod
def _get_by_attribute(obj: object, name: str) -> Tuple[bool, Any]:
# there is a bug in LibreOffice that in some cases getting XPropertySet
# returns the interface but it is missing setPropertyValue and or getPropertySetInfo
# this is the case with XChartDocument.getPageBackground() and XChartDocument.getFirstDiagram().getWall()
# See Chart2.set_background_colors()
#
# the same issue (ct is XChartType) with:
# white_day_ps = mLo.Lo.qi(XPropertySet, mProps.Props.get(ct, "WhiteDay"), True)
# black_day_ps = mLo.Lo.qi(XPropertySet, mProps.Props.get(ct, "BlackDay"), True)
# see Chart2.color_stock_bars()
# Even though the interface is missing setPropertyValue and or getPropertySetInfo the
# properties are still there.
# That is why this method. It is a fallback when bug is found to get value by attribute.
# see Props.get()
with contextlib.suppress(AttributeError):
return (True, getattr(obj, name))
return (False, None)
@classmethod
def set(cls, obj: object, **kwargs) -> None:
"""
Set one or more properties.
Args:
obj (object): object to set properties for. Must support ``XPropertySet``
**kwargs: Variable length Key value pairs used to set properties.
Raises:
MissingInterfaceError: if obj does not implement ``XPropertySet`` interface
MultiError: If unable to set a property
Returns:
None:
:events:
.. cssclass:: lo_event
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SETTING` :eventref:`src-docs-props-event-setting`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SET` :eventref:`src-docs-props-event-set`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SET_ERROR` :eventref:`src-docs-props-event-set-error`
Note:
If a Event is canceled then that property is not set. No error occurs.
If ``MultiError`` occurs only the properties that raised an error is part of the error object.
The remaining properties will still be set.
If ``KeyValCancelArgs.default`` is set to true then property is set to Default
Note:
If an error occurs a ``PROP_SET_ERROR`` is raised. If the event args are set to ``cancel`` or ``handled`` then the error is ignored.
See Also:
:py:meth:`~.props.Props.set_default`
.. versionchanged:: 0.9.0
Setting ``KeyValCancelArgs.default=False`` will set a property to its default.
.. versionchanged:: 0.9.4
Now event is raised if a property fails to set.
"""
if not kwargs:
return
if mInfo.Info.is_type_interface(obj, "com.sun.star.beans.XPropertySet"):
ps = cast(XPropertySet, obj)
else:
ps = mLo.Lo.qi(XPropertySet, obj, True)
errs = []
for key, value in kwargs.items():
has_error = False
cargs = KeyValCancelArgs(Props.set.__qualname__, key, value)
cargs.event_data = obj
_Events().trigger(PropsNamedEvent.PROP_SETTING, cargs)
if cargs.cancel:
continue
try:
if cargs.default:
cls.set_default(obj, cargs.key)
elif cargs.key == "":
continue
else:
ps.setPropertyValue(cargs.key, cargs.value)
except (AttributeError, UnknownPropertyException) as e:
# handle a LibreOffice bug
try:
if not cls._set_by_attribute(obj, cargs.key, cargs.value):
raise e
except Exception as ex:
has_error = True
if type(ex).__name__ == "com.sun.star.beans.UnknownPropertyException":
errs.append(mEx.PropertyNotFoundError(key, ex))
else:
errs.append(
mEx.UnKnownError(
f'Something went wrong. Could not find setPropertyValue attribute on property set. Tried setting "{key}" manually but failed'
)
)
except PropertyVetoException as e:
has_error = True
errs.append(mEx.PropertySetError(f'Could not set readonly-property "{key}"', e))
except Exception as e:
has_error = True
errs.append(Exception(f'Could not set property "{key}"', e))
if has_error:
error_args = KeyValCancelArgs.from_args(cargs)
error_args.cancel = False
error_args.handled = False
_Events().trigger(PropsNamedEvent.PROP_SET_ERROR, error_args)
if (error_args.handled or error_args.cancel) and errs:
_ = errs.pop()
else:
_Events().trigger(PropsNamedEvent.PROP_SET, KeyValArgs.from_args(cargs))
if errs:
raise mEx.MultiError(errs)
@classmethod
def set_default(cls, obj: object, *prop_names: str) -> None:
"""
Set one or more properties to default values.
Args:
obj (object): object to set properties for. Must support ``XPropertyState``
**prop_names: Variable length of property names to set default.
Raises:
MissingInterfaceError: if obj does not implement ``XPropertyState`` interface
MultiError: If unable to set a property
Returns:
None:
:events:
.. cssclass:: lo_event
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_DEFAULT_SETTING` :eventref:`src-docs-event-cancel`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_DEFAULT_SET` :eventref:`src-docs-event`
- :py:attr:`~.events.props_named_event.PropsNamedEvent.PROP_SET_DEFAULT_ERROR` :eventref:`src-docs-event-cancel`
Note:
Event data is a dictionary of ``{"obj": obj, "name": name}`` with name being the property name currently being set.
If a Event is canceled then that property is not set. No error occurs.
If ``MultiError`` occurs only the properties that raised an error is part of the error object.
The remaining properties will still be set to default.
.. versionadded:: 0.9.0
.. versionchanged:: 0.9.4
Now event is raised if a property fails to set default.
"""
ps = mLo.Lo.qi(XPropertyState, obj, True)
errs = []
for name in prop_names:
has_error = False
cargs = CancelEventArgs(Props.set.__qualname__)
cargs.event_data = {"obj": obj, "name": name}
_Events().trigger(PropsNamedEvent.PROP_DEFAULT_SETTING, cargs)
if cargs.cancel:
continue
prop_name = cargs.event_data["name"]
try:
ps.setPropertyToDefault(prop_name)
except Exception as e:
has_error = True
errs.append(Exception(f'Could not set property Default "{prop_name}"', e))
if has_error:
error_args = CancelEventArgs.from_args(cargs)
cargs.cancel = False
cargs.handled = False
_Events().trigger(PropsNamedEvent.PROP_SET_DEFAULT_ERROR, error_args)
if (error_args.handled or error_args.cancel) and errs:
_ = errs.pop()
else:
_Events().trigger(PropsNamedEvent.PROP_DEFAULT_SET, EventArgs.from_args(cargs))
if errs:
raise mEx.MultiError(errs)
# endregion ---------------- set properties -----------------------
# region ------------------- get properties ------------------------
@staticmethod
def get_default(obj: object, prop_name: str, default: Any = gUtil.NULL_OBJ) -> Any:
"""
Gets the default value of the property with the name Property Name.
Args:
obj (object): object to set properties for. Must support ``XPropertyState``
prop_name (str): Property name to get default for.
default (Any, optional): Return value if property value is ``None`` or ``obj`` does not support ``XPropertyState`` interface.
Raises:
MissingInterfaceError: If ``obj`` does not support ``XPropertyState`` interface and a ``default`` value is not provided.
Returns:
Any: If no default exists, is not known or is ``None``, then the return type is ``None``.
"""
try:
ps = mLo.Lo.qi(XPropertyState, obj, True)
result = ps.getPropertyDefault(prop_name)
return default if result is None and default is not gUtil.NULL_OBJ else result
except mEx.MissingInterfaceError:
if default is not gUtil.NULL_OBJ:
return default
raise
# region get()
@overload
@classmethod
def get(cls, obj: object, name: str) -> Any:
...
@overload
@classmethod
def get(cls, obj: object, name: str, default: Any) -> Any:
...
@classmethod
def get(cls, obj: object, name: str, default: Any = gUtil.NULL_OBJ) -> Any:
"""
Gets a property value from an object.
``obj`` must support ``XPropertySet`` interface
Args:
obj (object): Object to get property from.
name (str): Property Name.
default (Any, optional): Return value if property value is ``None``.
Raises:
PropertyNotFoundError: If Property is not found and default was not set.
PropertyError: If any other error occurs and default was not set.
Returns:
Any: Property value or default
Note:
If a ``default`` is not set then an error is raised if property is not found.
Otherwise, the ``default`` value is returned if property is not found.
"""
try:
if mInfo.Info.is_type_interface(obj, "com.sun.star.beans.XPropertySet"):
ps = cast(XPropertySet, obj)
else:
ps = mLo.Lo.qi(XPropertySet, obj, True)
try:
val = ps.getPropertyValue(name)
except (AttributeError, UnknownPropertyException) as e:
# handle a LibreOffice bug
success = False
try:
success, val = cls._get_by_attribute(ps, name)
except Exception as ex:
if type(e).__name__ == "com.sun.star.beans.UnknownPropertyException":
raise e from ex
raise mEx.UnKnownError(
f'Something went wrong. Could not find getPropertyValue attribute on property set. Tried getting "{name}" manually but failed.'
) from ex
if not success:
if type(e).__name__ == "com.sun.star.beans.UnknownPropertyException":
raise e
raise mEx.UnKnownError(
f'Something went wrong. Could not find getPropertyValue attribute on property set. Tried getting "{name}" manually but failed.'
) from e
# it is perfectly fine for a property to have a value of None
return default if val is None and default is not gUtil.NULL_OBJ else val
except UnknownPropertyException as exc:
# the property name is not in the property set
if default is not gUtil.NULL_OBJ:
return default
raise mEx.PropertyNotFoundError(name) from exc
except mEx.UnKnownError:
raise
except Exception as exx:
if default is not gUtil.NULL_OBJ:
return default
raise mEx.PropertyError(f'Error getting property: "{name}"') from exx
# endregion get()
# region get_property()
@overload
@classmethod
def get_property(cls, obj: object, name: str) -> object:
"""
Gets a property value from property set
Args:
obj (object): object that implements XPropertySet interface
xprops (XPropertySet): property set
name (str): property name
Raises:
PropertyNotFoundError: If unable to get property
MissingInterfaceError: if obj does not implement XPropertySet interface
Returns:
object: property value