-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
ibrowse.py
1767 lines (1564 loc) · 62 KB
/
ibrowse.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
# -*- coding: iso-8859-1 -*-
import curses, fcntl, signal, struct, tty, textwrap, inspect
from IPython import ipapi
import astyle, ipipe
# Python 2.3 compatibility
try:
set
except NameError:
import sets
set = sets.Set
# Python 2.3 compatibility
try:
sorted
except NameError:
from ipipe import sorted
class UnassignedKeyError(Exception):
"""
Exception that is used for reporting unassigned keys.
"""
class UnknownCommandError(Exception):
"""
Exception that is used for reporting unknown commands (this should never
happen).
"""
class CommandError(Exception):
"""
Exception that is used for reporting that a command can't be executed.
"""
class Keymap(dict):
"""
Stores mapping of keys to commands.
"""
def __init__(self):
self._keymap = {}
def __setitem__(self, key, command):
if isinstance(key, str):
for c in key:
dict.__setitem__(self, ord(c), command)
else:
dict.__setitem__(self, key, command)
def __getitem__(self, key):
if isinstance(key, str):
key = ord(key)
return dict.__getitem__(self, key)
def __detitem__(self, key):
if isinstance(key, str):
key = ord(key)
dict.__detitem__(self, key)
def register(self, command, *keys):
for key in keys:
self[key] = command
def get(self, key, default=None):
if isinstance(key, str):
key = ord(key)
return dict.get(self, key, default)
def findkey(self, command, default=ipipe.noitem):
for (key, commandcandidate) in self.iteritems():
if commandcandidate == command:
return key
if default is ipipe.noitem:
raise KeyError(command)
return default
class _BrowserCachedItem(object):
# This is used internally by ``ibrowse`` to store a item together with its
# marked status.
__slots__ = ("item", "marked")
def __init__(self, item):
self.item = item
self.marked = False
class _BrowserHelp(object):
style_header = astyle.Style.fromstr("yellow:black:bold")
# This is used internally by ``ibrowse`` for displaying the help screen.
def __init__(self, browser):
self.browser = browser
def __xrepr__(self, mode):
yield (-1, True)
if mode == "header" or mode == "footer":
yield (astyle.style_default, "ibrowse help screen")
else:
yield (astyle.style_default, repr(self))
def __iter__(self):
# Get reverse key mapping
allkeys = {}
for (key, cmd) in self.browser.keymap.iteritems():
allkeys.setdefault(cmd, []).append(key)
fields = ("key", "description")
commands = []
for name in dir(self.browser):
if name.startswith("cmd_"):
command = getattr(self.browser, name)
commands.append((inspect.getsourcelines(command)[-1], name[4:], command))
commands.sort()
commands = [(c[1], c[2]) for c in commands]
for (i, (name, command)) in enumerate(commands):
if i:
yield ipipe.Fields(fields, key="", description="")
description = command.__doc__
if description is None:
lines = []
else:
lines = [l.strip() for l in description.splitlines() if l.strip()]
description = "\n".join(lines)
lines = textwrap.wrap(description, 60)
keys = allkeys.get(name, [])
yield ipipe.Fields(fields, key="", description=astyle.Text((self.style_header, name)))
for i in xrange(max(len(keys), len(lines))):
try:
key = self.browser.keylabel(keys[i])
except IndexError:
key = ""
try:
line = lines[i]
except IndexError:
line = ""
yield ipipe.Fields(fields, key=key, description=line)
class _BrowserLevel(object):
# This is used internally to store the state (iterator, fetch items,
# position of cursor and screen, etc.) of one browser level
# An ``ibrowse`` object keeps multiple ``_BrowserLevel`` objects in
# a stack.
def __init__(self, browser, input, mainsizey, *attrs):
self.browser = browser
self.input = input
self.header = [x for x in ipipe.xrepr(input, "header") if not isinstance(x[0], int)]
# iterator for the input
self.iterator = ipipe.xiter(input)
# is the iterator exhausted?
self.exhausted = False
# attributes to be display (autodetected if empty)
self.attrs = attrs
# fetched items (+ marked flag)
self.items = ipipe.deque()
# Number of marked objects
self.marked = 0
# Vertical cursor position
self.cury = 0
# Horizontal cursor position
self.curx = 0
# Index of first data column
self.datastartx = 0
# Index of first data line
self.datastarty = 0
# height of the data display area
self.mainsizey = mainsizey
# width of the data display area (changes when scrolling)
self.mainsizex = 0
# Size of row number (changes when scrolling)
self.numbersizex = 0
# Attributes to display (in this order)
self.displayattrs = []
# index and attribute under the cursor
self.displayattr = (None, ipipe.noitem)
# Maps attributes to column widths
self.colwidths = {}
# Set of hidden attributes
self.hiddenattrs = set()
# This takes care of all the caches etc.
self.moveto(0, 0, refresh=True)
def fetch(self, count):
# Try to fill ``self.items`` with at least ``count`` objects.
have = len(self.items)
while not self.exhausted and have < count:
try:
item = self.iterator.next()
except StopIteration:
self.exhausted = True
break
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
have += 1
self.items.append(_BrowserCachedItem(exc))
self.exhausted = True
break
else:
have += 1
self.items.append(_BrowserCachedItem(item))
def calcdisplayattrs(self):
# Calculate which attributes are available from the objects that are
# currently visible on screen (and store it in ``self.displayattrs``)
attrs = set()
self.displayattrs = []
if self.attrs:
# If the browser object specifies a fixed list of attributes,
# simply use it (removing hidden attributes).
for attr in self.attrs:
attr = ipipe.upgradexattr(attr)
if attr not in attrs and attr not in self.hiddenattrs:
self.displayattrs.append(attr)
attrs.add(attr)
else:
endy = min(self.datastarty+self.mainsizey, len(self.items))
for i in xrange(self.datastarty, endy):
for attr in ipipe.xattrs(self.items[i].item, "default"):
if attr not in attrs and attr not in self.hiddenattrs:
self.displayattrs.append(attr)
attrs.add(attr)
def getrow(self, i):
# Return a dictionary with the attributes for the object
# ``self.items[i]``. Attribute names are taken from
# ``self.displayattrs`` so ``calcdisplayattrs()`` must have been
# called before.
row = {}
item = self.items[i].item
for attr in self.displayattrs:
try:
value = attr.value(item)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
value = exc
# only store attribute if it exists (or we got an exception)
if value is not ipipe.noitem:
# remember alignment, length and colored text
row[attr] = ipipe.xformat(value, "cell", self.browser.maxattrlength)
return row
def calcwidths(self):
# Recalculate the displayed fields and their widths.
# ``calcdisplayattrs()'' must have been called and the cache
# for attributes of the objects on screen (``self.displayrows``)
# must have been filled. This sets ``self.colwidths`` which maps
# attribute descriptors to widths.
self.colwidths = {}
for row in self.displayrows:
for attr in self.displayattrs:
try:
length = row[attr][1]
except KeyError:
length = 0
# always add attribute to colwidths, even if it doesn't exist
if attr not in self.colwidths:
self.colwidths[attr] = len(attr.name())
newwidth = max(self.colwidths[attr], length)
self.colwidths[attr] = newwidth
# How many characters do we need to paint the largest item number?
self.numbersizex = len(str(self.datastarty+self.mainsizey-1))
# How must space have we got to display data?
self.mainsizex = self.browser.scrsizex-self.numbersizex-3
# width of all columns
self.datasizex = sum(self.colwidths.itervalues()) + len(self.colwidths)
def calcdisplayattr(self):
# Find out which attribute the cursor is on and store this
# information in ``self.displayattr``.
pos = 0
for (i, attr) in enumerate(self.displayattrs):
if pos+self.colwidths[attr] >= self.curx:
self.displayattr = (i, attr)
break
pos += self.colwidths[attr]+1
else:
self.displayattr = (None, ipipe.noitem)
def moveto(self, x, y, refresh=False):
# Move the cursor to the position ``(x,y)`` (in data coordinates,
# not in screen coordinates). If ``refresh`` is true, all cached
# values will be recalculated (e.g. because the list has been
# resorted, so screen positions etc. are no longer valid).
olddatastarty = self.datastarty
oldx = self.curx
oldy = self.cury
x = int(x+0.5)
y = int(y+0.5)
newx = x # remember where we wanted to move
newy = y # remember where we wanted to move
scrollbordery = min(self.browser.scrollbordery, self.mainsizey//2)
scrollborderx = min(self.browser.scrollborderx, self.mainsizex//2)
# Make sure that the cursor didn't leave the main area vertically
if y < 0:
y = 0
# try to get enough items to fill the screen
self.fetch(max(y+scrollbordery+1, self.mainsizey))
if y >= len(self.items):
y = max(0, len(self.items)-1)
# Make sure that the cursor stays on screen vertically
if y < self.datastarty+scrollbordery:
self.datastarty = max(0, y-scrollbordery)
elif y >= self.datastarty+self.mainsizey-scrollbordery:
self.datastarty = max(0, min(y-self.mainsizey+scrollbordery+1,
len(self.items)-self.mainsizey))
if refresh: # Do we need to refresh the complete display?
self.calcdisplayattrs()
endy = min(self.datastarty+self.mainsizey, len(self.items))
self.displayrows = map(self.getrow, xrange(self.datastarty, endy))
self.calcwidths()
# Did we scroll vertically => update displayrows
# and various other attributes
elif self.datastarty != olddatastarty:
# Recalculate which attributes we have to display
olddisplayattrs = self.displayattrs
self.calcdisplayattrs()
# If there are new attributes, recreate the cache
if self.displayattrs != olddisplayattrs:
endy = min(self.datastarty+self.mainsizey, len(self.items))
self.displayrows = map(self.getrow, xrange(self.datastarty, endy))
elif self.datastarty<olddatastarty: # we did scroll up
# drop rows from the end
del self.displayrows[self.datastarty-olddatastarty:]
# fetch new items
for i in xrange(min(olddatastarty, self.datastarty+self.mainsizey)-1,
self.datastarty-1, -1):
try:
row = self.getrow(i)
except IndexError:
# we didn't have enough objects to fill the screen
break
self.displayrows.insert(0, row)
else: # we did scroll down
# drop rows from the start
del self.displayrows[:self.datastarty-olddatastarty]
# fetch new items
for i in xrange(max(olddatastarty+self.mainsizey, self.datastarty),
self.datastarty+self.mainsizey):
try:
row = self.getrow(i)
except IndexError:
# we didn't have enough objects to fill the screen
break
self.displayrows.append(row)
self.calcwidths()
# Make sure that the cursor didn't leave the data area horizontally
if x < 0:
x = 0
elif x >= self.datasizex:
x = max(0, self.datasizex-1)
# Make sure that the cursor stays on screen horizontally
if x < self.datastartx+scrollborderx:
self.datastartx = max(0, x-scrollborderx)
elif x >= self.datastartx+self.mainsizex-scrollborderx:
self.datastartx = max(0, min(x-self.mainsizex+scrollborderx+1,
self.datasizex-self.mainsizex))
if x == oldx and y == oldy and (x != newx or y != newy): # couldn't move
self.browser.beep()
else:
self.curx = x
self.cury = y
self.calcdisplayattr()
def sort(self, key, reverse=False):
"""
Sort the currently list of items using the key function ``key``. If
``reverse`` is true the sort order is reversed.
"""
curitem = self.items[self.cury] # Remember where the cursor is now
# Sort items
def realkey(item):
return key(item.item)
self.items = ipipe.deque(sorted(self.items, key=realkey, reverse=reverse))
# Find out where the object under the cursor went
cury = self.cury
for (i, item) in enumerate(self.items):
if item is curitem:
cury = i
break
self.moveto(self.curx, cury, refresh=True)
def refresh(self):
"""
Restart iterating the input.
"""
self.iterator = ipipe.xiter(self.input)
self.items.clear()
self.exhausted = False
self.datastartx = self.datastarty = 0
self.moveto(0, 0, refresh=True)
def refreshfind(self):
"""
Restart iterating the input and go back to the same object as before
(if it can be found in the new iterator).
"""
try:
oldobject = self.items[self.cury].item
except IndexError:
oldobject = ipipe.noitem
self.iterator = ipipe.xiter(self.input)
self.items.clear()
self.exhausted = False
while True:
self.fetch(len(self.items)+1)
if self.exhausted:
curses.beep()
self.datastartx = self.datastarty = 0
self.moveto(self.curx, 0, refresh=True)
break
if self.items[-1].item == oldobject:
self.datastartx = self.datastarty = 0
self.moveto(self.curx, len(self.items)-1, refresh=True)
break
class _CommandInput(object):
keymap = Keymap()
keymap.register("left", curses.KEY_LEFT)
keymap.register("right", curses.KEY_RIGHT)
keymap.register("home", curses.KEY_HOME, "\x01") # Ctrl-A
keymap.register("end", curses.KEY_END, "\x05") # Ctrl-E
# FIXME: What's happening here?
keymap.register("backspace", curses.KEY_BACKSPACE, "\x08\x7f")
keymap.register("delete", curses.KEY_DC)
keymap.register("delend", 0x0b) # Ctrl-K
keymap.register("execute", "\r\n")
keymap.register("up", curses.KEY_UP)
keymap.register("down", curses.KEY_DOWN)
keymap.register("incsearchup", curses.KEY_PPAGE)
keymap.register("incsearchdown", curses.KEY_NPAGE)
keymap.register("exit", "\x18"), # Ctrl-X
def __init__(self, prompt):
self.prompt = prompt
self.history = []
self.maxhistory = 100
self.input = ""
self.curx = 0
self.cury = -1 # blank line
def start(self):
self.input = ""
self.curx = 0
self.cury = -1 # blank line
def handlekey(self, browser, key):
cmdname = self.keymap.get(key, None)
if cmdname is not None:
cmdfunc = getattr(self, "cmd_%s" % cmdname, None)
if cmdfunc is not None:
return cmdfunc(browser)
curses.beep()
elif key != -1:
try:
char = chr(key)
except ValueError:
curses.beep()
else:
return self.handlechar(browser, char)
def handlechar(self, browser, char):
self.input = self.input[:self.curx] + char + self.input[self.curx:]
self.curx += 1
return True
def dohistory(self):
self.history.insert(0, self.input)
del self.history[:-self.maxhistory]
def cmd_backspace(self, browser):
if self.curx:
self.input = self.input[:self.curx-1] + self.input[self.curx:]
self.curx -= 1
return True
else:
curses.beep()
def cmd_delete(self, browser):
if self.curx<len(self.input):
self.input = self.input[:self.curx] + self.input[self.curx+1:]
return True
else:
curses.beep()
def cmd_delend(self, browser):
if self.curx<len(self.input):
self.input = self.input[:self.curx]
return True
def cmd_left(self, browser):
if self.curx:
self.curx -= 1
return True
else:
curses.beep()
def cmd_right(self, browser):
if self.curx < len(self.input):
self.curx += 1
return True
else:
curses.beep()
def cmd_home(self, browser):
if self.curx:
self.curx = 0
return True
else:
curses.beep()
def cmd_end(self, browser):
if self.curx < len(self.input):
self.curx = len(self.input)
return True
else:
curses.beep()
def cmd_up(self, browser):
if self.cury < len(self.history)-1:
self.cury += 1
self.input = self.history[self.cury]
self.curx = len(self.input)
return True
else:
curses.beep()
def cmd_down(self, browser):
if self.cury >= 0:
self.cury -= 1
if self.cury>=0:
self.input = self.history[self.cury]
else:
self.input = ""
self.curx = len(self.input)
return True
else:
curses.beep()
def cmd_incsearchup(self, browser):
prefix = self.input[:self.curx]
cury = self.cury
while True:
cury += 1
if cury >= len(self.history):
break
if self.history[cury].startswith(prefix):
self.input = self.history[cury]
self.cury = cury
return True
curses.beep()
def cmd_incsearchdown(self, browser):
prefix = self.input[:self.curx]
cury = self.cury
while True:
cury -= 1
if cury <= 0:
break
if self.history[cury].startswith(prefix):
self.input = self.history[self.cury]
self.cury = cury
return True
curses.beep()
def cmd_exit(self, browser):
browser.mode = "default"
return True
def cmd_execute(self, browser):
raise NotImplementedError
class _CommandGoto(_CommandInput):
def __init__(self):
_CommandInput.__init__(self, "goto object #")
def handlechar(self, browser, char):
# Only accept digits
if not "0" <= char <= "9":
curses.beep()
else:
return _CommandInput.handlechar(self, browser, char)
def cmd_execute(self, browser):
level = browser.levels[-1]
if self.input:
self.dohistory()
level.moveto(level.curx, int(self.input))
browser.mode = "default"
return True
class _CommandFind(_CommandInput):
def __init__(self):
_CommandInput.__init__(self, "find expression")
def cmd_execute(self, browser):
level = browser.levels[-1]
if self.input:
self.dohistory()
while True:
cury = level.cury
level.moveto(level.curx, cury+1)
if cury == level.cury:
curses.beep()
break # hit end
item = level.items[level.cury].item
try:
globals = ipipe.getglobals(None)
if eval(self.input, globals, ipipe.AttrNamespace(item)):
break # found something
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
browser.report(exc)
curses.beep()
break # break on error
browser.mode = "default"
return True
class _CommandFindBackwards(_CommandInput):
def __init__(self):
_CommandInput.__init__(self, "find backwards expression")
def cmd_execute(self, browser):
level = browser.levels[-1]
if self.input:
self.dohistory()
while level.cury:
level.moveto(level.curx, level.cury-1)
item = level.items[level.cury].item
try:
globals = ipipe.getglobals(None)
if eval(self.input, globals, ipipe.AttrNamespace(item)):
break # found something
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
browser.report(exc)
curses.beep()
break # break on error
else:
curses.beep()
browser.mode = "default"
return True
class ibrowse(ipipe.Display):
# Show this many lines from the previous screen when paging horizontally
pageoverlapx = 1
# Show this many lines from the previous screen when paging vertically
pageoverlapy = 1
# Start scrolling when the cursor is less than this number of columns
# away from the left or right screen edge
scrollborderx = 10
# Start scrolling when the cursor is less than this number of lines
# away from the top or bottom screen edge
scrollbordery = 5
# Accelerate by this factor when scrolling horizontally
acceleratex = 1.05
# Accelerate by this factor when scrolling vertically
acceleratey = 1.05
# The maximum horizontal scroll speed
# (as a factor of the screen width (i.e. 0.5 == half a screen width)
maxspeedx = 0.5
# The maximum vertical scroll speed
# (as a factor of the screen height (i.e. 0.5 == half a screen height)
maxspeedy = 0.5
# The maximum number of header lines for browser level
# if the nesting is deeper, only the innermost levels are displayed
maxheaders = 5
# The approximate maximum length of a column entry
maxattrlength = 200
# Styles for various parts of the GUI
style_objheadertext = astyle.Style.fromstr("white:black:bold|reverse")
style_objheadernumber = astyle.Style.fromstr("white:blue:bold|reverse")
style_objheaderobject = astyle.Style.fromstr("white:black:reverse")
style_colheader = astyle.Style.fromstr("blue:white:reverse")
style_colheaderhere = astyle.Style.fromstr("green:black:bold|reverse")
style_colheadersep = astyle.Style.fromstr("blue:black:reverse")
style_number = astyle.Style.fromstr("blue:white:reverse")
style_numberhere = astyle.Style.fromstr("green:black:bold|reverse")
style_sep = astyle.Style.fromstr("blue:black")
style_data = astyle.Style.fromstr("white:black")
style_datapad = astyle.Style.fromstr("blue:black:bold")
style_footer = astyle.Style.fromstr("black:white")
style_report = astyle.Style.fromstr("white:black")
# Column separator in header
headersepchar = "|"
# Character for padding data cell entries
datapadchar = "."
# Column separator in data area
datasepchar = "|"
# Character to use for "empty" cell (i.e. for non-existing attributes)
nodatachar = "-"
# Prompts for modes that require keyboard input
prompts = {
"goto": _CommandGoto(),
"find": _CommandFind(),
"findbackwards": _CommandFindBackwards()
}
# Maps curses key codes to "function" names
keymap = Keymap()
keymap.register("quit", "q")
keymap.register("up", curses.KEY_UP)
keymap.register("down", curses.KEY_DOWN)
keymap.register("pageup", curses.KEY_PPAGE)
keymap.register("pagedown", curses.KEY_NPAGE)
keymap.register("left", curses.KEY_LEFT)
keymap.register("right", curses.KEY_RIGHT)
keymap.register("home", curses.KEY_HOME, "\x01")
keymap.register("end", curses.KEY_END, "\x05")
keymap.register("prevattr", "<\x1b")
keymap.register("nextattr", ">\t")
keymap.register("pick", "p")
keymap.register("pickattr", "P")
keymap.register("pickallattrs", "C")
keymap.register("pickmarked", "m")
keymap.register("pickmarkedattr", "M")
keymap.register("pickinput", "i")
keymap.register("pickinputattr", "I")
keymap.register("hideattr", "h")
keymap.register("unhideattrs", "H")
keymap.register("help", "?")
keymap.register("enter", "\r\n")
keymap.register("enterattr", "E")
# FIXME: What's happening here?
keymap.register("leave", curses.KEY_BACKSPACE, "x\x08\x7f")
keymap.register("detail", "d")
keymap.register("detailattr", "D")
keymap.register("tooglemark", " ")
keymap.register("markrange", "%")
keymap.register("sortattrasc", "v")
keymap.register("sortattrdesc", "V")
keymap.register("goto", "g")
keymap.register("find", "f")
keymap.register("findbackwards", "b")
keymap.register("refresh", "r")
keymap.register("refreshfind", "R")
def __init__(self, input=None, *attrs):
"""
Create a new browser. If ``attrs`` is not empty, it is the list
of attributes that will be displayed in the browser, otherwise
these will be determined by the objects on screen.
"""
ipipe.Display.__init__(self, input)
self.attrs = attrs
# Stack of browser levels
self.levels = []
# how many colums to scroll (Changes when accelerating)
self.stepx = 1.
# how many rows to scroll (Changes when accelerating)
self.stepy = 1.
# Beep on the edges of the data area? (Will be set to ``False``
# once the cursor hits the edge of the screen, so we don't get
# multiple beeps).
self._dobeep = True
# Cache for registered ``curses`` colors and styles.
self._styles = {}
self._colors = {}
self._maxcolor = 1
# How many header lines do we want to paint (the numbers of levels
# we have, but with an upper bound)
self._headerlines = 1
# Index of first header line
self._firstheaderline = 0
# curses window
self.scr = None
# report in the footer line (error, executed command etc.)
self._report = None
# value to be returned to the caller (set by commands)
self.returnvalue = None
# The mode the browser is in
# e.g. normal browsing or entering an argument for a command
self.mode = "default"
# set by the SIGWINCH signal handler
self.resized = False
def nextstepx(self, step):
"""
Accelerate horizontally.
"""
return max(1., min(step*self.acceleratex,
self.maxspeedx*self.levels[-1].mainsizex))
def nextstepy(self, step):
"""
Accelerate vertically.
"""
return max(1., min(step*self.acceleratey,
self.maxspeedy*self.levels[-1].mainsizey))
def getstyle(self, style):
"""
Register the ``style`` with ``curses`` or get it from the cache,
if it has been registered before.
"""
try:
return self._styles[style.fg, style.bg, style.attrs]
except KeyError:
attrs = 0
for b in astyle.A2CURSES:
if style.attrs & b:
attrs |= astyle.A2CURSES[b]
try:
color = self._colors[style.fg, style.bg]
except KeyError:
curses.init_pair(
self._maxcolor,
astyle.COLOR2CURSES[style.fg],
astyle.COLOR2CURSES[style.bg]
)
color = curses.color_pair(self._maxcolor)
self._colors[style.fg, style.bg] = color
self._maxcolor += 1
c = color | attrs
self._styles[style.fg, style.bg, style.attrs] = c
return c
def addstr(self, y, x, begx, endx, text, style):
"""
A version of ``curses.addstr()`` that can handle ``x`` coordinates
that are outside the screen.
"""
text2 = text[max(0, begx-x):max(0, endx-x)]
if text2:
self.scr.addstr(y, max(x, begx), text2, self.getstyle(style))
return len(text)
def addchr(self, y, x, begx, endx, c, l, style):
x0 = max(x, begx)
x1 = min(x+l, endx)
if x1>x0:
self.scr.addstr(y, x0, c*(x1-x0), self.getstyle(style))
return l
def _calcheaderlines(self, levels):
# Calculate how many headerlines do we have to display, if we have
# ``levels`` browser levels
if levels is None:
levels = len(self.levels)
self._headerlines = min(self.maxheaders, levels)
self._firstheaderline = levels-self._headerlines
def getstylehere(self, style):
"""
Return a style for displaying the original style ``style``
in the row the cursor is on.
"""
return astyle.Style(style.fg, astyle.COLOR_BLUE, style.attrs | astyle.A_BOLD)
def report(self, msg):
"""
Store the message ``msg`` for display below the footer line. This
will be displayed as soon as the screen is redrawn.
"""
self._report = msg
def enter(self, item, *attrs):
"""
Enter the object ``item``. If ``attrs`` is specified, it will be used
as a fixed list of attributes to display.
"""
if self.levels and item is self.levels[-1].input:
curses.beep()
self.report(CommandError("Recursion on input object"))
else:
oldlevels = len(self.levels)
self._calcheaderlines(oldlevels+1)
try:
level = _BrowserLevel(
self,
item,
self.scrsizey-1-self._headerlines-2,
*attrs
)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
if not self.levels:
raise
self._calcheaderlines(oldlevels)
curses.beep()
self.report(exc)
else:
self.levels.append(level)
def startkeyboardinput(self, mode):
"""
Enter mode ``mode``, which requires keyboard input.
"""
self.mode = mode
self.prompts[mode].start()
def keylabel(self, keycode):
"""
Return a pretty name for the ``curses`` key ``keycode`` (used in the
help screen and in reports about unassigned keys).
"""
if keycode <= 0xff:
specialsnames = {
ord("\n"): "RETURN",
ord(" "): "SPACE",
ord("\t"): "TAB",
ord("\x7f"): "DELETE",
ord("\x08"): "BACKSPACE",
}
if keycode in specialsnames:
return specialsnames[keycode]
elif 0x00 < keycode < 0x20:
return "CTRL-%s" % chr(keycode + 64)
return repr(chr(keycode))
for name in dir(curses):
if name.startswith("KEY_") and getattr(curses, name) == keycode:
return name
return str(keycode)
def beep(self, force=False):
if force or self._dobeep:
curses.beep()
# don't beep again (as long as the same key is pressed)
self._dobeep = False
def cmd_up(self):
"""
Move the cursor to the previous row.
"""
level = self.levels[-1]
self.report("up")
level.moveto(level.curx, level.cury-self.stepy)