-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleadmacro.py
More file actions
5275 lines (4727 loc) · 180 KB
/
leadmacro.py
File metadata and controls
5275 lines (4727 loc) · 180 KB
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
"""
~
Copyright (c) 2016 John Schwarz
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
As a macro, all LOC are going to be located within this module.
It may not be the best organization, but it allows easier mobility of
the produced macro.
This is intended to be run as a LibreOffice Calc macro or executed alongside
a running office program with open Excel sheets.
TODO:
* Add ability to check for duplicates against a collection of
previously used values.
* Possible implementations;
* XML table storing sheets/values
* Folder containing a file for each used input sheet,
storing key values
* Add message to user, asking them not to edit source sheet
Contents:
Office Interface handling
Translations
GUI
KNOWN BUGS:
* Attempting to open two instances of the macro simultaneously will
freeze both macros and the office program
INSTALL:
for libreoffice, requires python scripts module installed.
in ubuntu, this can be installed via
'apt-get install libreoffice-script-provider-python'
"""
import collections
import os
import datetime # used for saving logs by time
import pickle
import csv # used for saving logs
import platform
import sys
from PyQt5.QtWidgets import QMessageBox, QVBoxLayout, QHBoxLayout, \
QInputDialog, QCheckBox, QComboBox, QPushButton, QGridLayout, \
QLineEdit, QDialog, QTableWidget, QTableWidgetItem, QListWidget, \
QWidget, QLabel, QApplication
try:
import xlwings as xw
except ImportError:
xw = None
APP_FOLDER_NAME = 'leadsmacro'
SAVED_TRANSLATIONS_FOLDER_NAME = 'saved_translations'
LOG_DIR_NAME = 'logs'
SERIALIZED_OBJ_SUFFIX = '.pkl'
MAX_CELL_GAP = 10 # max distance between inhabited cells in the workbook
CACHING = True # whether or not cells should cache accessed values
APP_WINDOW_TITLE = 'Lead Macro'
DEFAULT_WIDGET_X = 512
DEFAULT_WIDGET_Y = 512
DEFAULT_WIDGET_H = 512
DEFAULT_WIDGET_W = 524
DEFAULT_CONTENT_MARGIN_X = 15
DEFAULT_CONTENT_MARGIN_Y = 5
STANDARD_GRID_SPACING = 10 # spacing in gui grid
NONE_STRING = '< Empty >'
# colors #
DEFAULT_COLOR = -1
WHITE = 0xffffff
FIREBRICK = 0xB22222
CORAL = 0xFF7F50
ORANGE = 0xBDB76B
KHAKI = 0xF0E68C
WHITESPACE_CELL_COLOR = ORANGE
WHITESPACE_ROW_COLOR = DEFAULT_COLOR
DUPLICATE_CELL_COLOR = FIREBRICK
DUPLICATE_ROW_COLOR = DEFAULT_COLOR
# Settings Keys #
SOURCE_SHEET_KEY = 'Source Sheet'
TARGET_SHEET_KEY = 'Target Sheet'
SOURCE_START_KEY = 'Source Start'
TARGET_START_KEY = 'Target Start'
DUPLICATE_ACTION_KEY = 'Duplicate Action'
WHITESPACE_ACTION_KEY = 'Whitespace Action'
COLUMN_TRANSLATIONS_KEY = 'Column Translations'
SOURCE_COLUMN_NAME_KEY = 'source_column_name'
TARGET_COLUMN_NAME_KEY = 'target_column_name'
SOURCE_COLUMN_INDEX_KEY = 'source_column_i'
TARGET_COLUMN_INDEX_KEY = 'target_column_i'
WHITESPACE_CHK_KEY = 'check_for_whitespace'
DUPLICATE_CHK_KEY = 'check_for_duplicates'
# Row dlg settings
LOG_WRITE_KEY = 'log_write'
LOG_READ_KEY = 'log_read'
LOG_GROUP_KEY = 'log_group'
WHITESPACE_REMOVE_STR = 'Remove Whitespace'
WHITESPACE_HIGHLIGHT_STR = 'Highlight'
WHITESPACE_IGNORE_STR = 'Do nothing'
DUPLICATE_REMOVE_ROW_STR = 'Remove row'
DUPLICATE_HIGHLIGHT_STR = 'Highlight'
DUPLICATE_IGNORE_STR = 'Do nothing'
###############################################################################
# BOOK INTERFACE
class Model:
"""
Abstract model to be extended by office interface specific
subclasses in Office.
"""
def __init__(self) -> None:
raise NotImplementedError
def __getitem__(self, item: str or int):
"""
Gets sheet from model, either by the str name of the sheet,
or the int index.
:param item: str or int
:return: Office.Sheet
"""
raise NotImplementedError
# implemented by office program specific subclasses
def __iter__(self):
"""
Gets iterator returning sheets in model
:return: Iterator
"""
raise NotImplementedError
def get_sheet(
self,
sheet_name: str,
row_ref_i: int=0,
col_ref_i: int=0
) -> 'Sheet':
"""
Gets sheet of passed name in Model.
Functions the same as Model.__getitem__ except reference row
and reference column indices may be passed to this method.
:param sheet_name: str
:param row_ref_i: int
:param col_ref_i: int
:return: Sheet
"""
raise NotImplementedError # todo: finish sorting these two methods out
def sheet_exists(self, *sheet_name: str) -> str:
"""
Checks that the passed string(s) exist in the model.
if so, returns the first passed sheet name to do so.
:param sheet_name: str
:return: str
"""
raise NotImplementedError
# implemented by office program specific subclasses
@property
def sheets(self):
"""
Returns iterator of sheets in model.
:return: Iterator
"""
raise NotImplementedError
# implemented by office program specific subclasses
@property
def sheet_names(self):
"""
Gets iterable of sheet names
:return: str iterable
"""
raise NotImplementedError
class WorkBookComponent:
"""
Abstract class with common methods for classes that exist within
a workbook.
"""
sheet = None
@property
def parents(self):
"""
Gets parents of WorkBookComponent (instances containing this component)
:return: Generator[WorkBookComponent]
"""
raise NotImplementedError
@property
def instantiated_parents(self):
"""
Works as 'parents' method, but returns only parents that have
been instantiated.
This method was written to facilitate clearing caches when a
sub-component has been changed
:return: Generator[WorkBookComponent]
"""
raise NotImplementedError
@staticmethod
def value_cache(getter: callable) -> callable:
"""
decorator that caches results of the passed method
:param getter: callable
:return: callable
"""
def getter_wrapper(o, *args, **kwargs):
# if caching is not possible, just call getter
# to do this, find sheet and check if exclusive_editor is True
if not o.sheet.exclusive_editor:
return getter(o, *args, **kwargs)
# get cache
try:
cache = o.__value_cache
except AttributeError:
cache = o.__value_cache = {}
# if caching is possible, but nothing is in cache, set it
try:
value = cache[getter] # try to return cached value
except KeyError:
value = cache[getter] = getter(o, *args, **kwargs)
return value
return getter_wrapper
@staticmethod
def enduring_cache(getter):
"""
Caches results of method in a cache that is not removed
when a clear_cache method is called. This is to be used
for methods whose results will always remain the same
for the object they have been called upon, even if values
of that WorkBookObject have changed.
This method will also cache results regardless of whether
the sheet interface obj is the exclusive editor of its values,
since changes made by other means do not affect the returned
values of the method being cached.
:param getter: callable
:return: callable
"""
def enduring_cache_getter(o, *args, **kwargs):
# get cache
try:
cache = o.__enduring_cache
except AttributeError:
cache = o.__enduring_cache = {}
# if caching is possible, but nothing is in cache, set it
try:
value = cache[getter] # try to return cached value
except KeyError:
value = cache[getter] = getter(o, *args, **kwargs)
return value
return enduring_cache_getter
@staticmethod
def clear_cache(setter):
"""
decorator method to be used by value setter.
amends method to clear cache of this WorkBookComponent and
instantiated parents.
:param setter: callable
:return: callable
"""
def setter_wrapper(o, *args, **kwargs) -> None:
"""
Function wrapping passed setter method.
first clears cached values,
then calls original setter method with values.
:return: None
"""
assert isinstance(o, WorkBookComponent)
# for each WorkBookComponent modified, clear its cache
modified_components = \
[o] + [parent for parent in o.instantiated_parents]
for component in modified_components:
try: # try to find cache.
cache = component.__value_cache
except AttributeError:
pass
else: # if cell has a cache, clear it.
assert isinstance(cache, dict)
cache.clear()
setter(o, *args, **kwargs) # call original value setter method
return setter_wrapper
class Sheet(WorkBookComponent):
"""
Abstract class for sheet handling cell values of a passed sheet.
Inherited from by PyUno.Sheet and XW.Sheet.
"""
i7e_sheet = None # interface sheet obj. ie; com.sun.star...Sheet
_reference_row_index = 0
_reference_column_index = 0
_content_row_start = None # default start index of table_row iter
_table_col_start = None # default start index of table_col iter
_snapshot = None
exclusive_editor = False # true if no concurrent editing will occur
_all_sheets = {} # all sheets so far instantiated, by repr string
def __init__(
self,
i7e_sheet, # used by subclasses
reference_row_index=0, # used by subclasses
reference_column_index=0 # used by subclasses
) -> None:
self.i7e_sheet = i7e_sheet
self.reference_column_index = reference_column_index
self.reference_row_index = reference_row_index
self.sheet = self # returns self, as required by WorkBookComponent
assert repr(self) not in Sheet._all_sheets
Sheet._all_sheets[repr(self)] = self
@staticmethod
def factory(i7e_sheet, ref_row_index=0, ref_col_index=0) -> 'Sheet':
"""
Factory method return Sheet.
This method does not create duplicate sheets,
instead, it returns a reference to a pre-existing sheet
if one exists.
:return: Sheet
"""
sheet_class = Office.get_sheet_class()
key = sheet_class.key(i7e_sheet)
try:
return Sheet._all_sheets[key]
except KeyError:
return sheet_class(
i7e_sheet=i7e_sheet,
reference_column_index=ref_col_index,
reference_row_index=ref_row_index
)
@staticmethod
def key(i7e_sheet):
return i7e_sheet
def get_column(
self,
column_identifier: int or float or str
) -> 'Column':
"""
Gets column by name if identifier is str, otherwise,
attempts to get column by index.
:param column_identifier: int, float, or str
:return: Office.Column
"""
if isinstance(column_identifier, str):
return self.get_column_by_name(column_identifier)
else:
return self.get_column_by_index(column_identifier)
def get_column_by_index(self, column_index: int) -> 'Column':
"""
Gets column in Sheet by passed index.
Implemented by sub-classes.
:param column_index: int
:return: Column
"""
return Column.factory(
sheet=self,
index=column_index,
reference_index=self.reference_column_index
)
def get_column_by_name(self, column_name: int or float or str) -> 'Column':
"""
Gets column from a passed reference value which is compared
to each cell value in the reference row.
This function will return the first column whose name matches
the passed value.
:return: Office.Column
"""
i = self.get_column_index_from_name(column_name)
return self.get_column_by_index(i) if i is not None else None
def get_column_index_from_name(
self,
column_name: int or float or str
) -> int or None:
"""
Gets column index from name
:param column_name: int, float, or str
:return: int or None
"""
# todo: cache this
for x, cell in enumerate(self.reference_row):
if cell.value == column_name:
return x
def get_row(self, row_identifier: int or float or str) -> 'Row':
"""
Gets row by name if identifier is str, otherwise by index
:param row_identifier: int, float, or str
:return: Office.Row
"""
if isinstance(row_identifier, str):
return self.get_row_by_name(row_identifier)
else:
return self.get_row_by_index(row_identifier)
def get_row_by_index(self, row_index: int or str) -> 'Row':
"""
Gets row by passed index.
Implemented by subclasses.
:param row_index: int
:return: Row
"""
return Row.factory(
sheet=self,
index=row_index,
reference_index=self.reference_row_index
)
def get_row_by_name(self, row_name: int or str or float) -> 'Row':
"""
Gets row from a passed reference value which is compared
to each cell value in the reference row.
This function will return the first row whose name matches
the passed value.
:return: Office.Column
"""
y = self.get_row_index_from_name(row_name)
return self.get_row_by_index(y) if y is not None else None
def get_row_index_from_name(
self,
row_name: int or float or str
) -> int or None:
"""
Gets index of a row from passed name
:param row_name: int, float, or str
:return: int or None
"""
for y, cell in enumerate(self.reference_column):
if cell.value == row_name:
return y
def get_cell(self, cell_identifier, **kwargs) -> 'Cell':
"""
Gets cell from Sheet.
May be identified as;
example_sheet.get_cell((x, y))
example_sheet.get_cell((row_name, column_name))
example_sheet.get_cell((row_name, y_int))
Assumes that a passed number is a row or column index.
If a number is to be passed as a row or sheet name,
pass as a kwarg x_identifier_type='name' or
y_identifier_type='name'.
Also valid: x_identifier_type='index'
:param cell_identifier: tuple
:param kwargs: strings
:return:
"""
# if cell_identifier is list or tuple, get cell via
# x, y coordinates
if isinstance(cell_identifier, (list, tuple)):
x_identifier = cell_identifier[0]
y_identifier = cell_identifier[1]
x_identifier_type = kwargs.get('x_identifier_type', None)
y_identifier_type = kwargs.get('y_identifier_type', None)
# sanity check
assert x_identifier_type in ('index', 'name', None), \
"x identifier type should be 'index', 'name', or None." \
"Instead got %s" % x_identifier_type
assert y_identifier_type in ('index', 'name', None), \
"y identifier type should be 'index', 'name', or None." \
'instead got %s' % y_identifier_type
if (x_identifier_type == 'name' or
x_identifier_type is None and isinstance(
x_identifier, str)):
x = self.get_column_index_from_name(x_identifier)
else:
assert isinstance(x_identifier, int) # sanity check
x = x_identifier
if (y_identifier_type == 'name' or
y_identifier_type is None and isinstance(
y_identifier, str)):
y = self.get_row_index_from_name(y_identifier)
else:
assert isinstance(y_identifier, int) # sanity check
y = y_identifier
# We now have x and y indices for the cell
# now we call the cell factory method, which returns a cell
# of the correct type. The Cell factory method will not
# create duplicate cells, instead it will return a
# reference to the pre-existing cell in that sheet+position
return Cell.factory(sheet=self, position=(x, y))
@property
def reference_row_index(self) -> int:
"""
Gets index of reference row
:return: int
"""
return self._reference_row_index
@reference_row_index.setter
def reference_row_index(self, new_index: int) -> None:
"""
Sets reference row by passing the index of the new row.
Must be > 0
:param new_index: int
:return: None
"""
if new_index < 0:
raise IndexError('Reference row index must be > 0')
self._reference_row_index = new_index
@property
def reference_row(self) -> 'Row':
"""
Gets reference row
:return: Office.Row
"""
return self.get_row(self.reference_row_index)
@property
def reference_column_index(self) -> int:
"""
Gets index of reference column
:return: int
"""
return self._reference_column_index
@reference_column_index.setter
def reference_column_index(self, new_index) -> None:
"""
Sets reference column by passing the index of the new
reference column.
Must be > 0.
:param new_index: int
:return: None
"""
if new_index < 0:
raise IndexError('Reference row index must be > 0')
self._reference_column_index = new_index
@property
def reference_column(self) -> 'Column':
"""
Gets reference column
:return: Office.Column
"""
return self.get_column(self.reference_column_index)
@property
def columns(self) -> 'LineSeries':
"""
Gets iterator of columns in sheet
:return: Iterator[Column]
"""
return LineSeries(reference_line=self.reference_row)
@property
def table_columns(self) -> 'LineSeries':
"""
Gets iterator of columns in sheet's table contents
:return: Iterator[Column]
"""
return LineSeries(
reference_line=self.reference_column,
start_index=self.table_col_start_i
)
@property
def table_col_start_i(self) -> int:
"""
Gets index of first column in sheet's table.
By default, this is the first column after the reference column.
This value may also be explicitly set by passing an int to this
property setter.
:return: int
"""
if self._table_col_start is not None:
return self._table_col_start
else:
return self._reference_column_index + 1
@table_col_start_i.setter
def table_col_start_i(self, new_i: int) -> None:
"""
Sets first column which is included in table_columns.
:param new_i: int
:return: None
"""
if new_i is not None or not isinstance(new_i, int):
raise TypeError(
'New index should be an integer, or None. Got: %s'
% repr(new_i)
)
self._table_col_start = new_i
@property
def rows(self) -> 'LineSeries':
"""
Gets iterator of rows in Sheet.
:return: Iterator[Row]
"""
return LineSeries(reference_line=self.reference_column)
@property
def table_rows(self) -> 'LineSeries':
"""
Gets iterator of table rows in Sheet
:return: Iterator[Row]
"""
return LineSeries(
reference_line=self.reference_column,
start_index=self.table_row_start_i
)
@property
def table_row_start_i(self) -> int:
"""
Gets index of first row in sheet's table.
By default, this is the first row after the reference row.
This value may also be explicitly set by passing an int to this
property setter.
:return: int
"""
if self._content_row_start is not None:
return self._content_row_start
else:
return self.reference_row_index + 1
@table_row_start_i.setter
def table_row_start_i(self, new_i: int) -> None:
"""
Sets first row which is included in table_columns.
:param new_i: int
:return: None
"""
if new_i is not None or not isinstance(new_i, int):
raise TypeError(
'New index should be an integer, or None. Got: %s'
% repr(new_i)
)
self._content_row_start = new_i
def take_snapshot(
self,
width: int=None,
height: int=None,
frozen_size: bool=False
):
"""
Gets snapshot of sheet as it currently exists, and uses that
for all reading and writing of values.
The snapshot will by default include all values within the
width of the reference row, and within the height of the
reference column. Values outside that area may be overridden
if the range is expanded.
The snapshot can be prevented from growing by setting
frozen_size to True.
If a snapshot has already been taken, it is replaced, along
with any changes made to it.
:param width: int
:param height: int
:param frozen_size: bool
:return: None
"""
if height is None:
height = len(self.reference_column)
if width is None:
width = len(self.reference_row)
if height == 0 and width > 0:
height = 1 # if width > 0, then a reference row was found
if width == 0 and height > 0:
width = 1 # if height > 0, then a reference col was found
self._snapshot = self.Snapshot(self, width, height, frozen_size)
def write_snapshot(self):
"""
Writes values in snapshot to memory in one single write
(much, much faster than writing each cell individually)
:return: None
"""
self._snapshot.write()
def discard_snapshot(self):
"""
Throws out snapshot along with all changes made to it
:return: None
"""
self._snapshot = None
@property
def snapshot(self) -> None or 'Snapshot':
return self._snapshot
@property
def screen_updating(self) -> bool or None:
"""
Gets bool of whether screen updating occurs on sheet.
does nothing here, may be overridden by subclasses.
returns None if this sheet type does not support this method.
:return: bool
"""
return
@screen_updating.setter
def screen_updating(self, new_bool: bool) -> None:
"""
Sets whether sheet refreshes its display after update of
values, etc.
Does nothing here, subclasses may implement this method.
:param new_bool: bool
:return: None
"""
return
@property
def parents(self):
return # nothing to yield or return
@property
def instantiated_parents(self):
return # nothing to yield or return
def __str__(self) -> str:
raise NotImplementedError
def __repr__(self) -> str:
raise NotImplementedError
class Snapshot:
"""
Class storing a sheet entirely in memory, so that individual
reads and writes to a sheet can be grouped together.
Snapshot is sub-classed within XW and Uno.
"""
def __init__(
self,
sheet: 'Sheet',
width: int,
height: int,
frozen_size: bool
) -> None:
self._sheet = sheet
self._height = height
self._width = width
self.frozen_size = frozen_size
self._values = self._get_values()
def _get_values(self) -> list:
"""
Gets list of lists containing values of cells within snapshot
:return: list[list[str, float or None]]
"""
raise NotImplementedError
def _grow(self, new_width: int=None, new_height: int=None) -> None:
"""
Grows snapshot to new passed size.
If passed width or height is smaller than the present size,
the snapshot will stay the same size, it will not shrink.
:param new_width: int
:param new_height: int
:return: None
"""
if new_height < self._height:
new_height = self._height
if new_width < self._width:
new_width = self._width
height_difference = new_height - self._height
width_difference = new_width - self._width
# first add rows
if height_difference:
self._values += [[None] * new_width] * height_difference
# then columns
if width_difference:
for i in range(0, self._height): # for each pre-existing row
self._values[i] += [None] * width_difference
self._width = new_width
self._height = new_height
def get_value(self, x: int, y: int) -> str or float or int or None:
""""
Gets value of cell at x, y.
Throws IndexError if x or y is outside range of snapshot.
:param x: int
:param y: int
:return str, float, int or None
"""
try:
row = self._values[y]
except IndexError:
raise IndexError('Snapshot:get_value: %s is outside height of '
'snapshot. (height:%s)' %
(x, self._height))
else:
try:
return row[x] # return value
except IndexError:
raise IndexError(
'Snapshot:get_value: %s is outside width of '
'snapshot. (width:%s)' %
(x, self._width))
def set_value(self, x: int, y: int, value) -> None:
"""
Sets value of cell at x, y. (to be committed to cell when
snapshot is written.)
Throws IndexError if x or y is outside range of snapshot
:param x: int
:param y: int
:param value: Any
:return: None
"""
if not isinstance(value, (int, float, str, None)):
raise TypeError(
'Snapshot:set_value: Passed value should be an int, float'
' , str, or None. Got: %s' % repr(value))
if x >= self._width or y >= self._height:
if self.frozen_size:
raise IndexError(
'Snapshot:set_value: (%s, %s) is outside range of '
'snapshot (size: (%s, %s)' %
(x, y, self._width, self._height)
)
self._grow(x + 1, y + 1)
self._values[y][x] = value
def write(self):
"""
Commits values in snapshot to sheet in a single bulk write
:return: None
"""
raise NotImplementedError
class LineSeries:
"""Class storing collection of Line, Column, or Row objects"""
COLUMNS_STR = 'columns'
ROWS_STR = 'rows'
def __init__(
self,
reference_line: 'Line',
start_index: int=0, # iterator start index
end_index: int=None, # iterator end index (exclusive)
) -> None:
if not isinstance(reference_line, Line):
raise TypeError('Expected LineSeries to be passed reference line.'
'Got instead: %s' % repr(reference_line))
self.reference_line = reference_line
self.start_index = start_index
self.end_index = end_index
def __getitem__(self, item: int or float or str):
"""
If item is int, returns line of that index, otherwise looks
for a line of that name.
:param item: int, float, or str
:return: Line or None
"""
if isinstance(item, int):
return self.get_by_index(item)
else:
return self.get_by_name(item)
def __iter__(self):
"""
Returns Generator that iterates over columns in LineSeries
:return: Generator<Line>
"""
# find whether this is a series of rows or columns
if self.end_index is not None:
ref_cells = self.reference_line[self.start_index:self.end_index]
else:
ref_cells = self.reference_line[self.start_index:]
for cell in ref_cells:
if self._contents_type == LineSeries.COLUMNS_STR:
yield cell.column
if self._contents_type == LineSeries.ROWS_STR:
yield cell.rows
def __len__(self) -> int:
"""
Returns size of LineSeries
:return: int
"""
count = self.start_index
try: # it feels like there should be a better way to do this
assert self.end_index is None or isinstance(self.end_index, int)
# while there is a next cell, and it is inside range
while self.__iter__().__next__() and \
(self.end_index is None or count + 1 < self.end_index):
count += 1 # increment count
except StopIteration:
return count
def get_by_name(self, name: int or float or str) -> 'Line':
"""
Gets line from passed line name.
Returns None if no line of that name is found.
:param name: int, float or str
:return: Line or None
"""
for cell in self.reference_line:
if cell.value == name:
if self._contents_type == LineSeries.COLUMNS_STR:
return cell.column
elif self._contents_type == LineSeries.ROWS_STR:
return cell.row
def get_by_index(self, index: int) -> 'Line':
"""
Gets line from passed line index
:param index:
:return: Line
"""
if self._contents_type == 'rows':
return self.sheet.get_row_by_index(index)
elif self._contents_type == 'columns':
return self.sheet.get_column_by_index(index)
@property
def sheet(self) -> Sheet:
"""
Gets sheet that owns the Columns or Rows of this Lines obj.
:return: Sheet
"""
return self.reference_line.sheet
@property
def names(self):
"""
Yields names of lines in LineList
:return: int, float, or str
"""
for line in self:
yield line.name
@property
def named_only(self):
"""
Yields only lines in this series that have line headers
:return:
"""
for line in self:
if line.name:
yield line
@property
def indexes(self):
"""
Yields indexes of lines in LineList
:return: int