-
Notifications
You must be signed in to change notification settings - Fork 1
/
leoDataModel.py
3311 lines (3017 loc) · 114 KB
/
leoDataModel.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
#@+leo-ver=5-thin
#@+node:vitalije.20180510153405.1: * @file leoDataModel.py
import random as _mrandom
from collections import defaultdict, namedtuple
import re
import os
import xml.etree.ElementTree as ET
import pickle
import time
import base64
import difflib
random = _mrandom.Random()
random.seed(12)
class myrandom:
def __init__(self):
self.x = 1
def random(self):
self.x += 1
return 1 - 1/self.x
random = myrandom()
#@+others
#@+node:vitalije.20180510153747.1: ** parPosIter
def parPosIter(ps, levs):
'''Helper iterator for parent positions. Given sequence of
positions and corresponding levels it generates sequence
of parent positions'''
rootpos = ps[0]
levPars = [rootpos for i in range(256)] # max depth 255 levels
it = zip(ps, levs)
next(it) # skip first root node which has no parent
yield rootpos
for p, l in it:
levPars[l] = p
yield levPars[l - 1]
#@+node:vitalije.20180510153733.2: ** nodes2treemodel
def nodes2treemodel(inodes, oldpositions=None):
'''Creates LeoTreeModel from the sequence of tuples
(gnx, h, b, level, size, parentGnxes, childrenGnxes)'''
ltm = LeoTreeModel()
(positions, nodes, attrs, levels, expanded, marked) = ltm.data
if oldpositions is None:
positions.extend(random.random() for x in inodes)
else:
positions.extend(oldpositions)
levels.extend(x[3] for x in inodes)
nodes.extend(x[0] for x in inodes)
for pos, x in zip(positions, inodes):
gnx, h, b, lev, sz, ps, chn = x
if gnx not in attrs:
attrs[gnx] = NData(h, b, ps, chn, sz[0])
# root node must not have parents
rgnx = nodes[0]
del attrs[rgnx].parents[:]
return ltm
#@+node:vitalije.20180510153733.1: ** vnode2treemodel
def vnode2treemodel(vnode):
'''Utility convertor: converts VNode instance into
LeoTreeModel instance'''
def viter(v, lev0):
s = [1]
mnode = (v.gnx, v.h, v.b, lev0, s,
[x.gnx for x in v.parents],
[x.gnx for x in v.children])
yield mnode
for ch in v.children:
for x in viter(ch, lev0 + 1):
s[0] += 1
yield x
return nodes2treemodel(tuple(viter(vnode, 0)))
#@+node:vitalije.20180510153733.3: ** xml2treemodel
def xml2treemodel(xvroot, troot):
'''Returns LeoTreeModel instance from vnodes and tnodes elements of xml Leo file'''
parDict = defaultdict(list)
hDict = {}
bDict = dict((ch.attrib['tx'], ch.text or '') for ch in troot.getchildren())
xDict = {}
#@+others
#@+node:vitalije.20180510153945.1: *3* xml viter
def viter(xv, lev0, dumpingClone=False):
s = [1]
gnx = xv.attrib['t']
if len(xv) == 0:
# clone
for ch in viter(xDict[gnx], lev0, True):
yield ch
return
chs = [ch.attrib['t'] for ch in xv if ch.tag == 'v']
if not dumpingClone:
xDict[gnx] = xv
hDict[gnx] = xv[0].text
for ch in chs:
parDict[ch].append(gnx)
mnode = [gnx, hDict[gnx], bDict.get(gnx, ''), lev0, s, parDict[gnx], chs]
yield mnode
for ch in xv.getchildren():
if ch.tag != 'v':continue
for x in viter(ch, lev0 + 1, dumpingClone):
s[0] += 1
yield x
#@+node:vitalije.20180510154050.1: *3* riter
def riter():
s = [1]
chs = []
yield 'hidden-root-vnode-gnx', '<hidden root vnode>','', 0, s, [], chs
for xv in xvroot.getchildren():
gnx = xv.attrib['t']
chs.append(gnx)
parDict[gnx].append('hidden-root-vnode-gnx')
for ch in viter(xv, 1):
s[0] += 1
yield ch
#@-others
nodes = tuple(riter())
return nodes2treemodel(nodes)
#@+node:vitalije.20180510153733.4: ** load_leo
def load_leo(fname):
'''Loads given xml Leo file and returns LeoTreeModel instance'''
with open(fname, 'rt') as inp:
s = inp.read()
xroot = ET.fromstring(s)
vnodesEl = xroot.find('vnodes')
tnodesEl = xroot.find('tnodes')
return xml2treemodel(vnodesEl, tnodesEl)
#@+node:vitalije.20180518104947.1: ** load_external_files
def load_external_files(ltm, loaddir):
mpaths = paths(ltm, loaddir)
(positions, nodes, attrs, levels, expanded, marked) = ltm.data
for gnx, ps in mpaths.items():
h = attrs[gnx].h
if h.startswith('@file '):
ltm2 = ltm_from_derived_file(ps[0])
gnx2 = ltm2.data.nodes[0]
if gnx2 != gnx:
ltm.change_gnx(gnx, gnx2)
ltm.replace_node(ltm2)
elif h.startswith('@auto ') and h.endswith('.py'):
ltm2 = auto_py(gnx, ps[0])
ltm2.data.attrs[gnx].h = h
ltm.replace_node(ltm2)
ltm.invalidate_visual()
#@+node:vitalije.20180518155338.1: ** load_leo_full
def load_leo_full(fname):
'''Loads both given xml Leo file and external files.
Returns LeoTreeModel instance'''
ltm = load_leo(fname)
loaddir = os.path.dirname(fname)
loaddir = os.path.normpath(loaddir)
loaddir = os.path.abspath(loaddir)
load_external_files(ltm, loaddir)
return ltm
#@+node:vitalije.20180518100350.1: ** paths
atFileNames = [
"@auto-rst", "@auto","@asis",
"@edit",
"@file-asis", "@file-thin", "@file-nosent", "@file",
"@clean", "@nosent",
"@shadow",
"@thin"
]
atFilePat = re.compile(r'^(%s)\s+(.+)$'%('|'.join(atFileNames)))
def paths(ltm, loaddir):
'''Returns dict keys are gnx of each file node,
and values are lists of absolute paths corresponding
to the node.'''
(positions, nodes, attrs, levels, expanded, marked) = ltm.data
stack = [loaddir for x in range(255)]
res = defaultdict(list)
pat = re.compile(r'^@path\s+(.+)$', re.M)
cdir = loaddir
npath = lambda x: os.path.normpath(os.path.abspath(x))
jpath = lambda x:npath(os.path.join(cdir, x))
for p, gnx, lev in zip(positions, nodes, levels):
if lev == 0: continue
cdir = stack[lev - 1]
h, b = attrs[gnx][:2]
m = pat.search(h) or pat.search(b)
if m:
cdir = jpath(m.group(1))
stack[lev] = cdir
m = atFilePat.match(h)
if m:
res[gnx].append(jpath(m.group(2)))
return res
#@+node:vitalije.20180731211311.1: ** chapter_name
_chapter_name_cleaner = re.compile(r'[^-0-9A-Za-z]+', re.ASCII)
def chapter_name(s):
if not s.startswith('@chapter '):return ''
name, sep, binding = s[9:].strip().partition('@')
name = '-'.join(name.strip().split())
return _chapter_name_cleaner.sub('', name)[:128]
#@+node:vitalije.20180624125820.1: ** gnx_iter
def gnx_iter(nodes, gnx, sz=1):
i = 0
try:
while i < len(nodes):
i = nodes.index(gnx, i)
yield i
i += sz
except ValueError:
pass
#@+node:vitalije.20180624130228.1: ** up_level_index
def up_level_index(levels, i):
lev = levels[i]
return levels.rfind(lev-1, 0, i) if lev > 1 else 0
parent_index = up_level_index
#@+node:vitalije.20180629170433.1: ** to_leo_pos
def to_leo_pos(ltmdata, pos, c):
(positions, nodes, attrs, levels, expanded, marked) = ltmdata
def pstack_rev(i):
while i > 0:
v = c.fileCommands.gnxDict[nodes[i]]
pi = up_level_index(levels, i)
ci = levels[pi+1:i].count(levels[i])
yield v, ci
i = pi
ipos = positions.index(pos)
pth = list(pstack_rev(ipos))
pth.reverse()
v, i = pth.pop()
p = c.rootPosition()
p.stack[:] = pth
p.v = v
p._childIndex = i
return p
#@+node:vitalije.20180715224523.1: ** to_ltm_pos
def to_ltm_pos(ltmdata, p):
(positions, nodes, attrs, levels, expanded, marked) = ltmdata
i = 0
for (v, ci) in p.stack:
i += 1
while ci:
i += attrs[nodes[i]].size
ci -= 1
i += 1
ci = p._childIndex
while ci:
i += attrs[nodes[i]].size
ci -= 1
return positions[i]
#@+node:vitalije.20180613161708.1: ** LTMData
LTMData = namedtuple('LTMData', 'positions nodes attrs levels expanded marked')
def copy_ltmdata(data):
attrs = dict((gnx, nd.deepCopy()) for gnx, nd in data.attrs.items())
return LTMData(
data.positions[:],
data.nodes[:],
attrs,
data.levels[:],
set(data.expanded),
set(data.marked)
)
#@+node:vitalije.20180726162502.1: ** transform_ltmdata
def transform_ltmdata(t1, t2):
'''Transformes t1 to have same outline as t2, but keeping
positions from t1 where possible.
'''
aseq = tuple(zip(t1.nodes, t1.levels))
bseq = tuple(zip(t2.nodes, t2.levels))
sm = difflib.SequenceMatcher(None, aseq, bseq, autojunk=False)
for op, i1, i2, j1, j2 in sm.get_opcodes():
if op in ('insert','replace'):
t1.positions[i1:i2] = t2.positions[j1:j2]
t1.nodes[i1:i2] = t2.nodes[j1:j2]
t1.levels[i1:i2] = t2.levels[j1:j2]
elif op == 'delete':
del t1.positions[i1:i2]
del t1.nodes[i1:i2]
del t1.levels[i1:i2]
elif op == 'equal':
continue
sync_attrs(t1.attrs, t2.attrs)
def sync_attrs(a1, a2):
# a1.clear()
# a1.update(a2)
# this might invalidate pdata instances from t1
# it is safer to do it
for k, v in a2.items():
if k in a1:
a1[k].copy_from(v)
else:
a1[k] = v
remgnx = set(a1.keys()) - set(a2.keys())
for x in remgnx:
a1.pop(x)
#@+node:vitalije.20180625191254.1: ** NData
class NData:
fieldnames = 'h', 'b', 'parents', 'children', 'size'
def __init__(self, h, b, parents, children, size):
self.h = h
self.b = b
self.parents = parents
self.children = children
self.size = size
def __getitem__(self, i):
names = NData.fieldnames[i]
if isinstance(names, tuple):
return tuple(getattr(self, x) for x in names)
else:
return getattr(self, names)
def __setitem__(self, i, v):
setattr(self, NData.fieldnames[i], v)
def copy(self):
return NData(self.h, self.b, self.parents, self.children, self.size)
def copy_from(self, other):
self.h = other.h
self.b = other.b
self.parents[:] = other.parents
self.children[:] = other.children
self.size = other.size
def deepCopy(self):
return NData(self.h, self.b, self.parents[:], self.children[:], self.size)
def __iter__(self):
yield self.h
yield self.b
yield self.parents
yield self.children
yield self.size
#@+node:vitalije.20180727125449.1: ** PData
PData = namedtuple('PData', 'i pos gnx lev nd')
#@+node:vitalije.20180510153738.1: ** LeoTreeModel
class LeoTreeModel(object):
'''Model representing all of Leo outline data.
warning: work in progress - still doesn't contain all Leo data
TODO: add support for unknownAttributes
add support for status bits
add support for gui view values
- body cursor position
- selected text'''
def __init__(self):
self.data = LTMData([], [], {}, bytearray(b''), set(), set())
self.selectedPosition = None
self._visible_positions_serial = 0
self._visible_positions_last = -1
self._visible_positions = tuple()
self._selectedIndex = -1
self._undostack = []
self._undopos = -1
self._vis_top = 0
#@+others
#@+node:vitalije.20180727123721.1: *3* normalize
def normalize(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if positions[i] != pos:
try:
i = positions.index(pos)
except ValueError:
return PData(0, positions[0], nodes[0], 0, attrs[nodes[0]])
gnx = nodes[i]
return PData(i, pos, gnx, levels[i], attrs[gnx])
nd1 = attrs[gnx]
if nd1 is not nd:
return PData(i, pos, gnx, levels[i], nd1)
return pdata
def mkpos(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
if i >= len(nodes): i = 0
gnx = nodes[i]
return PData(i, positions[i], gnx, levels[i], attrs[gnx])
#@+node:vitalije.20180510153738.2: *3* parents
def parents(self, gnx):
'''Returns list of gnxes of parents of node with given gnx'''
a = self.data.attrs.get(gnx)
return a.parents if a else []
#@+node:vitalije.20180510153738.3: *3* children
def children(self, gnx):
'''Returns list of gnxes of children of the node with given gnx'''
a = self.data.attrs.get(gnx)
return a.children if a else []
#@+node:vitalije.20180718200706.1: *3* ...iterators...
def is_visible(self, pos):
return self.is_visilbe_i(self.positions.index(pos))
def is_visible_i(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
lev = levels[i]
if lev == 1:
return True
while lev > 1:
lev -= 1
i = levels.rfind(lev, 0, i)
if positions[i] not in expanded:
return False
return True
#@+node:vitalije.20180622143953.1: *4* _child_iterator
def _child_iterator(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
pgnx = nodes[i]
nd = attrs[pgnx]
i += 1
for j, gnx in enumerate(nd.children):
yield j, i, gnx
i += attrs[gnx].size
#@+node:vitalije.20180727135224.1: *5* pos_unique_subtree
def pos_unique_subtree(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
B = i + nd.size
i += 1
seen = set()
while i < B:
gnx = nodes[i]
if gnx in seen:
i += attrs[gnx].size
else:
seen.add(gnx)
nd = attrs[gnx]
yield PData(i, positions[i], gnx, levels[i], nd)
i += 1
#@+node:vitalije.20180727135230.1: *5* pos_child_iterator
def pos_child_iterator(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
B = i + nd.size
i += 1
while i < B:
gnx = nodes[i]
nd = attrs[gnx]
yield PData(i, positions[i], gnx, levels[i], nd)
i += nd.size
#@+node:vitalije.20180727143912.1: *4* UNL
def UNL_simple(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
res = []
while i > 0:
res.append(attrs[nodes[i]].h)
i = parent_index(levels, i)
res.reverse()
return '-->'.join(x.replace('-->', '--%3E') for x in res)
def UNL_with_indexes(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
res = []
while i > 0:
pi = parent_index(levels, i)
if i == pi + 1:
h = attrs[nodes[i]].h.replace('-->', '--%3E') + ':0'
else:
h = self._UNL_ind(nodes, attrs, levels, i, pi)
res.append(h)
i = pi
res.reverse()
return '-->'.join(res)
def _UNL_ind(self, nodes, attrs, levels, i, pi):
h = attrs[nodes[i]].h
lev = levels[i]
count = 0
while i > pi + 1:
i = levels.rfind(lev, pi, i)
if h == attrs[nodes[i]].h: count += 1
return h.replace('-->', '--%3E') + ':%d'%count
#@+node:vitalije.20180731211148.1: *4* chapter_names
def chapter_names(self):
(positions, nodes, attrs, levels, expanded, marked) = self.data
seen = set()
yield 0, positions[0], 'main'
i = 1
N = len(positions)
while i < N:
gnx = nodes[i]
nd = attrs[gnx]
if gnx in seen:
i += nd.size
else:
s = chapter_name(nd.h)
if s:
yield i, positions[i], s
i += 1
def chapter_name_for_pos(self, pos):
(positions, nodes, attrs, levels, expanded, marked) = self.data
j = positions.index(pos)
while j > 0:
s = chapter_name(attrs[nodes[j]].h)
if s:
return s
j = parent_index(levels, j)
return 'main'
def position_is_in_chapter(self, rdata, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = self.normalize(rdata)
return pdata.pos in positions[i+1:i+nd.size]
#@+node:vitalije.20180718153808.1: *4* subtree_iter_from
def subtree_iter_from(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
sz = attrs[nodes[i]].size
for j in range(i, i+sz):
yield positions[j], j
#@+node:vitalije.20180718200730.1: *4* following_siblings_from
def following_siblings_from(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
N = len(positions)
lev = levels[i]
i += attrs[nodes[i]].size
while i < N and levels[i] == lev:
yield positions[i], i
i += attrs[nodes[i]].size
def following_siblings_pos(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if i:
if pos != positions[i]:
i = positions.index(pos)
N = len(positions)
i += nd.size
while i < N and levels[i] == lev:
yield self.mkpos(i)
i += attrs[nodes[i]].size
#@+node:vitalije.20180723151757.1: *4* next_sibling_i
def next_sibling_i(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
lev = levels[i]
j = attrs[nodes[i]].size + i
if j < len(levels) and levels[j] == lev: return j
return 0
#@+node:vitalije.20180723203232.1: *4* prev_sibling_i
def prev_sibling_i(self, i):
if i < 2: return 0
(positions, nodes, attrs, levels, expanded, marked) = self.data
lev = levels[i]
if lev - 1 == levels[i-1]: return 0
j = levels.rfind(lev, 0, i)
return max(0, j)
#@+node:vitalije.20180727140734.1: *4* last_child
def last_child(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
gnx = nodes[i]
sz = attrs[gnx].size
if sz < 2:return 0
lev = levels[i] + 1
j = levels.rfind(lev, i, i + sz)
return max(0, j)
def last_child_pos(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if i == 0: return pdata
if pos != positions[i]:
i = positions.index(pos)
lgnx = nd.children[-1]
return self.mkpos(i + nd.size - attrs[lgnx].size)
#@+node:vitalije.20180727141314.1: *4* last_node
def last_node(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
gnx = nodes[i]
sz = attrs[gnx].size
if sz < 2:return 0
return i + sz - 1
def last_node_pos(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if i == 0: return pdata
if pos != positions[i]:
i = positions.index(pos)
return self.mkpos(i + nd.size - 1)
#@+node:vitalije.20180728130307.1: *4* exists
def exists(self, pdata, root=None):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if i == 0: return False
if positions[i] != pos:
i = positions.index(pos)
if root:
ir, rpos, rgnx, rlev, rnd = root
if positions[ir] != rpos:
ir = positions.index(rpos)
return ir <= i < ir + rnd.size
return True
#@+node:vitalije.20180723152016.1: *4* pos_after_delete_i
def pos_after_delete_i(self, i):
j = self.vis_back_i(i)
j = j or self.next_sibling_i(i)
return self.data.positions[j] if j else None
#@+node:vitalije.20180718221153.1: *4* vis_back_i
def vis_back_i(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
# assumes i is visible
a = self._vis_top
if levels[i-1] == levels[i]+1:
return i-1 if a < i-1 else 0
j = levels.rfind(levels[i], 0, i-1)
while j < i:
if positions[j] in expanded:
dj = 1
else:
dj = attrs[nodes[j]].size
if j + dj >= i:
return j if a < j else 0
j += dj
return 0
#@+node:vitalije.20180718221548.1: *4* vis_next_i
def vis_next_i(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
# assumes i is visible
if positions[i] in expanded:
i += 1
else:
i += attrs[nodes[i]].size
a = self._vis_top
b = a + attrs[nodes[a]].size
return i if a < i < b else 0
#@+node:vitalije.20180718200733.1: *4* parent_index
def parent_index(self, i):
return parent_index(self.data.levels, i)
#@+node:vitalije.20180718200737.1: *4* child_index
def child_index(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev, nd = pdata
if positions[i] != pos:
i = positions.index(pos)
pi = parent_index(levels, i) + 1
lev = levels[i]
return levels[pi:i].count(lev)
#@+node:vitalije.20180718200740.1: *4* all_siblings_from
def all_siblings_from(self, i):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i = parent_index(levels, i) + 1
N = len(positions)
lev = levels[i]
while i < N and levels[i] == lev:
yield positions[i], i
i += attrs[nodes[i]].size
#@+node:vitalije.20180613193835.1: *3* size
@property
def size(self):
return len(self.data.positions)
#@+node:vitalije.20180613194129.1: *3* body
def body(self, gnx):
return self.data.attrs[gnx].b
def set_b(self, gnx, b):
self.data.attrs[gnx].b = b
#@+node:vitalije.20180613194137.1: *3* head
def head(self, gnx):
return self.data.attrs[gnx].h
def set_h(self, gnx, h):
self.data.attrs[gnx].h = h.replace('\n', '')
#@+node:vitalije.20180723174759.1: *3* size_gnx
def size_gnx(self, gnx):
a = self.data.attrs.get(gnx)
return a.size if a else 0
#@+node:vitalije.20180620135448.1: *3* isClone
def isClone(self, gnx):
return len(self.data.attrs[gnx].parents) > 1
#@+node:vitalije.20180516103839.1: *3* selectedIndex
@property
def selectedIndex(self):
p = self.selectedPosition
si = max(0, self._selectedIndex)
if si < len(self.data.positions) and p == self.data.positions[si]:
return si
try:
i = self.data.positions.index(p)
self._selectedIndex = i
except ValueError:
i = -1
return i
#@+node:vitalije.20180715224624.1: *3* from_leo_pos
def from_leo_pos(self, p):
return to_ltm_pos(self.data, p)
def select_leo_pos(self, p):
self.selectedPosition = to_ltm_pos(self.data, p)
self._selectedIndex = self.data.positions.index(self.selectedPosition)
#@+node:vitalije.20180613192634.1: *3* selectedGnx
@property
def selectedGnx(self):
i = self.selectedIndex
return self.data.nodes[i]
#@+node:vitalije.20180717195931.1: *3* selection
@property
def selection(self):
'''returns currently selected (index, gnx, h, b, size)'''
i = self.selectedIndex
gnx = self.data.nodes[i]
nd = self.data.attrs[gnx]
return i, gnx, nd.h, nd.b, nd.size
#@+node:vitalije.20180613192640.1: *3* selectedBody
@property
def selectedBody(self):
i = self.selectedIndex
if i < 0:
b = ''
else:
gnx = self.data.nodes[i]
b = self.data.attrs[gnx].b
return b
#@+node:vitalije.20180613192643.1: *3* selectedHead
@property
def selectedHead(self):
i = self.selectedIndex
if i < 0:
h = ''
else:
gnx = self.data.nodes[i]
h = self.data.attrs[gnx].h
return h
#@+node:vitalije.20180516160109.1: *3* insert_leaf
def insert_leaf(self, pos, gnx, h, b):
i = self.data.positions.index(pos)
return self.insert_leaf_i(i, gnx, h, b)
def insert_leaf_i_after(self, i, gnx, h, b):
(positions, nodes, attrs, levels, expanded, marked) = self.data
pi = parent_index(levels, i)
i += attrs[nodes[i]].size
return self.insert_leaf_i_pi(i, gnx, h, b, pi)
def insert_leaf_i(self, i, gnx, h, b):
pi = parent_index(self.data.levels, i)
return self.insert_leaf_i_pi(i, gnx, h, b, pi)
def insert_leaf_i_pi(self, i, gnx, h, b, pi):
(positions, nodes, attrs, levels, expanded, marked) = self.data
pp = positions[pi]
di0 = i - pi
pgnx = nodes[pi]
psz = attrs[pgnx].size
lev = levels[pi] + 1
for pxi in gnx_iter(nodes, pgnx, psz + 1):
j = pxi + di0
levels.insert(j, levels[pxi] + 1)
positions.insert(j, random.random())
if positions[pxi] == pp:
retp = positions[j]
nodes.insert(j, gnx)
if gnx in attrs:
attrs[gnx].parents.append(pgnx)
else:
attrs[gnx] = NData(h, b, [pgnx], [], 1)
update_size(attrs, pgnx, 1)
self._update_children(pgnx)
return retp
#@+node:vitalije.20180724085428.1: *3* insert_node
def insert_node(self, t, i, lev):
(positions, nodes, attrs, levels, expanded, marked) = self.data
(tpositions, tnodes, tattrs, tlevels, texpanded, tmarked) = t.data
if lev == 1:
pi = 0
else:
pi = levels.rfind(lev - 1, 0, i)
pgnx = nodes[pi]
psz = attrs[pgnx].size
dpi = i - pi
rpos = positions[i-1]
sz = len(tpositions)
def insOne(j, zlev):
levels[j:j] = (x + zlev for x in tlevels)
positions[j:j] = (random.random() for x in tpositions)
nodes[j:j] = tnodes
for pxi in gnx_iter(nodes, pgnx, psz + sz):
insOne(pxi + dpi, levels[pxi] + 1)
# keep other parents of pasted node
prnts = attrs.get(tnodes[0], None)
prnts = prnts.parents if prnts else []
prnts.append(pgnx)
tattrs[tnodes[0]].parents.extend(prnts)
# sync attrs
for k, v in tattrs.items():
if k in attrs:
v1 = attrs[k]
v1.copy_from(v)
else:
attrs[k] = v
update_size(attrs, pgnx, sz)
self._update_children(pgnx)
i = positions.index(rpos) + 1
assert nodes[i] == tnodes[0], attrs[nodes[i]].h + ' is not ' + attrs[tnodes[0]].h
return positions[i]
#@+node:vitalije.20180726202438.1: *3* relink_as_clone_of
def relink_as_clone_of(self, i, j):
(positions, nodes, attrs, levels, expanded, marked) = self.data
lev = levels[i]
pos = positions[i]
pi = parent_index(levels, i)
ppos = positions[pi]
dpi = i - pi
gnx = nodes[j]
sz = attrs[gnx].size
pgnx = nodes[pi]
if pgnx in nodes[j:j+sz]:
return
t = self.subtree(positions[j])
self.delete_node(pos)
pi = positions.index(ppos)
i = dpi + pi
npos = self.insert_node(t, i, lev)
i = positions.index(npos)
positions[i] = pos
#@+node:vitalije.20180616125730.1: *3* clone_node
def clone_node_i(self, i):
return self.clone_node(self.mkpos(i))
def clone_node(self, pdata):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i, pos, gnx, lev0, nd = pdata
if i == 0: return
# this node
sz0 = nd.size
# parent
pi = parent_index(levels, i)
pp = positions[pi]
pgnx = nodes[pi]
psz = attrs[pgnx].size
# distance
di0 = i - pi
di1 = di0 + sz0
update_size(attrs, pgnx, sz0)
for pxi in gnx_iter(nodes, pgnx, psz + sz0):
A = pxi + di0
B = pxi + di1
positions[B:B] = (random.random() for x in range(sz0))
nodes[B:B] = nodes[A:A+sz0]
levels[B:B] = levels[A:A+sz0]
attrs[gnx].parents.append(pgnx)
self._update_children(pgnx)
i = positions.index(pos)
return PData(i+sz0, positions[i+sz0], gnx, lev0, nd)
#@+node:vitalije.20180724120429.1: *3* clone_marked
def clone_marked(self, gengnx):
(positions, nodes, attrs, levels, expanded, marked) = self.data
if not marked: return
i = self.selectedIndex
pi = parent_index(levels, i)
i += attrs[nodes[i]].size
pgnx = nodes[pi]
def cando(x):
if x in marked:
return False
for x1 in attrs[x].parents:
if cando(x1):continue
return False
return True
if not cando(pgnx): return
gnx = gengnx()
retp = self.insert_leaf_i_pi(i, gnx, 'Clones of marked nodes', '', pi)
chn = attrs[gnx].children
chn.extend(marked)
nps = []
nns = []
lev = levels[i] + 1
levs = []
for x in chn:
nd = attrs[x]
nd.parents.append(gnx)
j = nodes.index(x)
k = j + nd.size
lz = levels[j]
nns.extend(nodes[j:k])
levs.extend(x-lz for x in levels[j:k])
update_size(attrs, gnx, len(nns))
n = len(nns)
for pxi in gnx_iter(nodes, gnx, len(nns) + 1):
a = pxi + 1
nodes[a:a] = nns
positions[a:a] = (random.random() for x in range(n))
lz = levels[pxi] + 1
levels[a:a] = (x+lz for x in levs)
self.selectedPosition = retp
return True
#@+node:vitalije.20180724204158.1: *3* delete_marked
def delete_marked(self):
(positions, nodes, attrs, levels, expanded, marked) = self.data
if not marked: return
rgnx = nodes[0]
chn = set(attrs[rgnx].children)
if not (chn - marked): return
def delone(gnx):
nd = attrs[gnx]
sz = nd.size
for pgnx in nd.parents:
if pgnx not in attrs: continue
chn = attrs[pgnx].children
n = len(chn)
chn[:] = (x for x in chn if x != gnx)
n = n - len(chn)
update_size(attrs, pgnx, - n * sz)
for i in gnx_iter(nodes, gnx, 1):
del positions[i:i+sz]
del nodes[i:i+sz]
del levels[i:i+sz]
for x in marked:
if x in attrs:
delone(x)
attrs.pop(x)
marked.clear()
return True
#@+node:vitalije.20180724163137.1: *3* set_mark
def set_mark(self, pos):
i = self.data.positions.index(pos)
gnx = self.data.nodes[i]
self.data.marked.add(gnx)
#@+node:vitalije.20180724163425.1: *3* clear_mark
def clear_mark(self, pos):
i = self.data.positions.index(pos)
gnx = self.data.nodes[i]
self.data.marked.discard(gnx)
#@+node:vitalije.20180616151338.1: *3* _update_children
def _update_children(self, pgnx):
(positions, nodes, attrs, levels, expanded, marked) = self.data
i = nodes.index(pgnx)
del attrs[pgnx].children[:]
chn = attrs[pgnx].children
B = i + attrs[pgnx].size
j = i + 1
while j < B:
cgnx = nodes[j]
chn.append(cgnx)
j += attrs[cgnx].size
#@+node:vitalije.20180531210047.1: *3* change_gnx
def change_gnx(self, gnx1, gnx2):
if gnx2 in self.data.attrs:
raise ValueError('Gnx:%r is already in the outline'%gnx2)
( positions, nodes, attrs, levels, expanded, marked) = self.data
def swap_in(ar):
for i, x in enumerate(ar):
if x == gnx1:
ar[i] = gnx2
attrs[gnx2] = a = attrs.pop(gnx1)
for cgnx in a.children:
swap_in(attrs[cgnx].parents)
for pgnx in a.parents:
swap_in(attrs[pgnx].children)
if gnx1 in marked:
marked.remove(gnx1)
marked.add(gnx2)
for pxi in gnx_iter(nodes, gnx1, a.size):
nodes[pxi] = gnx2
#@+node:vitalije.20180510194736.1: *3* replace_node
def replace_node(self, t2):
'''Replaces node with given subtree. This outline must contain
node with the same gnx as root gnx of t2.'''
(positions1, nodes1, attrs1, levels1, expanded1, marked1) = self.data
(positions2, nodes2, attrs2, levels2, expanded2, marked2) = t2.data
gnx = nodes2[0]
sz0 = attrs1[gnx][4]
i = nodes1.index(gnx)
ns = nodes1[i+1:i+sz0]