forked from boltex/leointeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leobridgeserver.py
3212 lines (2782 loc) · 110 KB
/
leobridgeserver.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
#! python3
import leo.core.leoBridge as leoBridge
import leo.core.leoNodes as leoNodes
from leo.core.leoGui import StringFindTabManager
import asyncio
import getopt
import json
import os.path
import sys
import time
import traceback
import websockets
# server defaults
wsHost = "localhost"
wsPort = 32125
# To help in printout
commonActions = ["getChildren", "getBody", "getBodyLength"]
# Special string signals server startup success
SERVER_STARTED_TOKEN = "LeoBridge started"
class IdleTimeManager:
"""
A singleton class to manage idle-time handling. This class handles all
details of running code at idle time, including running 'idle' hooks.
Any code can call g.app.idleTimeManager.add_callback(callback) to cause
the callback to be called at idle time forever.
"""
# TODO : REVISE/REPLACE WITH OWN SYSTEM
def __init__(self, g):
"""Ctor for IdleTimeManager class."""
self.g = g
self.callback_list = []
self.timer = None
self.on_idle_count = 0
def add_callback(self, callback):
"""Add a callback to be called at every idle time."""
self.callback_list.append(callback)
def on_idle(self, timer):
"""IdleTimeManager: Run all idle-time callbacks."""
if not self.g.app:
return
if self.g.app.killed:
return
if not self.g.app.pluginsController:
self.g.trace('No g.app.pluginsController', self.g.callers())
timer.stop()
return # For debugger.
self.on_idle_count += 1
# Handle the registered callbacks.
# print("list length : ", len(self.callback_list))
for callback in self.callback_list:
try:
callback()
except Exception:
self.g.es_exception()
self.g.es_print(f"removing callback: {callback}")
self.callback_list.remove(callback)
# Handle idle-time hooks.
self.g.app.pluginsController.on_idle()
def start(self):
"""Start the idle-time timer."""
self.timer = self.g.IdleTime(
self.on_idle,
delay=500, # Milliseconds
tag='IdleTimeManager.on_idle')
if self.timer:
self.timer.start()
class ExternalFilesController:
'''EFC Modified from Leo's sources'''
# pylint: disable=no-else-return
def __init__(self, integController):
'''Ctor for ExternalFiles class.'''
self.on_idle_count = 0
self.integController = integController
self.checksum_d = {}
# Keys are full paths, values are file checksums.
self.enabled_d = {}
# For efc.on_idle.
# Keys are commanders.
# Values are cached @bool check-for-changed-external-file settings.
self.has_changed_d = {}
# Keys are commanders. Values are boolean.
# Used only to limit traces.
self.unchecked_commanders = []
# Copy of g.app.commanders()
self.unchecked_files = []
# Copy of self file. Only one files is checked at idle time.
self._time_d = {}
# Keys are full paths, values are modification times.
# DO NOT alter directly, use set_time(path) and
# get_time(path), see set_time() for notes.
self.yesno_all_time = 0 # previous yes/no to all answer, time of answer
self.yesno_all_answer = None # answer, 'yes-all', or 'no-all'
# if yesAll/noAll forced, then just show info message after idle_check_commander
self.infoMessage = None
# False or "detected", "refreshed" or "ignored"
self.integController.g.app.idleTimeManager.add_callback(self.on_idle)
self.waitingForAnswer = False
self.lastPNode = None # last p node that was asked for if not set to "AllYes\AllNo"
self.lastCommander = None
def on_idle(self):
'''
Check for changed open-with files and all external files in commanders
for which @bool check_for_changed_external_file is True.
'''
# Fix for flushing the terminal console to traverse
# python through node.js when using start server in leoInteg
sys.stdout.flush()
if not self.integController.g.app or self.integController.g.app.killed:
return
if self.waitingForAnswer:
return
self.on_idle_count += 1
if self.unchecked_commanders:
# Check the next commander for which
# @bool check_for_changed_external_file is True.
c = self.unchecked_commanders.pop()
self.lastCommander = c
self.idle_check_commander(c)
else:
# Add all commanders for which
# @bool check_for_changed_external_file is True.
self.unchecked_commanders = [
z for z in self.integController.g.app.commanders() if self.is_enabled(z)
]
def idle_check_commander(self, c):
'''
Check all external files corresponding to @<file> nodes in c for
changes.
'''
# #1100: always scan the entire file for @<file> nodes.
# #1134: Nested @<file> nodes are no longer valid, but this will do no harm.
self.infoMessage = None # reset infoMessage
# False or "detected", "refreshed" or "ignored"
for p in c.all_unique_positions():
if self.waitingForAnswer:
break
if p.isAnyAtFileNode():
self.idle_check_at_file_node(c, p)
# if yesAll/noAll forced, then just show info message
if self.infoMessage:
w_package = {"async": "info", "message": self.infoMessage}
self.integController.sendAsyncOutput(w_package)
def idle_check_at_file_node(self, c, p):
'''Check the @<file> node at p for external changes.'''
trace = False
# Matt, set this to True, but only for the file that interests you.\
# trace = p.h == '@file unregister-leo.leox'
path = self.integController.g.fullPath(c, p)
has_changed = self.has_changed(path)
if trace:
self.integController.g.trace('changed', has_changed, p.h)
if has_changed:
self.lastPNode = p # can be set here because its the same process for ask/warn
if p.isAtAsisFileNode() or p.isAtNoSentFileNode():
# Fix #1081: issue a warning.
self.warn(c, path, p=p)
elif self.ask(c, path, p=p):
self.lastCommander.selectPosition(self.lastPNode)
c.refreshFromDisk()
# Always update the path & time to prevent future warnings.
self.set_time(path)
self.checksum_d[path] = self.checksum(path)
def integResult(self, p_result):
'''Received result from client'''
# Got the result to an asked question/warning from the client
if not self.waitingForAnswer:
print("ERROR: Received Result but no Asked Dialog", flush=True)
return
# check if p_resultwas from a warn (ok) or an ask ('yes','yes-all','no','no-all')
# act accordingly
path = self.integController.g.fullPath(
self.lastCommander, self.lastPNode)
# 1- if ok, unblock 'warn'
# 2- if no, unblock 'ask'
# ------------------------------------------ Nothing special to do
# 3- if noAll, set noAll, and unblock 'ask'
if p_result and "-all" in p_result.lower():
self.yesno_all_time = time.time()
self.yesno_all_answer = p_result.lower()
# ------------------------------------------ Also covers setting yesAll in #5
# 4- if yes, REFRESH self.lastPNode, and unblock 'ask'
# 5- if yesAll,REFRESH self.lastPNode, set yesAll, and unblock 'ask'
if bool(p_result and 'yes' in p_result.lower()):
self.lastCommander.selectPosition(self.lastPNode)
self.lastCommander.refreshFromDisk()
# Always update the path & time to prevent future warnings for this PNode.
self.set_time(path)
self.checksum_d[path] = self.checksum(path)
self.waitingForAnswer = False # unblock
# unblock: run the loop as if timer had hit
self.idle_check_commander(self.lastCommander)
def ask(self, c, path, p=None):
'''
Ask user whether to overwrite an @<file> tree.
Return True if the user agrees.
'''
# check with leoInteg's config first
if self.integController.leoIntegConfig:
w_check_config = self.integController.leoIntegConfig["defaultReloadIgnore"].lower(
)
if not bool('none' in w_check_config):
if bool('yes' in w_check_config):
self.infoMessage = "refreshed"
return True
else:
self.infoMessage = "ignored"
return False
# let original function resolve
if self.yesno_all_time + 3 >= time.time() and self.yesno_all_answer:
self.yesno_all_time = time.time() # Still reloading? Extend time.
# if yesAll/noAll forced, then just show info message
w_yesno_all_bool = bool('yes' in self.yesno_all_answer.lower())
return w_yesno_all_bool
if not p:
where = 'the outline node'
else:
where = p.h
_is_leo = path.endswith(('.leo', '.db'))
if _is_leo:
s = '\n'.join([
f'{self.integController.g.splitLongFileName(path)} has changed outside Leo.',
'Overwrite it?'
])
else:
s = '\n'.join([
f'{self.integController.g.splitLongFileName(path)} has changed outside Leo.',
f"Reload {where} in Leo?",
])
w_package = {"async": "ask", "ask": 'Overwrite the version in Leo?',
"message": s, "yes_all": not _is_leo, "no_all": not _is_leo}
self.integController.sendAsyncOutput(w_package)
self.waitingForAnswer = True
return False
# result = self.integController.g.app.gui.runAskYesNoDialog(c, 'Overwrite the version in Leo?', s,
# yes_all=not _is_leo, no_all=not _is_leo)
# if result and "-all" in result.lower():
# self.yesno_all_time = time.time()
# self.yesno_all_answer = result.lower()
# return bool(result and 'yes' in result.lower())
def checksum(self, path):
'''Return the checksum of the file at the given path.'''
import hashlib
return hashlib.md5(open(path, 'rb').read()).hexdigest()
def get_mtime(self, path):
'''Return the modification time for the path.'''
return self.integController.g.os_path_getmtime(self.integController.g.os_path_realpath(path))
def get_time(self, path):
'''
return timestamp for path
see set_time() for notes
'''
return self._time_d.get(self.integController.g.os_path_realpath(path))
def has_changed(self, path):
'''Return True if p's external file has changed outside of Leo.'''
if not path:
return False
if not self.integController.g.os_path_exists(path):
return False
if self.integController.g.os_path_isdir(path):
return False
#
# First, check the modification times.
old_time = self.get_time(path)
new_time = self.get_mtime(path)
if not old_time:
# Initialize.
self.set_time(path, new_time)
self.checksum_d[path] = self.checksum(path)
return False
if old_time == new_time:
return False
#
# Check the checksums *only* if the mod times don't match.
old_sum = self.checksum_d.get(path)
new_sum = self.checksum(path)
if new_sum == old_sum:
# The modtime changed, but it's contents didn't.
# Update the time, so we don't keep checking the checksums.
# Return False so we don't prompt the user for an update.
self.set_time(path, new_time)
return False
# The file has really changed.
assert old_time, path
# #208: external change overwrite protection only works once.
# If the Leo version is changed (dirtied) again,
# overwrite will occur without warning.
# self.set_time(path, new_time)
# self.checksum_d[path] = new_sum
return True
def is_enabled(self, c):
'''Return the cached @bool check_for_changed_external_file setting.'''
# check with leoInteg's config first
if self.integController.leoIntegConfig:
w_check_config = self.integController.leoIntegConfig["checkForChangeExternalFiles"].lower(
)
if bool('check' in w_check_config):
return True
if bool('ignore' in w_check_config):
return False
# let original function resolve
d = self.enabled_d
val = d.get(c)
if val is None:
val = c.config.getBool(
'check-for-changed-external-files', default=False)
d[c] = val
return val
def join(self, s1, s2):
'''Return s1 + ' ' + s2'''
return f"{s1} {s2}"
def set_time(self, path, new_time=None):
'''
Implements c.setTimeStamp.
Update the timestamp for path.
NOTE: file paths with symbolic links occur with and without those links
resolved depending on the code call path. This inconsistency is
probably not Leo's fault but an underlying Python issue.
Hence the need to call realpath() here.
'''
# print("called set_time for " + str(path), flush=True)
t = new_time or self.get_mtime(path)
self._time_d[self.integController.g.os_path_realpath(path)] = t
def warn(self, c, path, p):
'''
Warn that an @asis or @nosent node has been changed externally.
There is *no way* to update the tree automatically.
'''
# check with leoInteg's config first
if self.integController.leoIntegConfig:
w_check_config = self.integController.leoIntegConfig["defaultReloadIgnore"].lower(
)
if w_check_config != "none":
# if not 'none' then do not warn, just infoMessage 'warn' at most
if not self.infoMessage:
self.infoMessage = "warn"
return
# let original function resolve
if self.integController.g.unitTesting or c not in self.integController.g.app.commanders():
return
if not p:
self.integController.g.trace('NO P')
return
s = '\n'.join([
'%s has changed outside Leo.\n' % self.integController.g.splitLongFileName(
path),
'Leo can not update this file automatically.\n',
'This file was created from %s.\n' % p.h,
'Warning: refresh-from-disk will destroy all children.'
])
w_package = {"async": "warn",
"warn": 'External file changed', "message": s}
self.integController.sendAsyncOutput(w_package)
self.waitingForAnswer = True
# Some methods are called in the usual (non-leoBridge without 'efc') save process.
# Those may be called by the 'save' function, like check_overwrite,
# or by any other functions from the instance of leo.core.leoBridge that's running.
def open_with(self, c, d):
return
def check_overwrite(self, c, fn):
# print("check_overwrite!! ", flush=True)
return True
def shut_down(self):
return
def destroy_frame(self, f):
return
class IntegTextWrapper:
"""
A class that represents text as a Python string.
Modified from Leo's StringTextWrapper class source
"""
def __init__(self, c, name, g):
"""Ctor for the IntegTextWrapper class."""
self.c = c
self.name = name
self.g = g # Should g be totally global across all leoIntegration classes?
self.ins = 0
self.sel = 0, 0
self.s = ''
self.yScroll = 0
self.supportsHighLevelInterface = True
self.widget = None # This ivar must exist, and be None.
def __repr__(self):
return f"<IntegTextWrapper: {id(self)} {self.name}>"
def getName(self):
"""IntegTextWrapper."""
return self.name # Essential.
def clipboard_clear(self):
self.g.app.gui.replaceClipboardWith('')
def clipboard_append(self, s):
s1 = self.g.app.gui.getTextFromClipboard()
self.g.app.gui.replaceClipboardWith(s1 + s)
def flashCharacter(self, i, bg='white', fg='red',
flashes=3, delay=75): pass
def see(self, i): pass
def seeInsertPoint(self): pass
def setFocus(self): pass
def setStyleClass(self, name): pass
def tag_configure(self, colorName, **keys): pass
def appendText(self, s):
"""IntegTextWrapper appendText"""
self.s = self.s + self.g.toUnicode(s)
# defensive
self.ins = len(self.s)
self.sel = self.ins, self.ins
def delete(self, i, j=None):
"""IntegTextWrapper delete"""
i = self.toPythonIndex(i)
if j is None:
j = i + 1
j = self.toPythonIndex(j)
# This allows subclasses to use this base class method.
if i > j:
i, j = j, i
s = self.getAllText()
self.setAllText(s[:i] + s[j:])
# Bug fix: 2011/11/13: Significant in external tests.
self.setSelectionRange(i, i, insert=i)
def deleteTextSelection(self):
"""IntegTextWrapper."""
i, j = self.getSelectionRange()
self.delete(i, j)
def get(self, i, j=None):
"""IntegTextWrapper get"""
i = self.toPythonIndex(i)
if j is None:
j = i + 1
j = self.toPythonIndex(j)
s = self.s[i:j]
# print("WRAPPER GET with self.s[i:j]: " + s)
return self.g.toUnicode(s)
def getAllText(self):
"""IntegTextWrapper getAllText"""
s = self.s
# print("WRAPPER getAllText " + s)
return self.g.checkUnicode(s)
def getInsertPoint(self):
"""IntegTextWrapper getInsertPoint"""
i = self.ins
if i is None:
if self.virtualInsertPoint is None:
i = 0
else:
i = self.virtualInsertPoint
self.virtualInsertPoint = i
return i
def getSelectedText(self):
"""IntegTextWrapper getSelectedText"""
i, j = self.sel
s = self.s[i:j]
# print("WRAPPER getSelectedText with self.s[i:j]: " + s)
return self.g.checkUnicode(s)
def getSelectionRange(self, sort=True):
"""Return the selected range of the widget."""
sel = self.sel
if len(sel) == 2 and sel[0] >= 0 and sel[1] >= 0:
i, j = sel
if sort and i > j:
sel = j, i # Bug fix: 10/5/07
return sel
i = self.ins
return i, i
def getXScrollPosition(self):
return 0
# X axis ignored
def getYScrollPosition(self):
# print("wrapper get y scroll" + str(self.yScroll))
return self.yScroll
def hasSelection(self):
"""IntegTextWrapper hasSelection"""
i, j = self.getSelectionRange()
return i != j
def insert(self, i, s):
"""IntegTextWrapper insert"""
i = self.toPythonIndex(i)
s1 = s
self.s = self.s[:i] + s1 + self.s[i:]
i += len(s1)
self.ins = i
self.sel = i, i
def selectAllText(self, insert=None):
"""IntegTextWrapper selectAllText"""
self.setSelectionRange(0, 'end', insert=insert)
def setAllText(self, s):
"""IntegTextWrapper setAllText"""
# print("WRAPPER setAllText: " + s)
self.s = s
i = len(self.s)
self.ins = i
self.sel = i, i
def setInsertPoint(self, pos, s=None):
"""IntegTextWrapper setInsertPoint"""
self.virtualInsertPoint = i = self.toPythonIndex(pos)
self.ins = i
self.sel = i, i
def setXScrollPosition(self, i):
pass
# X axis ignored
def setYScrollPosition(self, i):
self.yScroll = i
# print("wrapper set y scroll" + str(self.yScroll))
def setSelectionRange(self, i, j, insert=None):
"""IntegTextWrapper setSelectionRange"""
i, j = self.toPythonIndex(i), self.toPythonIndex(j)
self.sel = i, j
self.ins = j if insert is None else self.toPythonIndex(insert)
def toPythonIndex(self, index):
"""IntegTextWrapper toPythonIndex"""
return self.g.toPythonIndex(self.s, index)
def toPythonIndexRowCol(self, index):
"""IntegTextWrapper toPythonIndexRowCol"""
s = self.getAllText()
i = self.toPythonIndex(index)
row, col = self.g.convertPythonIndexToRowCol(s, i)
return i, row, col
class LeoBridgeIntegController:
'''Leo Bridge Controller'''
# pylint: disable=no-else-return
def __init__(self):
# TODO : @boltex #74 need gnx_to_vnode for each opened file/commander
self.gnx_to_vnode = [] # utility array - see leoflexx.py in leoPluginsRef.leo
self.bridge = leoBridge.controller(
gui='nullGui',
loadPlugins=True, # True: attempt to load plugins.
readSettings=True, # True: read standard settings files.
silent=True, # True: don't print signon messages.
# True: prints what would be sent to the log pane.
verbose=False,
)
self.g = self.bridge.globals()
# * Trace outputs to pythons stdout, also prints the function call stack
# self.g.trace('test trace')
# * Intercept Log Pane output: Sends to client's log pane
self.g.es = self.es # pointer - not a function call
# print(dir(self.g), flush=True)
self.currentActionId = 1 # Id of action being processed, STARTS AT 1 = Initial 'ready'
# * Currently Selected Commander (opened from leo.core.leoBridge or chosen via the g.app.windowList 2 list)
self.commander = None
self.leoIntegConfig = None
self.webSocket = None
self.loop = None
# * Replacement instances to Leo's codebase : getScript, IdleTime, idleTimeManager and externalFilesController
self.g.getScript = self._getScript
self.g.IdleTime = self._idleTime
self.g.app.idleTimeManager = IdleTimeManager(self.g)
# attach instance to g.app for calls to set_time, etc.
self.g.app.externalFilesController = ExternalFilesController(self)
# TODO : Maybe use those yes/no replacement right before actual usage instead of in init. (to allow re-use/switching)
# override for "revert to file" operation
self.g.app.gui.runAskYesNoDialog = self._returnYes
self.g.app.gui.show_find_success = self._show_find_success
self.headlineWidget = self.g.bunch(_name='tree')
self.g.app.loadManager.createAllImporterData()
# * setup leoBackground to get messages from leo
try:
self.g.app.idleTimeManager.start() # To catch derived file changes
except Exception:
print('ERROR with idleTimeManager')
async def _asyncIdleLoop(self, p_seconds, p_fn):
while True:
await asyncio.sleep(p_seconds)
p_fn(self)
def _returnNo(self, *arguments, **kwargs):
'''Used to override g.app.gui.ask[XXX] dialogs answers'''
return "no"
def _returnYes(self, *arguments, **kwargs):
'''Used to override g.app.gui.ask[XXX] dialogs answers'''
return "yes"
def _getScript(self, c, p,
useSelectedText=True,
forcePythonSentinels=True,
useSentinels=True,
):
"""
Return the expansion of the selected text of node p.
Return the expansion of all of node p's body text if
p is not the current node or if there is no text selection.
"""
w = c.frame.body.wrapper
if not p:
p = c.p
try:
if w and p == c.p and useSelectedText and w.hasSelection():
s = w.getSelectedText()
else:
s = p.b
# Remove extra leading whitespace so the user may execute indented code.
s = self.g.removeExtraLws(s, c.tab_width)
s = self.g.extractExecutableString(c, p, s)
script = self.g.composeScript(c, p, s,
forcePythonSentinels=forcePythonSentinels,
useSentinels=useSentinels)
except Exception:
self.g.es_print("unexpected exception in g.getScript")
self.g.es_exception()
script = ''
return script
def _idleTime(self, fn, delay, tag):
# TODO : REVISE/REPLACE WITH OWN SYSTEM
asyncio.get_event_loop().create_task(self._asyncIdleLoop(delay/1000, fn))
def _getTotalOpened(self):
'''Get total of opened commander (who have closed == false)'''
w_total = 0
for w_commander in self.g.app.commanders():
if not w_commander.closed:
w_total = w_total + 1
return w_total
def _getFirstOpenedCommander(self):
'''Get first opened commander, or False if there are none.'''
for w_commander in self.g.app.commanders():
if not w_commander.closed:
return w_commander
return False
def _show_find_success(self, c, in_headline, insert, p):
'''Handle a successful find match.'''
if in_headline:
self.g.app.gui.set_focus(c, self.headlineWidget)
# no return
def sendAsyncOutput(self, p_package):
if "async" not in p_package:
print('[sendAsyncOutput] Error async member missing in package parameter')
print(json.dumps(p_package, separators=(',', ':')), flush=True)
return
if self.loop:
self.loop.create_task(self.asyncOutput(
json.dumps(p_package, separators=(',', ':'))))
else:
print('[sendAsyncOutput] Error loop not ready' +
json.dumps(p_package, separators=(',', ':')))
def set_ask_result(self, p_result):
'''Got the result to an asked question/warning from client'''
self.g.app.externalFilesController.integResult(p_result)
return self.sendLeoBridgePackage() # Just send empty as 'ok'
def set_config(self, p_config):
'''Got leoInteg's config from client'''
self.leoIntegConfig = p_config
return self.sendLeoBridgePackage() # Just send empty as 'ok'
def logSignon(self):
'''Simulate the Initial Leo Log Entry'''
if self.loop:
self.g.app.computeSignon()
self.g.es(str(self.g.app.signon))
self.g.es(str(self.g.app.signon1))
else:
print('no loop in logSignon', flush=True)
def setActionId(self, p_id):
self.currentActionId = p_id
async def asyncOutput(self, p_json):
'''Output json string to the websocket'''
if self.webSocket:
await self.webSocket.send(p_json)
else:
print("websocket not ready yet", flush=True)
def sendLeoBridgePackage(self, p_package={}):
p_package["id"] = self.currentActionId
return(json.dumps(p_package, separators=(',', ':'))) # send as json
def _outputError(self, p_message="Unknown Error"):
# Output to this server's running console
print("ERROR: " + p_message, flush=True)
w_package = {"id": self.currentActionId}
w_package["error"] = p_message
return p_message
def _outputBodyData(self, p_bodyText=""):
return self.sendLeoBridgePackage({"body": p_bodyText})
def _outputSelectionData(self, p_bodySelection):
return self.sendLeoBridgePackage({"bodySelection": p_bodySelection})
def _outputPNode(self, p_node=False):
if p_node:
# Single node, singular
return self.sendLeoBridgePackage({"node": self._p_to_ap(p_node)})
else:
return self.sendLeoBridgePackage({"node": None})
def _outputPNodes(self, p_pList):
w_apList = []
for p in p_pList:
w_apList.append(self._p_to_ap(p))
# Multiple nodes, plural
return self.sendLeoBridgePackage({"children": w_apList})
def es(self, * args, **keys):
'''Output to the Log Pane'''
d = {
'color': None,
'commas': False,
'newline': True,
'spaces': True,
'tabName': 'Log',
'nodeLink': None,
}
d = self.g.doKeywordArgs(keys, d)
s = self.g.translateArgs(args, d)
w_package = {"async": "log", "log": s}
self.sendAsyncOutput(w_package)
def initConnection(self, p_webSocket):
self.webSocket = p_webSocket
self.loop = asyncio.get_event_loop()
def _get_commander_method(self, p_command):
""" Return the given method (p_command) in the Commands class or subcommanders."""
# self.g.trace(p_command)
#
# First, try the commands class.
w_func = getattr(self.commander, p_command, None)
if w_func:
return w_func
#
# Search all subcommanders for the method.
table = ( # This table comes from c.initObjectIvars.
'abbrevCommands',
'bufferCommands',
'chapterCommands',
'controlCommands',
'convertCommands',
'debugCommands',
'editCommands',
'editFileCommands',
'evalController',
'gotoCommands',
'helpCommands',
'keyHandler',
'keyHandlerCommands',
'killBufferCommands',
'leoCommands',
'leoTestManager',
'macroCommands',
'miniBufferWidget',
'printingController',
'queryReplaceCommands',
'rectangleCommands',
'searchCommands',
'spellCommands',
'vimCommands', # Not likely to be useful.
)
for ivar in table:
subcommander = getattr(self.commander, ivar, None)
if subcommander:
w_func = getattr(subcommander, p_command, None)
if w_func:
### self.g.trace(f"Found c.{ivar}.{p_command}")
return w_func
# else:
# self.g.trace(f"Not Found: c.{ivar}") # Should never happen.
return None
def leoCommand(self, p_command, param):
'''
Generic call to a method in Leo's Commands class or any subcommander class.
The param["ap"] position is to be selected before having the command run,
while the param["keep"] parameter specifies wether the original position
should be re-selected afterward.
The whole of those operations is to be undoable as one undo step.
command: a method name (a string).
param["ap"]: an archived position.
param["keep"]: preserve the current selection, if possible.
'''
w_keepSelection = False # Set default, optional component of param
if "keep" in param:
w_keepSelection = param["keep"]
w_ap = param["ap"] # At least node parameter is present
if not w_ap:
return self._outputError(f"Error in {p_command}: no param ap")
w_p = self._ap_to_p(w_ap)
if not w_p:
return self._outputError(f"Error in {p_command}: no w_p position found")
w_func = self._get_commander_method(p_command)
if not w_func:
return self._outputError(f"Error in {p_command}: no method found")
if w_p == self.commander.p:
w_func(event=None)
else:
w_oldPosition = self.commander.p
self.commander.selectPosition(w_p)
w_func(event=None)
if w_keepSelection and self.commander.positionExists(w_oldPosition):
self.commander.selectPosition(w_oldPosition)
return self._outputPNode(self.commander.p)
def get_all_open_commanders(self, param):
'''Return array of opened file path/names to be used as openFile parameters to switch files'''
w_files = []
for w_commander in self.g.app.commanders():
if not w_commander.closed:
w_isSelected = False
w_isChanged = w_commander.changed
if self.commander == w_commander:
w_isSelected = True
w_entry = {
"name": w_commander.mFileName,
"changed": w_isChanged,
"selected": w_isSelected
}
w_files.append(w_entry)
return self.sendLeoBridgePackage({"files": w_files})
def get_ui_states(self, param):
"""
Gets the currently opened file's general states for UI enabled/disabled states
such as undo available, file changed/unchanged
"""
w_states = {}
if self.commander:
try:
# 'dirty/changed' member
w_states["changed"] = self.commander.changed
w_states["canUndo"] = self.commander.canUndo()
w_states["canRedo"] = self.commander.canRedo()
w_states["canDemote"] = self.commander.canDemote()
w_states["canPromote"] = self.commander.canPromote()
w_states["canDehoist"] = self.commander.canDehoist()
except Exception as e:
self.g.trace('Error while getting states')
print("Error while getting states", flush=True)
print(str(e), flush=True)
else:
w_states["changed"] = False
w_states["canUndo"] = False
w_states["canRedo"] = False
w_states["canDemote"] = False
w_states["canPromote"] = False
w_states["canDehoist"] = False
return self.sendLeoBridgePackage({"states": w_states})
def set_opened_file(self, param):
'''Choose the new active commander from array of opened file path/names by numeric index'''
w_openedCommanders = []
for w_commander in self.g.app.commanders():
if not w_commander.closed:
w_openedCommanders.append(w_commander)
w_index = param['index'] # index in param
if w_openedCommanders[w_index]:
self.commander = w_openedCommanders[w_index]
if self.commander:
self.commander.closed = False
self._create_gnx_to_vnode()
w_result = {"total": self._getTotalOpened(), "filename": self.commander.fileName(),
"node": self._p_to_ap(self.commander.p)}
# maybe needed for frame wrapper
self.commander.selectPosition(self.commander.p)
return self.sendLeoBridgePackage(w_result)
else:
return self._outputError('Error in setOpenedFile')
def open_file(self, param):
"""
Open a leo file via leoBridge controller, or create a new document if empty string.
Returns an object that contains a 'opened' member.
"""
w_found = False
w_filename = param.get('filename') # Optional.
# If not empty string (asking for New file) then check if already opened
if w_filename:
for w_commander in self.g.app.commanders():
if w_commander.fileName() == w_filename:
w_found = True
self.commander = w_commander