-
Notifications
You must be signed in to change notification settings - Fork 0
/
libreoffice_wrapper.py
2010 lines (1711 loc) · 84.8 KB
/
libreoffice_wrapper.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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tmux
tmux ls
tmux attach -t 0
tmux attach-session -t 0
tmux rename-session -t 0 new_name
tmux new -s session_name
tmux kill-session -t name
panes
ctrl+b % create panes vertical
ctrl+b <arrow-keys> move to panes
ctrl+b " create pane horizontal
windows:
ctrl+b c new window
ctrl+b 0 move to window 0
ctrl+b 1 move to window 1
ctrl+b , rename window
exit close window
sessions:
ctrl+b d detach
windows:
...
"""
# %%
import libtmux
import numpy as np
from pathlib import Path
import time
import psutil
import os
import signal
import re
import subprocess
import warnings
import sys
def start_soffice(port=8100, folder='/opt/libreoffice7.0', nodefault=True, norestore=False, nologo=False, tmux_config=True, timeout=10):
# set libreoffice folder
folder = Path(folder)/'program'
# tmux server
if tmux_config:
tmux_server = libtmux.Server(config_file=str(Path(os.path.dirname(__file__))/'tmux.conf'))
else:
tmux_server = libtmux.Server()
# new session
if tmux_server.has_session('libreoffice-wrapper'):
tmux_session = tmux_server.find_where({'session_name':'libreoffice-wrapper'})
else:
tmux_session = tmux_server.new_session('libreoffice-wrapper')
# new pane
if tmux_session.find_where({'window_name':'soffice'}) is None:
tmux_pane = tmux_session.new_window(attach=False, window_name='soffice').panes[0]
else:
tmux_pane = tmux_session.find_where({'window_name':'soffice'}).panes[0]
time.sleep(1)
tmux_pane.capture_pane = lambda: [x.rstrip() for x in tmux_pane.cmd('capture-pane', '-p', '-J').stdout]
# initialize libreoffice
print('Initialing soffice (it may take a few moments.)')
tmux_pane.send_keys(f'cd {folder}', enter=True, suppress_history=True)
time.sleep(0.1)
options = ''
if nodefault:
options += ' --nodefault'
if norestore:
options += ' --norestore'
if nologo:
options += ' --nologo'
tmux_pane.send_keys(f"./soffice{options} --accept='socket,host=localhost,port={port};urp;' &", enter=True, suppress_history=True)
time.sleep(0.1)
pid = 0
start_time = time.time()
while time.time() < start_time + timeout:
try:
pid = int(tmux_pane.capture_pane()[-2].split()[-1])
if pid != 0:
print(f'soffice started\nProcess pid {pid}')
if not _has_pid(pid):
warnings.warn(f'\nsoffice seems to be already running. \nCommunication stabilished. \nNote that killing this process (pid={pid}) will not close soffice', stacklevel=2)
return pid
except ValueError:
pass
raise TimeoutError(f'soffice taking more than {timeout_soffice} seconds to load. Maybe try again.')
def _has_pid(pid):
for proc in psutil.process_iter():
if proc.as_dict(attrs=['pid'])['pid'] == pid: return True
return False
def _get_children(pid):
output = subprocess.check_output(["bash", "-c", f"pstree -p -n {pid}"])
pattern = re.compile(r"\((\d+)\)")
pid_children = pattern.findall(output.decode('utf-8'))
return [int(pid) for pid in pid_children]
def kill(*args, recursive=True):
"""Kill processes."""
try:
if recursive:
pid2 = []
for pid in args:
for p in _get_children(pid):
pid2.append(p)
else:
pid2 = args
except TypeError:
if recursive:
pid2 = []
for pid in args[0]:
for p in _get_children(pid):
pid2.append(p)
else:
pid2 = args
for pid in pid2:
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
def kill_tmux(session_name='libreoffice-wrapper'):
tmux_server = libtmux.Server()
if tmux_server.has_session('libreoffice-wrapper'):
tmux_server.kill_server()
def str2bool(string):
if string == 'False':
return False
else:
return True
def _name2ImplementationName(name):
if name == 'scalc' or name == 'calc':
return 'ScModelObj'
elif name == 'swriter' or name == 'writer':
return 'SwXTextDocument'
elif name == 'simpress' or name == 'impress' or name == 'draw':
return 'SdXImpressDocument'
elif name == 'smath' or name == 'math':
return 'com.sun.star.comp.Math.FormulaDocument'
elif name == 'base' or name == 'sbase' or name == 'obase':
return 'com.sun.star.comp.dba.ODatabaseDocument'
else:
raise ValueError('type must be calc, writer, impress, draw, math, or base')
def query_yes_no(question, default="yes"):
"""Ask a yes/no question and return answer.
Note:
It accepts many variations of yes and no as answer, like, "y", "YES", "N", ...
Args:
question (str): string that is presented to the user.
default ('yes', 'no' or None): default answer if the user just hits
<Enter>. If None, an answer is required of the user.
Returns:
True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "Y": True, "YES": True, "YE": True,
"no": False, "n": False, "No":True, "NO":True, "N":True}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt + '\n')
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"('y' or 'n').\n")
def _letter2num(string):
string = string.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
n = 0
for idx, s in enumerate(string):
n += alphabet.index(s)+(idx)*26
return n
def cell2num(string):
if not isinstance(string, str):
raise TypeError('value is not a cell.')
if ':' in string:
raise ValueError('cell seems to be a range.')
try:
temp = re.compile("([a-zA-Z]+)([0-9]+)")
res = temp.match(string).groups()
return _letter2num(res[0]), int(res[1])-1
except AttributeError:
raise ValueError('value is not a cell.')
def range2num(string):
if ':' not in string:
raise ValueError('range seems to be a cell.')
return flatten((cell2num(string.split(':')[0]), cell2num(string.split(':')[1])))
def _check_row_value(row):
if type(row) == str:
row = int(row)-1
if row < 0:
raise ValueError('row cannot be negative')
return row
def _check_column_value(column):
if type(column) == str:
column = _letter2num(column)
if column < 0:
raise ValueError('column cannot be negative')
return column
def flatten(x):
"""Returns the flattened list or tuple."""
if len(x) == 0:
return x
if isinstance(x[0], list) or isinstance(x[0], tuple):
return flatten(x[0]) + flatten(x[1:])
return x[:1] + flatten(x[1:])
def transpose(l):
"""Transpose lists."""
try:
row_count, col_count = np.shape(l)
return [list(x) for x in list(zip(*l))]
except ValueError:
return [[x] for x in l]
def chunk(lst, n):
for i in range(0, len(lst), n):
yield lst[i:i + n]
def partitionate(value, max_string=4000, i=1):
# find i
while len(str(value)) > max_string:
i += 1
if i >= len(value):
raise ValueError(f'It seemns like length of rows are too big. Try setting shorter rows at a time and/or setting shorter data (less characters)')
g = chunk(value, int(len(value)/i))
while True:
try:
if len(str(next(g))) > max_string:
return partitionate(value, max_string=max_string, i=i)
except StopIteration:
break
return chunk(value, int(len(value)/i))
return chunk(value, int(len(value)/i))
def _parse_args(args, kwargs, req_args=[], opt_args=[]):
"""
opt_args must be given in kwargs
Range
cell_start, cell_stop
column_start, row_start, column_stop, row_stop
cell
column, row
"""
req = {k:False for k in req_args}
opt = {k:None for k in opt_args}
for i, k in enumerate(opt_args):
if k in kwargs:
opt[k] = kwargs[k]
lookout = 0
del_list = []
for i, k in enumerate(req_args):
try:
req[k] = kwargs[k]
del_list.append(k)
except KeyError:
lookout += 1
for k in del_list:
del req_args[req_args.index(k)]
for i in range(lookout):
req[req_args[::-1][i]] = args[::-1][i]
if lookout != 0:
args = args[:-lookout]
isRange = False
if len(args) == 0:
isRange = -1
elif len(args) == 1:
try:
column_start, row_start = cell2num(args[0])
except ValueError:
column_start, row_start, column_stop, row_stop = range2num(args[0])
isRange = True
elif len(args) == 2:
try:
column_start, row_start = cell2num(args[0])
column_stop, row_stop = cell2num(args[1])
isRange = True
except TypeError:
column_start = args[0]
row_start = args[1]
except ValueError:
column_start = args[0]
row_start = args[1]
elif len(args) == 3:
raise ValueError('cannot parse arguments.')
elif len(args) == 4:
column_start = args[0]
row_start = args[1]
column_stop = args[2]
row_stop = args[3]
isRange = True
if 'column' in kwargs:
column_start = kwargs['column']
isRange = False
if 'row' in kwargs:
row_start = kwargs['row']
isRange = False
if 'column_start' in kwargs:
column_start = kwargs['column_start']
isRange = False
if 'row_start' in kwargs:
row_start = kwargs['row_start']
isRange = False
if 'column_stop' in kwargs:
column_stop = kwargs['column_stop']
isRange = True
if 'row_stop' in kwargs:
row_stop = kwargs['row_stop']
isRange = True
if 'cell' in kwargs:
column_start, row_start = cell2num(kwargs['cell'])
isRange = False
if 'cell_start' in kwargs:
column_start, row_start = cell2num(kwargs['cell_start'])
isRange = False
if 'cell_stop' in kwargs:
column_stop, row_stop = cell2num(kwargs['cell_stop'])
isRange = True
if 'Range' in kwargs:
column_start, row_start, column_stop, row_stop = range2num(kwargs['Range'])
isRange = True
if isRange == -1:
return -1, (), req, opt
else:
column_start = _check_column_value(column_start)
row_start = _check_row_value(row_start)
if isRange:
column_stop = _check_column_value(column_stop)
row_stop = _check_row_value(row_stop)
if column_stop < column_start:
raise ValueError(f'column_start ({column_start}) cannot be bigger than column_stop ({column_stop})')
if row_stop < row_start:
raise ValueError(f'row_start ({row_start}) cannot be bigger than row_stop ({row_stop})')
return True, (column_start, row_start, column_stop, row_stop), req, opt
else:
return False, (column_start, row_start), req, opt
operator_map = {0:('is equal to', 'equal', '=', '==', 'EQUAL'),
1:('is less than', 'less', '<', 'LESS'),
2:('is greater than', 'greater', '>', 'GREATER'),
3:('is less than or equal to', 'less-equal', 'less equal', '<=', 'LESS_EQUAL'),
4:('is greater than or equal to', 'greater-equal', 'greater equal', '>=', 'GREATER_EQUAL'),
5:('is not equal to', 'not-equal', 'not equal', '<>', '!=', 'NOT_EQUAL'),
6:('is between', 'between', 'BETWEEN'),
7:('is not between', 'not-between', 'not between', 'NOT_BETWEEN'),
8:('is duplicated', 'duplicated', 'DUPLICATED', ''),
9:('is not duplicated', 'not-duplicated', 'not duplicated', 'NOT_DUPLICATED', ''),
10:('is in top N elements', 'is in top n elements', 'top', 'top n', 'top-n', 'TOP', ''),
11:('is in bottom N elements', 'is in bottom n elements', 'bottom', 'bottom n', 'bottom-n', 'BOTTOM', ''),
12:('is in top N percent', 'is in top n percent', 'top percent', 'top-percent', 'top n percent', 'top-n-percent', 'TOP_PERCENT', ''),
13:('is in bottom N percent', 'is in bottom n percent', 'bottom percent', 'bottom-percent', 'bottom n percent', 'bottom-n-percent', 'BOTTOM_PERCENT', ''),
14:('is above average', 'above', 'above average', 'above-average', 'ABOVE', ''),
15:('is below average', 'below', 'below average', 'below-average', 'BELOW', ''),
16:('is above or equal average', 'above equal', 'above-equal', 'above equal average', 'above-equal-average', 'ABOVE-EQUAL', ''),
17:('is below or equal average', 'below equal', 'below-equal', 'below equal average', 'below-equal-average', 'BELOW-EQUAL', ''),
18:('is error', 'error', 'ERROR', ''),
19:('is not error', 'not error', 'not-error', 'NOT-ERROR', ''),
20:('begins with', 'begins', 'BEGINS', ''),
21:('ends with', 'ends', 'ENDS', ''),
22:('contains', 'CONTAINS', ''),
23:('does not contain', 'not contain', 'not-contain', 'NOT_CONTAIN', ''),
24:('formula', 'Formula', 'FORMULA'),
}
class soffice():
def __init__(self, tmux_config=True, port=8100, folder='/opt/libreoffice7.0'):
"""
server -> session (pycalc) -> window (soffice-python) -> pane (0)
"""
timeout_python = 10
timeout_soffice = 60
# set libreoffice folder
self.folder = Path(folder)/'program'
# tmux server
if tmux_config:
self.tmux_server = libtmux.Server(config_file=str(Path(os.path.dirname(__file__))/'tmux.conf'))
else:
self.tmux_server = libtmux.Server()
# new session
if self.tmux_server.has_session('libreoffice-wrapper'):
self.tmux_session = self.tmux_server.find_where({'session_name':'libreoffice-wrapper'})
else:
self.tmux_session = self.tmux_server.new_session('libreoffice-wrapper')
# new pane
if self.tmux_session.find_where({'window_name':'python'}) is None:
self.tmux_pane = self.tmux_session.new_window(attach=False, window_name='python').panes[0]
else:
self.tmux_pane = self.tmux_session.find_where({'window_name':'python'}).panes[0]
time.sleep(1)
self.tmux_pane.capture_pane = lambda starting_line=0: [x.rstrip() for x in self.tmux_pane.cmd('capture-pane', '-p', '-J', f'-S {starting_line}').stdout]
# initialize python
print('Initialing python (it may take a few moments.)')
self.tmux_pane.send_keys(f'cd {self.folder}', enter=True, suppress_history=True)
time.sleep(0.1)
self.tmux_pane.send_keys('./python', enter=True, suppress_history=True)
start_time = time.time()
flag = True
while time.time() < start_time + timeout_python:
if self.tmux_pane.capture_pane()[-1] == '>>>':
print('done')
flag = False
break
if flag:
raise TimeoutError(f'Python taking more than {timeout_python} seconds to load. Maybe try again.')
# python imports
print('Importing modules (it may take a few moments.)')
self.tmux_pane.send_keys(f"""try: exec(\"import traceback\")""" + '\n'\
"""except Exception as e: print(e)""" + '\n'
, enter=True, suppress_history=False)
start_time = time.time()
while time.time() < start_time + 10:
if self.check_running():
pass
else:
break
self.write(f"""import uno\n"""+\
f"""from com.sun.star.beans import PropertyValue\n"""
)
time.sleep(0.1)
print('done')
# initialize communication
print('Initializing comunications (it may take a few moments.)')
self.write(f"""local = uno.getComponentContext()\n""" +\
f"""resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)\n""" +\
f"""context = resolver.resolve("uno:socket,host=localhost,port={port};urp;StarOffice.ComponentContext")\n""" +\
f"""desktop = context.ServiceManager.createInstanceWithContext('com.sun.star.frame.Desktop', context)\n"""
)
time.sleep(0.1)
# self.write("local = uno.getComponentContext()")
# time.sleep(0.1)
# self.write("""resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)""")
# time.sleep(0.1)
# self.write(f"""context = resolver.resolve("uno:socket,host=localhost,port={port};urp;StarOffice.ComponentContext")""")
# time.sleep(0.1)
# self.write("desktop = context.ServiceManager.createInstanceWithContext('com.sun.star.frame.Desktop', context)")
# time.sleep(0.1)
try:
self._get_tag()
except soffice_python_error:
self._set_tag(0)
time.sleep(0.1)
print('done')
def _get_tag(self):
return int(self.write("print(tag)")[0])
def _set_tag(self, tag):
self.write(f"tag = {tag}")
def kill(self, force_kill=False):
if self.tmux_server.has_session('libreoffice-wrapper') and force_kill == False:
tmux_session = self.tmux_server.find_where({'session_name':'libreoffice-wrapper'})
if tmux_session.find_where({'window_name':'soffice'}) is None:
self.tmux_server.kill_server()
else:
self.write("documents = desktop.getComponents().createEnumeration()")
hasMoreElements = str2bool(self.write("print(documents.hasMoreElements())")[0])
if hasMoreElements:
print('Killing this process will close (without saving) the following opened files')
while hasMoreElements:
self.write("document = documents.nextElement()")
print(self.write(f"print(document.getImplementationName())")[0] + ': ' + self.write(f"document.getTitle()")[0])
hasMoreElements = str2bool(self.write("print(documents.hasMoreElements())")[0])
if query_yes_no('Continue?', 'no'):
self.tmux_server.kill_server()
else:
self.tmux_server.kill_server()
def check_running(self):
# if self.tmux_pane.capture_pane()[-1] in ['>>>', '... >>>', '... ... >>>']:
if self.tmux_pane.capture_pane()[-1].endswith('>>>'):
return False
else:
return True
def write(self, string, timeout=10, max_output=1000):
# check quotes
keys2send = f"try: exec(\"\"\"{string}\"\"\")" + '\n'\
"""except: print('calc-ERROR'); print(traceback.format_exc())"""
self.tmux_pane.send_keys(keys2send, enter=True, suppress_history=False)
self.tmux_pane.enter()
# time.sleep(0.05)
time.sleep(0.001)
start_time = time.time()
while time.time() < start_time + timeout:
if self.check_running():
pass
else:
# output = self.tmux_pane.capture_pane()
# i = output[::-1].index('>>> ' + keys2send.split('\n')[0])
output = self.tmux_pane.capture_pane()
starting_line = 0
while '>>> ' + keys2send.split('\n')[0] not in output and starting_line>-max_output:
starting_line -= 10
output = self.tmux_pane.capture_pane(starting_line)
if starting_line<-max_output:
raise valueError(f'output seems to be bigger than max_output {max_output}.')
i = output[::-1].index('>>> ' + keys2send.split('\n')[0])
if 'calc-ERROR' in output[-i:]:
f = output[::-1].index('>>>')
# try:
# i = output[::-1].index('.calc-ERROR')
# except ValueError:
# i = [i for i, s in enumerate(output[-i::-1]) if 'calc-ERROR' in s][0]
raise soffice_python_error('\n'.join(output[-i:-1+f]))
else:
return output[-i+2:-1]
# i = output[::-1].index('>>> ' + keys2send.split('\n')[0])
# if output[-i+2] == 'calc-ERROR':
# f = output[::-1].index('>>>')
# raise soffice_python_error('\n'.join(output[-i+3:-1+f]))
# elif output[-i+2].startswith('...'):
# if output[-i+3] == 'calc-ERROR':
# f = output[::-1].index('>>>')
# raise soffice_python_error('\n'.join(output[-i+4:-1+f]))
# else:
# return output[-i+3:-1]
# else:
# return output[-i+2:-1]
raise TimeoutError(f'timeout: {timeout}s. Process is still running.')
def read(self, timeout=10, max_output=1000):
start_time = time.time()
while time.time() < start_time + timeout:
if self.check_running():
pass
else:
output = self.tmux_pane.capture_pane()
starting_line = 0
while '>>>' not in output[:-1] and starting_line>-max_output:
starting_line -= 10
output = self.tmux_pane.capture_pane(starting_line)
if starting_line<-max_output:
raise valueError(f'output seems to be bigger than max_output {max_output}.')
output = output[[i for i, x in enumerate(output[:-1]) if x.startswith('>>>')][-1]+3:-1]
if len(output) > 0:
if output[0] == 'calc-ERROR':
raise soffice_python_error('\n'.join(output))
else:
return output
else:
return output
raise TimeoutError(f'timeout: {timeout}s. Process is still running.')
def Calc(self, filepath=None, new_file=False):
type = 'scalc'
if new_file:
tag = self._new_file(type=type)
elif filepath is None: # if a filepath is not defined
print('Filepath was not given.')
if self._has_open():
print('However, something is open.')
tag = self._connect_with_open(type=type)
if not tag:
print(f'Opening a new file...')
tag = self._new_file(type=type)
else: # if nothing is open, open a new calc instance
print(f'Nothing is opened.')
tag = self._new_file(type=type)
else:
tag = self._open_file(filepath)
return Calc(tag, soffice=self)
def Writer(self, filepath=None, new_file=False):
type = 'swriter'
if new_file:
tag = self._new_file(type=type)
elif filepath is None: # if a filepath is not defined
print('Filepath was not given.')
if self._has_open():
print('However, something is open.')
tag = self._connect_with_open(type=type)
if not tag:
print(f'Opening a new file...')
tag = self._new_file(type=type)
else: # if nothing is open, open a new calc instance
print(f'Nothing is opened.')
tag = self._new_file(type=type)
else:
tag = self._open_file(filepath)
return Writer(tag, soffice=self)
def Impress(self, filepath=None, new_file=False):
type = 'simpress'
if new_file:
tag = self._new_file(type=type)
elif filepath is None: # if a filepath is not defined
print('Filepath was not given.')
if self._has_open():
print('However, something is open.')
tag = self._connect_with_open(type=type)
if not tag:
print(f'Opening a new file...')
tag = self._new_file(type=type)
else: # if nothing is open, open a new calc instance
print(f'Nothing is opened.')
tag = self._new_file(type=type)
else:
tag = self._open_file(filepath)
return Impress(tag, soffice=self)
def Draw(self, filepath=None, new_file=False):
type = 'sdraw'
if new_file:
tag = self._new_file(type=type)
elif filepath is None: # if a filepath is not defined
print('Filepath was not given.')
if self._has_open():
print('However, something is open.')
tag = self._connect_with_open(type=type)
if not tag:
print(f'Opening a new file...')
tag = self._new_file(type=type)
else: # if nothing is open, open a new calc instance
print(f'Nothing is opened.')
tag = self._new_file(type=type)
else:
tag = self._open_file(filepath)
return Draw(tag, soffice=self)
def Math(self, filepath=None, new_file=False):
type = 'smath'
if new_file:
tag = self._new_file(type=type)
elif filepath is None: # if a filepath is not defined
print('Filepath was not given.')
if self._has_open():
print('However, something is open.')
tag = self._connect_with_open(type=type)
if not tag:
print(f'Opening a new file...')
tag = self._new_file(type=type)
else: # if nothing is open, open a new calc instance
print(f'Nothing is opened.')
tag = self._new_file(type=type)
else:
tag = self._open_file(filepath)
return Math(tag, soffice=self)
def Base(self, filepath=None, new_file=False):
raise NotImplementedError('Base not implemented yet')
def save(self, tag, type, extension, filepath=None):
"""Save file.
Args:
filepath (string or pathlib.Path, optional): filepath to save file.
"""
if filepath is None and self.get_filepath(tag)=='': # ok
temporary_path = Path.cwd()/self.get_title(tag)
temporary_path = temporary_path.with_suffix(extension)
if query_yes_no(f'Filepath not defined. Wish to save at {temporary_path}?'):
filepath = temporary_path
else:
print('File not saved')
return
elif filepath is None and self.get_filepath(tag)!='':
filepath = Path(self.get_filepath(tag)).with_suffix(extension)
else:
filepath = Path(filepath).with_suffix(extension)
# save
self.write(f'URL = uno.systemPathToFileUrl("{filepath}")')
self.write(f"properties = (PropertyValue('FilterName', 0, '{type}', 0),)")
self.write(f"document_{tag}.storeAsURL(URL, properties)")
time.sleep(0.1)
print(f'Saved at: {filepath}')
return self.get_filepath(tag)
def close(self, tag):
"""Close window."""
self.write(f'document_{tag}.close(True)')
self.write(f'del document_{tag}')
def get_filepath(self, tag):
hasFilepath = str2bool(self.write(f"print(document_{tag}.hasLocation())")[0])
if hasFilepath: # check if file has filepath
return self.write(f"print(uno.fileUrlToSystemPath(document_{tag}.getURL()))")[0]
else: return ''
def get_title(self, tag):
return self.write(f"print(document_{tag}.getTitle())")[0]
def _new_file(self, type):
"""type = calc or writer
https://wiki.documentfoundation.org/Macros/Basic/Documents
"""
if type == 'scalc' or type == 'calc':
self.write("URL = 'private:factory/scalc'")
elif type == 'swriter' or type == 'writer':
self.write("URL = 'private:factory/swriter'")
elif type == 'simpress' or type == 'impress':
self.write("URL = 'private:factory/SdXImpressDocument'")
elif type == 'sdraw' or type == 'draw':
self.write("URL = 'private:factory/sdraw'")
elif type == 'smath' or type == 'math':
self.write("URL = 'private:factory/smath'")
elif type == 'base' or type == 'obase' or type == 'sbase':
raise NotImplementedError('base not implemented yet')
else:
raise ValueError('type must be calc, writer, impress, draw, math, or base')
tag = self._get_tag() + 1
self._set_tag(tag)
self.write(f"document_{tag} = desktop.loadComponentFromURL(URL, '_default', 0, ())")
# time.sleep(0.1)
title = self.get_title(tag=tag)
time.sleep(0.1)
start_time = time.time()
while title is [] and time.time() < start_time + 10:
time.sleep(0.1)
title = self.get_title(tag=tag)
print(f'Connected with opened file: {title}')
return tag
def _open_file(self, filepath):
tag = self._get_tag() + 1
self._set_tag(tag)
print('Filepath was given.')
filepath = Path(filepath).absolute()
self.write(f"URL = uno.systemPathToFileUrl('{filepath}')")
self.write(f'document_{tag} = desktop.loadComponentFromURL(URL, "_default", 0, ())')
url = self.write(f"print(uno.fileUrlToSystemPath(document_{tag}.getURL()))")[0]
print(f'Connected with file: {url}')
return tag
def _has_open(self):
# is there something open???
self.write("document = desktop.getCurrentComponent()")
return str2bool(self.write("print('False') if document is None else print('True')")[0])
def _connect_with_open(self, type):
self.write(f"document = desktop.getCurrentComponent()")
implementationName = self.write(f"print(document.getImplementationName())")
if _name2ImplementationName(type) in implementationName:
return self._connect_with_current()
else:
print(f'current document is not type {type}.')
print(f'Searching for any opened {type} instances...')
self.write("documents = desktop.getComponents().createEnumeration()")
open_new = True
hasMoreElements = str2bool(self.write("print(documents.hasMoreElements())")[0])
while hasMoreElements:
self.write("document = documents.nextElement()")
implementationName = self.write("print(document.getImplementationName())")
if _name2ImplementationName(type) in implementationName:
tag = self._get_tag() + 1
self._set_tag(tag)
self.write(f"document_{tag} = document")
if self.get_filepath(tag) == '':
title = self.get_title(tag)
print(f'Connected with opened file: {title}')
else:
print(f'Connected with opened file: {self.get_filepath(tag)}')
return tag
hasMoreElements = str2bool(self.write("print(documents.hasMoreElements())")[0])
print(f'No opened {type} instances were found.')
return False
def _connect_with_current(self):
tag = self._get_tag() + 1
self._set_tag(tag)
self.write(f"document_{tag} = desktop.getCurrentComponent()")
print(f'Connecting with current file.')
time.sleep(0.1)
if self.get_filepath(tag) != '':
print(f'Connected with opened file: {self.get_filepath(tag)}')
else:
title = self.get_title(tag)
time.sleep(0.1)
start_time = time.time()
while title is [] and time.time() < start_time + 10:
time.sleep(0.1)
title = self.get_title(tag)
print(f'Connected with opened file: {title}')
return tag
class soffice_python_error(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
class Writer():
def __init__(self, tag, soffice):
self.soffice = soffice
self.tag = tag
self.sheet_tags = []
self.filepath = self.get_filepath()
def write(self, string, timeout=10):
return self.soffice.write(string=string, timeout=timeout)
def read(self, timeout=10):
return self.soffice.read(timeout=timeout)
def get_filepath(self):
return self.soffice.get_filepath(self.tag)
def get_title(self):
return self.soffice.get_title(self.tag)
def save(self, filepath=None, type='odt'):
if type in ['odt', '.odt', 'swriter', 'writer', 'Writer']:
type = 'writer8'
extension = '.odt'
else:
raise ValueError('type not recognised')
if filepath is None and self.filepath!='' and self.get_filepath()!='':
if self.filepath != self.get_filepath():
print('File was last saved in a different filepath than the one stored here.')
print('Last saved path:' + self.get_filepath())
print('Stored path:' + self.filepath)
if query_yes_no(f'Wish to save at {self.get_filepath()}?'):
# self.soffice.Calc(filepath()
filepath = self.get_filepath()
else:
if query_yes_no(f'Wish to save at {self.filepath}?'):
filepath = self.filepath
else:
print('File not saved')
return
self.filepath = self.soffice.save(tag=self.tag, type=type, extension=extension, filepath=filepath)
def close(self):
"""Close window."""
for tag in self.sheet_tags:
try:
self.write(f'del document_{tag}')
except soffice_python_error:
pass
self.soffice.close(self.tag)
class Impress():
def __init__(self, tag, soffice):
self.soffice = soffice
self.tag = tag
self.sheet_tags = []
self.filepath = self.get_filepath()
def write(self, string, timeout=10):
return self.soffice.write(string=string, timeout=timeout)
def read(self, timeout=10):
return self.soffice.read(timeout=timeout)
def get_filepath(self):
return self.soffice.get_filepath(self.tag)
def get_title(self):
return self.soffice.get_title(self.tag)
def save(self, filepath=None, type='odp'):
if type in ['odp', '.odt', 'simpress', 'impress', 'Impress']:
type = 'impress8'
extension = '.odp'
else:
raise ValueError('type not recognised')
if filepath is None and self.filepath!='' and self.get_filepath()!='':
if self.filepath != self.get_filepath():
print('File was last saved in a different filepath than the one stored here.')
print('Last saved path:' + self.get_filepath())
print('Stored path:' + self.filepath)
if query_yes_no(f'Wish to save at {self.get_filepath()}?'):
# self.soffice.Calc(filepath()
filepath = self.get_filepath()
else:
if query_yes_no(f'Wish to save at {self.filepath}?'):
filepath = self.filepath
else:
print('File not saved')
return
self.filepath = self.soffice.save(tag=self.tag, type=type, extension=extension, filepath=filepath)
def close(self):
"""Close window."""
for tag in self.sheet_tags:
try:
self.write(f'del document_{tag}')
except soffice_python_error:
pass
self.soffice.close(self.tag)
class Draw():
def __init__(self, tag, soffice):
self.soffice = soffice
self.tag = tag
self.sheet_tags = []
self.filepath = self.get_filepath()
def write(self, string, timeout=10):
return self.soffice.write(string=string, timeout=timeout)
def read(self, timeout=10):
return self.soffice.read(timeout=timeout)