-
Notifications
You must be signed in to change notification settings - Fork 1
/
graphterm.py
3108 lines (2531 loc) · 110 KB
/
graphterm.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
# This file implements graphterm, an interactive, ASCII representation for
# directed acyclic graphs.
#
# To Use:
# 1. Create a TermDAG object and populate with node and link information
# using the add_node(name) and add_link(source_name, sink_name) methods.
# 2. Call interactive() for an interactive curses screen with the DAG,
# or Call printonly() to print the layout to screen with the top node
# highlighted.
#
# Dependencies
# * The interactivity is managed through the curses library.
# * The ASCII layout modifies a graphical layout (TermLayout) translated from
# the Tulip graph drawing library: http://tulip.labri.fr/
#
# File: Kate Isaacs
# License: LGPL v.3
from __future__ import print_function
import heapq
from heapq import *
import curses
import curses.ascii
import math
class TermDAG(object):
"""Class to store DAG layout and manage interactions.
This class stores its own copy of the graph.
"""
def __init__(self, logfile = None, question = None):
"""Constructor. Nodes and links should be added after construction
using the add_node and add_link methods.
@param logifle: filename/path to store interaction log
@param question: question text that should be displayed above graph
"""
# Display question, keep logs for studies
self.logfile = logfile
if logfile:
self.logfile = open(logfile, 'a')
self.question = question
# Graph and layout
self._nodes = dict()
self._nodes_list = list()
self._links = list()
self._positions_set = False
self.gridsize = [0,0]
self.gridedge = [] # the last char per row
self.grid = []
self.grid_colors = []
self.row_max = 0
self.row_names = dict()
self.left_offset = 0
self.right_offset = 0
self.TL = None
self.placers = set()
# Interactive behavior
self.highlight_full_connectivity = False
self.layout = False # Is layout valid?
# Pad containing layout
self.pad = None
self.pad_pos_x = 0
self.pad_pos_y = 0
self.pad_extent_x = 0
self.pad_extent_y = 0
self.pad_corner_x = 0
self.pad_corner_y = 0
self.height = 0
self.width = 0
self.offset = 0
# Color defaults
self.maxcolor = 7
self.default_color = 0 # whatever is the true default
self.select_color = 2 # red
self.neighbor_color = 2 # red
self.initialize_help()
self.qpad = None
if self.question:
self.initialize_question()
def reset(self):
"""Resets the layout data structures for re-running the layout.
This can be used in multi-layout comparison.
"""
self._positions_set = False
self.gridsize = [0,0]
self.gridedge = [] # the last char per row
self.grid = []
self.grid_colors = []
self.row_max = 0
self.row_names = dict()
self.placers = set()
self.left_offset = 0
self.right_offset = 0
# Delete extra layout nodes
toDelete = list()
for node in self._nodes.values():
if not node.real:
toDelete.append(node)
else:
node.reset()
for node in toDelete:
del self._nodes[node.name]
del node
for link in self._links:
link.reset()
self.qpad = None
if self.question:
self.initialize_question()
def log_character(self, ch):
"""Write a character to the interaction log.
@param ch: character to write
"""
if isinstance(ch, unicode):
self.logfile.write(str(ch).decode('utf-8').encode('utf-8'))
elif isinstance(ch, int) and ch < 128:
self.logfile.write(str(unichr(ch)))
elif isinstance(ch, int):
self.logfile.write(str(ch).decode('utf-8').encode('utf-8'))
def initialize_question(self):
"""Initialize the pad that displays the question."""
self.qpad_pos_x = 0
self.qpad_pos_y = 0
self.qpad_extent_x = len(self.question)
self.qpad_extent_y = 1
self.qpad_corner_x = 0
self.qpad_corner_y = 0
self.qpad_max_x = self.qpad_extent_x + 1
self.qpad_max_y = 2
def initialize_help(self):
"""Initializes the help menu, both the pad and the items."""
self.hpad = None # Help Pad
self.hpad_default_cmds = []
self.hpad_default_cmds.append('h')
self.hpad_default_cmds.append('q')
self.hpad_default_msgs = []
self.hpad_default_msgs.append('toggle help')
self.hpad_default_msgs.append('quit')
self.hpad_pos_x = 0
self.hpad_pos_y = 0
self.hpad_extent_x = len(self.hpad_default_cmds[0]) + len(self.hpad_default_msgs[0]) + 5
self.hpad_extent_y = 3
self.hpad_corner_x = 0
self.hpad_corner_y = 0
self.hpad_collapsed = False
self.hpad_cmds = []
self.hpad_msgs = []
self.hpad_cmds.extend(self.hpad_default_cmds)
self.hpad_cmds.append('/foo')
self.hpad_cmds.append('ctrl-v')
self.hpad_cmds.append('')
self.hpad_cmds.append('n')
self.hpad_cmds.append('p')
self.hpad_cmds.append('w,a,s,d')
self.hpad_cmds.append('arrow keys')
self.hpad_msgs.extend(self.hpad_default_msgs)
self.hpad_msgs.append('highlight node "foo"')
self.hpad_msgs.append('change highlight mode:')
self.hpad_msgs.append(' neighbors or reachability')
self.hpad_msgs.append('advance highlighted node')
self.hpad_msgs.append('move back highlighted node')
self.hpad_msgs.append('scroll up, left, down, right')
self.hpad_msgs.append('scroll directions')
self.hpad_max_y = len(self.hpad_cmds)
self.hpad_max_cmd = 0
self.hpad_max_msg = 0
for i in range(len(self.hpad_cmds)):
self.hpad_max_cmd = max(len(self.hpad_cmds[i]), self.hpad_max_cmd)
self.hpad_max_msg = max(len(self.hpad_msgs[i]), self.hpad_max_msg)
hpad_collapse_max_cmd = 0
hpad_collapse_max_msg = 0
for i in range(len(self.hpad_default_cmds)):
hpad_collapse_max_cmd = max(len(self.hpad_default_cmds[i]), hpad_collapse_max_cmd)
hpad_collapse_max_msg = max(len(self.hpad_default_msgs[i]), hpad_collapse_max_msg)
# The 2 is for the prefix and suffix space
self.hpad_max_x = self.hpad_max_cmd + self.hpad_max_msg + len(' - ') + 2
self.hpad_max_collapse_x = hpad_collapse_max_msg + hpad_collapse_max_cmd + len(' - ') + 2
def add_node(self, name):
"""Add a node to the internal graph.
@param name: name of node to add.
"""
node = TermNode(name)
self._nodes[name] = node
self._nodes_list.append(name)
self.layout = False
def add_link(self, source, sink):
"""Add a link to the internal graph.
@param source: name of source node to add
@param sink: name of sink node to add
"""
link = TermLink(len(self._links), source, sink)
self._links.append(link)
self._nodes[source].add_out_link(link)
self._nodes[sink].add_in_link(link)
self.layout = False
def interactive(self):
"""Layout the graph and show interactively via curses."""
self.layout_hierarchical()
curses.wrapper(termdag_interactive_helper, self)
# Persist the depiction with stdout:
self.print_grid(True)
def printonly(self):
"""Layout the graph and print to stdout. Highlights the first node."""
self.layout_hierarchical()
self.grid_colors = []
for row in range(self.gridsize[0]):
self.grid_colors.append([self.default_color for x
in range(self.gridsize[1])])
import sys
if sys.stdout.isatty():
selected = self.node_order[0].name
self.select_node(None, selected, self.offset)
for i in range(self.gridsize[0]):
print(self.print_color_row(i, 0, self.gridsize[1] + 1))
else:
for row in self.grid:
print(''.join(row))
def report(self):
"""Report on the success of the layout algorithm."""
return self.layout_hierarchical()
def layout_hierarchical(self):
"""Layout the graph into an ASCII Grid."""
# Run graphical space layout
self.TL = TermLayout(self)
self.TL.layout()
# Data structures
xset = set() # set of seen x coords
yset = set() # set of seen y coords
node_yset = set() # set of y coords pertaining to nodes
segments = set() # set of seen segments
segment_lookup = dict()
self.segment_ids = dict()
coord_to_node = dict() # lookup a node from its coord
coord_to_placer = dict() # lookup a placer node from its coord
# Convert graphical layout to something we can manipulate for
# both nodes and links.
# Find set of all node coordinates from graphical layout.
# Also keep track of coordinate extents
maxy = -1e9
self.min_tulip_x = 1e9
self.max_tulip_x = -1e9
for node in self._nodes.values():
coord = self.TL._nodes[node.name].coord
node._x = coord[0]
node._y = coord[1]
xset.add(coord[0])
yset.add(coord[1])
node_yset.add(coord[1])
coord_to_node[(coord[0], coord[1])] = node
if coord[1] > maxy:
maxy = coord[1]
self.max_tulip_x = max(self.max_tulip_x, coord[0])
self.min_tulip_x = min(self.min_tulip_x, coord[0])
# Convert segments calculated in graphical layout to internal segments
# and update or seen x and y coords.
# Create placer nodes as necessary between segments.
# TODO: Make better use of TL which has already done some of this
# work.
# TODO: Factor some of the repeat code.
segmentID = 0
for link in self._links:
link._coords = self.TL._link_dict[link.id].segments
last = (self._nodes[link.source]._x, self._nodes[link.source]._y)
for coord in link._coords:
xset.add(coord[0])
yset.add(coord[1])
if (last[0], last[1], coord[0], coord[1]) in segment_lookup:
segment = segment_lookup[(last[0], last[1], coord[0], coord[1])]
else:
segment = TermSegment(last[0], last[1], coord[0], coord[1], segmentID)
self.segment_ids[segmentID] = segment
segmentID += 1
segments.add(segment)
segment_lookup[(last[0], last[1], coord[0], coord[1])] = segment
segment.paths.add((link.source, link.sink))
link.segments.append(segment)
segment.links.append(link)
segment.start = coord_to_node[last]
if (coord[0], coord[1]) in coord_to_node:
placer = coord_to_node[(coord[0], coord[1])]
segment.end = placer
segment.original_end = placer
placer.add_in_segment(segment)
else:
placer = TermNode("", False)
self.placers.add(placer)
coord_to_node[(coord[0], coord[1])] = placer
coord_to_placer[(coord[0], coord[1])] = placer
placer._x = coord[0]
placer._y = coord[1]
segment.end = placer
segment.original_end = placer
placer.add_in_segment(segment)
last = (coord[0], coord[1])
if (last[0], last[1], self._nodes[link.sink]._x, self._nodes[link.sink]._y) in segment_lookup:
segment = segment_lookup[(last[0], last[1], self._nodes[link.sink]._x, self._nodes[link.sink]._y)]
else:
segment = TermSegment(last[0], last[1], self._nodes[link.sink]._x,
self._nodes[link.sink]._y, segmentID)
self.segment_ids[segmentID] = segment
segment.paths.add((link.source, link.sink))
segmentID += 1
segments.add(segment)
segment_lookup[(last[0], last[1], self._nodes[link.sink]._x, self._nodes[link.sink]._y)] = segment
link.segments.append(segment)
segment.links.append(link)
placer = coord_to_node[last]
segment.start = placer
segment.end = self._nodes[link.sink]
segment.original_end = self._nodes[link.sink]
# Find crossings between segments in graphical layout.
self.find_crossings(segments)
# Consolidate crossing points so that fewer segment crossings will
# have to be dealt with. This keeps track of the x and y values of
# the crossings.
crossings_points = dict() # (x, y) -> set of segments
for k, v in self.crossings.items(): # crossings is (seg1, seg2) -> (x, y)
if v not in crossings_points:
crossings_points[v] = set()
crossings_points[v].add(k[0])
crossings_points[v].add(k[1])
self.segment_ids[k[0]].addCrossing(self.segment_ids[k[1]], v)
self.segment_ids[k[1]].addCrossing(self.segment_ids[k[0]], v)
# Based on the set of all crossings coming into a placer node,
# calculate appropriate crossing heights.
for placer in self.placers:
placer.findCrossingHeights(self.min_tulip_x, self.max_tulip_x)
# For each crossing, figure out if the end point of either already has
# a set of height for that y value. Cases:
# Neither has one: proceed as normal
# One has one: shift the crossing to that y value
# More than one has them: Ignore for now
for v, k in crossings_points.items():
x, y = v
special_heights = list()
for name in k:
segment = self.segment_ids[name]
if segment.y1 in segment.origin.original_end.crossing_heights:
special_heights.append(segment.origin.original_end.crossing_heights[segment.y1])
# Determine where to bundle depending on special heights.
placer_y = y
bundle = False
if len(special_heights) == 1:
placer_y = special_heights[0]
bundle = True
elif len(special_heights) > 1:
continue
# Get placer
if (x,placer_y) in coord_to_node:
placer = coord_to_node[(x,placer_y)]
else:
placer = TermNode('', False)
placer._x = x
placer._y = placer_y
coord_to_node[(x,placer_y)] = placer
coord_to_placer[(x,placer_y)] = placer
# Create segment break
for name in k:
segment = self.segment_ids[name]
new_segment = segment.split(placer, bundle)
segments.add(new_segment)
xset.add(x)
yset.add(placer_y)
# Convert found x and y coords in graphical layout to positions in
# the ASCII grid.
xsort = sorted(list(xset))
ysort = sorted(list(yset))
ysort.reverse()
segment_pos = dict() # Lookup of graphical y position to ASCII y position
column_multiplier = 2
row_multiplier = 2
self.gridsize = [len(ysort) - len(node_yset) + len(node_yset) * row_multiplier,
len(xsort) * column_multiplier]
y = 0
for ypos in ysort:
segment_pos[ypos] = y
if ypos in node_yset:
y += 1
y += 1
# Setup lookups from x-coord to col and y-coord to row
row_lookup = dict()
col_lookup = dict()
row_nodes = dict()
for i, x in enumerate(xsort):
col_lookup[x] = i
for i, y in enumerate(ysort):
row_lookup[y] = i
# Figure out how nodes map to rows so we can figure out label
# placement allowances
self.row_last = [0 for x in range(self.gridsize[0])]
self.row_last_mark = [0 for x in range(self.gridsize[0])]
self.row_first = [self.gridsize[1] for x in range(self.gridsize[0])]
self.row_first_mark = [self.gridsize[1] for x in range(self.gridsize[0])]
for coord, node in coord_to_node.items():
node._row = segment_pos[coord[1]]
node._col = column_multiplier * col_lookup[coord[0]]
if node.real:
if node._row not in row_nodes:
row_nodes[node._row] = []
row_nodes[node._row].append(node)
if node._col > self.row_last[node._row]:
self.row_last[node._row] = node._col
self.row_last_mark[node._row] = node._col
if node._col < self.row_first[node._row]:
self.row_first[node._row] = node._col
self.row_first_mark[node._row] = node._col
# Sort the labels by left-right position
for row, nodes in row_nodes.items():
row_nodes[row] = sorted(nodes, key = lambda node: node._col)
# Find the node order per row.
self.node_order = sorted(self._nodes.values(),
key = lambda node: node._row * 1e6 + node._col)
for i, node in enumerate(self.node_order):
node.order = i
# Create the grid
self.grid = []
for i in range(self.gridsize[0]):
self.grid.append([' ' for j in range(self.gridsize[1])])
self.gridedge.append(0)
# Add the nodes in the grid
for coord, node in coord_to_node.items():
node._row = segment_pos[coord[1]]
node._col = column_multiplier * col_lookup[coord[0]]
if node.real:
self.grid[node._row][self.left_offset + node._col] = 'o'
# Sort segments on drawing difficulty. This is used in the collision
# policy to determine which character to draw.
segments = sorted(segments, key = lambda x: x.for_segment_sort())
# Add segments to the grid. Status meaning:
# passed: Drawn with only |, /, \, _
# failed: Failed to draw for some reason
# drawing: Drawing uses X
status = 'passed'
for segment in segments:
segment.gridlist = self.draw_line(segment)
err = self.set_to_grid(segment) #, self.row_last)
if not err:
status = 'drawing'
# Determine max grid size with labels and reset grid.
self.grid = []
self.gridedge = []
self.grid_colors = []
self.calculate_max_labels(row_nodes)
# Max number of columns needed -- we add one for a space
# between the graph and the labels.
self.gridsize[1] = self.row_max + 1
# Re-create the grid for labels
for i in range(self.gridsize[0]):
self.grid.append([' ' for j in range(self.gridsize[1])])
self.gridedge.append(0)
# Re-Add the nodes in the grid
for coord, node in coord_to_node.items():
node._row = segment_pos[coord[1]]
node._col = column_multiplier * col_lookup[coord[0]]
if node.real:
self.grid[node._row][self.left_offset + node._col] = 'o'
# Re-Add segments to the grid
status = 'passed'
for segment in segments:
segment.gridlist = self.draw_line(segment)
err = self.set_to_grid(segment) #, self.row_last)
if not err:
status = 'drawing'
# Add labels to the grid
self.place_labels(row_nodes)
self.layout = True
return status
def place_label_left(self, node):
"""Attempt to place a label to the left of the node on the grid.
@param node: node with label to place.
@return True if successful, False if there is a collision.
"""
y = node._row
x = self.left_offset + node._col - 2 # start one space before node
characters = len(node.name) + 1 # include space before node
while characters > 0:
if self.grid[y][x] != '' and self.grid[y][x] != ' ':
return False
x -= 1
characters -= 1
x = self.left_offset + node._col - 1 - len(node.name)
node.label_pos = x
node.use_offset = False
for ch in node.name:
self.grid[y][x] = ch
x += 1
return True
def place_label_right(self, node):
"""Attempt to place a label to the right of the node on the grid.
@param: node: node with label to place.
@return True if successful, False if there is a collision.
"""
y = node._row
x = self.left_offset + node._col + 2 # start one space after node
characters = len(node.name) + 1 # include space after node
while characters > 0:
if self.grid[y][x] != '' and self.grid[y][x] != ' ':
return False
x += 1
characters -= 1
x = self.left_offset + node._col + 2
node.label_pos = x
node.use_offset = False
for ch in node.name:
self.grid[y][x] = ch
x += 1
return True
def place_label_bracket(self, node, left_bracket, right_bracket,
left_pos, right_pos, left_nodes, half_row):
"""Place a label in the bracketed space. Presently the left_bracket
is not used.
@returns left_bracket: string representing the running left_bracket
@returns right_bracket: string representing the running right_bracket
@returns left_pos: the offset into the left bracket
@returns right_pos: the offset into the right bracket
"""
# First attempt to place the label next to the node.
if self.place_label_right(node):
return left_bracket, right_bracket, left_pos, right_pos
if self.place_label_left(node):
return left_bracket, right_bracket, left_pos, right_pos
node.use_offset = True
# Logic for unused left bracket
#if node._col < half_row:
# if left_bracket == '':
# left_bracket = ' [ ' + node.name
# node.label_pos = left_pos + 3
# left_pos += len(node.name) + 3
# else:
# left_bracket += ', ' + node.name
# node.label_pos = left_pos + 2
# left_pos += len(node.name) + 2
# left_nodes.append(node)
#else:
if right_bracket == '':
right_bracket = ' [ ' + node.name
node.label_pos = right_pos + 3
right_pos += len(node.name) + 3
else:
right_bracket += ', ' + node.name
node.label_pos = right_pos + 2
right_pos += len(node.name) + 2
return left_bracket, right_bracket, left_pos, right_pos
def place_labels(self, row_nodes):
"""Places labels for all nodes in a grid row.
@param row_nodes: mapping from row to list of nodes on that row
"""
# Place the labels on the grid
for row, nodes in row_nodes.items():
half_row = math.floor(self.row_last_mark[row] / 2) - 1 # subtract for indexing at 0
left_pos = 0
right_pos = 0
left_bracket = ''
right_bracket = ''
left_nodes = []
right_name = ''
left_name = ''
# Special case: Last node
last = nodes[-1]
if self.place_label_right(last):
if last._col == self.row_last_mark[row]:
right_pos += len(last.name)
right_name = last.name
elif not self.place_label_left(last):
if right_name == '':
last.use_offset = True
last.label_pos = right_pos
right_pos += len(last.name)
right_name = last.name
else:
left_bracket, right_bracket, left_pos, right_pos \
= self.place_label_bracket(last, left_bracket, right_bracket,
left_pos, right_pos, left_nodes, half_row)
# Draw the rest
if len(nodes) > 1:
for node in nodes[0:-1]:
if not self.place_label_right(node) and not self.place_label_left(node):
if right_name == '':
node.use_offset = True
node.label_pos = right_pos
right_pos += len(node.name)
right_name = node.name
else:
left_bracket, right_bracket, left_pos, right_pos \
= self.place_label_bracket(node, left_bracket, right_bracket,
left_pos, right_pos, left_nodes, half_row)
if right_bracket != '':
right_bracket += ' ]'
right_pos += 2
row_left_offset = self.left_offset + self.row_first_mark[row] - left_pos
#- len(left_name) - len(left_bracket)
# Absolute positioning of the left bracket labels
for node in left_nodes:
node.use_offset = False
node.label_pos += row_left_offset - len(left_name) - 1
# Place bracketed elements
start = self.left_offset + self.row_last_mark[row] + 2 # Space between
right_names = right_name + right_bracket
for ch in right_names:
self.grid[row][start] = ch
start += 1
start = row_left_offset
left_names = left_bracket
for ch in left_names:
self.grid[row][start] = ch
start += 1
def calculate_max_labels(self, row_nodes):
"""Calculates the maximum amount of space needed to place labels
for a row of nodes.
@param row_nodes: mapping from row to list of nodes on that row
"""
self.row_max = 0
# For use in two-pracket case
#half_row = math.floor(self.gridsize[1] / 2) - 1 # subtract for indexing at 0
bracket_len = len(' [ ') + len(' ]')
comma_len = len(', ')
self.left_offset = 0
self.right_offset = 0
for row, nodes in row_nodes.items():
for node in nodes:
if len(node.name) - node._col >= 0:
self.left_offset = max(self.left_offset, 1 + len(node.name) - node._col)
if len(nodes) == 1:
self.right_offset = max(self.right_offset, 1 + len(nodes[0].name))
else:
# Figure out what bracket sides there are
right_side = 0
for node in nodes[:-1]:
if right_side == 0:
right_side = bracket_len
else:
right_side += comma_len
right_side += len(node.name)
self.right_offset = max(self.right_offset, 1 + len(nodes[-1].name) + right_side)
self.row_max = self.gridsize[1] + self.left_offset + self.right_offset
def set_to_grid(self, segment): #, row_last):
"""Converts calculated link segments into positions on the grid.
Implements rules for character collisions.
@param segment: segment to be drawn on ASCII grid.
"""
success = True
start = segment.start
end = segment.end
last_x = start._col
last_y = start._row
for i, coord in enumerate(segment.gridlist):
x, y, char, draw = coord
if x > self.row_last_mark[y]:
self.row_last_mark[y] = x
if x < self.row_first_mark[y]:
self.row_first_mark[y] = x
x += self.left_offset
if not draw or char == '':
continue
if self.grid[y][x] == ' ':
self.grid[y][x] = char
elif char != self.grid[y][x]:
# Precedence:
# Slash
# Pipe
# Underscore
#
# Crossing slashes get an X
if char == '_' and (self.grid[y][x] == '|'
or self.grid[y][x] == '/' or self.grid[y][x] == '\\'):
segment.gridlist[i] = (x, y, char, False)
elif (char == '|' or char == '/' or char == '\\') \
and self.grid[y][x] == '_':
self.grid[y][x] = char
elif char == '|' and (self.grid[y][x] == '/' or self.grid[y][x] == '\\'):
segment.gridlist[i] = (x, y, char, False)
elif (char == '/' or char == '\\') \
and self.grid[y][x] == '|':
self.grid[y][x] = char
else:
success = False
self.grid[y][x] = 'X'
#if x > row_last[y]:
# row_last[y] = x
last_x = x
last_y = y
#return row_last, success
return success
def draw_line(self, segment):
"""Determine grid positions for a line segment.
@param segment: segment to be converted to grid positions.
"""
x1 = segment.start._col
y1 = segment.start._row
x2 = segment.end._col
y2 = segment.end._row
if segment.start.real:
y1 += 1
if x2 > x1:
xdir = 1
else:
xdir = -1
ydist = y2 - y1
xdist = abs(x2 - x1)
moves = []
currentx = x1
currenty = y1
if ydist >= xdist:
# We don't ever quite travel the whole xdist -- so it's
# xdist - 1 ... except in the pure vertical case where
# xdist is already zero. Kind of strange isn't it?
for y in range(y1, y2 - max(0, xdist - 1)):
moves.append((x1, y, '|', True))
currenty = y
else:
currenty = y1 - 1
# Starting from currentx, move until just enough
# room to go the y direction (minus 1... we don't go all the way)
for x in range(x1, x2 - xdir * (ydist), xdir):
#for x in range(x1 + xdir, x2 - xdir * (ydist), xdir):
moves.append((x, y1 - 1, '_', True))
currentx = x
for y in range(currenty + 1, y2):
currentx += xdir
if xdir == 1:
moves.append((currentx, y, '\\', True))
else:
moves.append((currentx, y, '/', True))
return moves
def print_grid(self, with_colors = False):
"""Print grid to stdout.
@param with_colors: True if ANSI colors should be used. Otherwise
prints whatever terminal default is.
"""
if not self.layout:
self.layout_hierarchical()
row_begin = self.pad_corner_x
row_end = min(self.gridsize[1], self.pad_corner_x + self.width - 1)
if not with_colors or not self.grid_colors:
for row in self.grid:
if self.width == 0 or self.width > self.gridsize[1]:
print(''.join(row))
else:
window = row[rowbegin:rowend]
print(''.join(window))
return
for i in range(self.gridsize[0]):
print(self.print_color_row(i, row_begin, row_end))
def print_color_row(self, i, start, end):
"""Print a single text row using ANSI color escape codes.
@param i: row to print
@param start: start column in row to print in color
@param end: end column in row to print in color
"""
text = self.grid[i]
colors = self.grid_colors[i]
color = -1
string = ''
for i, ch in enumerate(text):
if i >= start and i <= end:
if colors[i] != color:
color = colors[i]
if color > self.maxcolor:
string += '\x1b[' + str(self.to_ansi_foreground(color - self.maxcolor + 10))
else:
string += '\x1b[' + str(self.to_ansi_foreground(color))
string += 'm'
string += ch
string += '\x1b[0m'
return string
def to_ansi_foreground(self, color):
"""Convert curses color to ANSI color.
@param color: curses color code to convert
@return color code of equivalent ANSI color
"""
# Note ANSI offset for foreground color is 30 + ANSI lookup.
# However, we are off by 1 due to curses, hence the minus one.
if color != 0:
color += 30 - 1
return color
def resize(self, stdscr):
"""Handle curses resize event.
@param stdscr: curses window.
"""
old_height = self.height
self.height, self.width = stdscr.getmaxyx()
self.offset = self.height - self.gridsize[0] - 1
self.pad_extent_y = self.height - 1 # lower left of pad winndow
if self.gridsize[0] < self.height:
self.pad_pos_y = self.height - self.gridsize[0] - 1 # upper left of pad window
self.pad_corner_y = 0
else:
self.pad_pos_y = 0
# Maintain the bottom of the graph in the same place
if old_height == 0:
self.pad_corner_y = self.gridsize[0] - self.height
else:
bottom = self.pad_corner_y + old_height
self.pad_corner_y = max(0, bottom - self.height)
self.pad_pos_x = 0 # position of pad window upper left
if self.gridsize[1] + 1 < self.width:
self.pad_extent_x = self.gridsize[1] + 1
else:
self.pad_extent_x = self.width - 1
self.hpad_pos_x = self.width - self.hpad_extent_x - 1
if self.qpad:
if self.gridsize[0] + 3 < self.height:
self.qpad_pos_y = self.height - self.gridsize[0] - 3
else:
self.qpad_pos_y = 0
def center_xy(self, stdscr, x, y):
"""Center the pad around (x,y). If this moved the pad off the screen,
shift show screen is as full as possible with pad while still showing
(x,y).
@param stdscr: curses window
@param x: x position to be centered
@param y: y position to be centered
"""
ideal_corner_x = self.pad_corner_x
ideal_corner_y = self.pad_corner_y
move_x = False
move_y = False
if x < self.pad_corner_x or x > self.pad_corner_x + self.width:
ideal_corner_x = max(0, min(x - self.width / 2, self.gridsize[1] - self.width))
move_x = True
if y < self.pad_corner_y or y > self.pad_corner_y + self.height:
ideal_corner_y = max(0, min(y - self.height / 2, self.gridsize[0] - self.height))
move_y = True
while move_x or move_y:
if move_x:
if self.pad_corner_x < ideal_corner_x:
self.scroll_left()
else:
self.scroll_right()
if self.pad_corner_x == ideal_corner_x:
move_x = False
if move_y:
if self.pad_corner_y < ideal_corner_y:
self.scroll_up()
else:
self.scroll_down()
if self.pad_corner_y == ideal_corner_y:
move_y = False
stdscr.refresh()
self.refresh_pad()
def scroll_up(self, amount = 1):
"""Performs upwards scroll by moving the main pad.
@param amount: number of rows to be scrolled.
"""