summaryrefslogtreecommitdiff
path: root/examples/calc.py
blob: 2ac324ad42ffa4bfb6fdc8ea1fa970893de4846f (plain)
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
#!/usr/bin/python
#
# Urwid advanced example column calculator application
#    Copyright (C) 2004-2009  Ian Ward
#
#    This library is free software; you can redistribute it and/or
#    modify it under the terms of the GNU Lesser General Public
#    License as published by the Free Software Foundation; either
#    version 2.1 of the License, or (at your option) any later version.
#
#    This library is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with this library; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Urwid web site: http://excess.org/urwid/

"""
Urwid advanced example column calculator application

Features:
- multiple separate list boxes within columns
- custom edit widget for editing calculator cells
- custom parent widget for links to other columns
- custom list walker to show and hide cell results as required
- custom wrap and align modes for editing right-1 aligned numbers
- outputs commands that may be used to recreate expression on exit
"""

import urwid
import urwid.raw_display
import urwid.web_display

# use appropriate Screen class
if urwid.web_display.is_web_request():
    Screen = urwid.web_display.Screen
else:
    Screen = urwid.raw_display.Screen


def div_or_none(a,b):
    """Divide a by b.  Return result or None on divide by zero."""
    if b == 0:
        return None
    return a/b

# operators supported and the functions used to calculate a result
OPERATORS = {
    '+': (lambda a, b: a+b),
    '-': (lambda a, b: a-b),
    '*': (lambda a, b: a*b),
    '/': div_or_none,
    }

# the uppercase versions of keys used to switch columns
COLUMN_KEYS = list( "?ABCDEF" )

# these lists are used to determine when to display errors
EDIT_KEYS = OPERATORS.keys() + COLUMN_KEYS + ['backspace','delete']
MOVEMENT_KEYS = ['up','down','left','right','page up','page down']

# Event text
E_no_such_column = "Column %s does not exist."
E_no_more_columns = "Maxumum number of columns reached."
E_new_col_cell_not_empty = "Column must be started from an empty cell."
E_invalid_key = "Invalid key '%s'."
E_no_parent_column = "There is no parent column to return to."
E_cant_combine = "Cannot combine cells with sub-expressions."
E_invalid_in_parent_cell = "Cannot enter numbers into parent cell."
E_invalid_in_help_col = [
    "Help Column is in focus.  Press ",
    ('key',COLUMN_KEYS[1]),"-",('key',COLUMN_KEYS[-1]),
    " to select another column."]

# Shared layout object
CALC_LAYOUT = None


class CalcEvent(Exception):
    """Events triggered by user input."""

    attr = 'event'

    def __init__(self, message):
        self.message = message

    def widget(self):
        """Return a widget containing event information"""
        text = urwid.Text( self.message, 'center' )
        return urwid.AttrWrap( text, self.attr )

class ColumnDeleteEvent(CalcEvent):
    """Sent when user wants to delete a column"""

    attr = 'confirm'

    def __init__(self, letter, from_parent=0):
        self.message = ["Press ", ('key',"BACKSPACE"),
            " again to confirm column removal."]
        self.letter = letter

class UpdateParentEvent(Exception):
    """Sent when parent columns may need to be updated."""
    pass


class Cell:
    def __init__(self, op ):
        self.op = op
        self.is_top = op is None
        self.child = None
        self.setup_edit()
        self.result = urwid.Text("", layout=CALC_LAYOUT)

    def show_result(self, next_cell):
        """Return whether this widget should display its result.

        next_cell -- the cell following self or None"""

        if self.is_top:
            return False
        if next_cell is None:
            return True
        if self.op == "+" and next_cell.op == "+":
            return False
        return True


    def setup_edit(self):
        """Create the standard edit widget for this cell."""

        self.edit = urwid.IntEdit()
        if not self.is_top:
            self.edit.set_caption( self.op + " " )
        self.edit.set_layout( None, None, CALC_LAYOUT )

    def get_value(self):
        """Return the numeric value of the cell."""

        if self.child is not None:
            return self.child.get_result()
        else:
            return long("0"+self.edit.edit_text)

    def get_result(self):
        """Return the numeric result of this cell's operation."""

        if self.is_top:
            return self.get_value()
        if self.result.text == "":
            return None
        return long(self.result.text)

    def set_result(self, result):
        """Set the numeric result for this cell."""

        if result == None:
            self.result.set_text("")
        else:
            self.result.set_text( "%d" %result )

    def become_parent(self, column, letter):
        """Change the edit widget to a parent cell widget."""

        self.child = column
        self.edit = ParentEdit( self.op, letter )

    def remove_child(self):
        """Change the edit widget back to a standard edit widget."""

        self.child = None
        self.setup_edit()

    def is_empty( self ):
        """Return True if the cell is "empty"."""

        return self.child is None and self.edit.edit_text == ""


class ParentEdit(urwid.Edit):
    """Edit widget modified to link to a child column"""

    def __init__(self, op, letter):
        """Use the operator and letter of the child column as caption

        op -- operator or None
        letter -- letter of child column
        remove_fn -- function to call when user wants to remove child
                     function takes no parameters
        """

        urwid.Edit.__init__(self, layout=CALC_LAYOUT)
        self.op = op
        self.set_letter( letter )

    def set_letter(self, letter):
        """Set the letter of the child column for display."""

        self.letter = letter
        caption = "("+letter+")"
        if self.op is not None:
            caption = self.op+" "+caption
        self.set_caption(caption)

    def keypress(self, size, key):
        """Disable usual editing, allow only removing of child"""

        if key == "backspace":
            raise ColumnDeleteEvent(self.letter, from_parent=True)
        elif key in list("0123456789"):
            raise CalcEvent, E_invalid_in_parent_cell
        else:
            return key


class CellWalker(urwid.ListWalker):
    def __init__(self, content):
        self.content = urwid.MonitoredList(content)
        self.content.modified = self._modified
        self.focus = (0,0)
        # everyone can share the same divider widget
        self.div = urwid.Divider("-")

    def get_cell(self, i):
        if i < 0 or i >= len(self.content):
            return None
        else:
            return self.content[i]

    def _get_at_pos(self, pos):
        i, sub = pos
        assert sub in (0,1,2)
        if i < 0 or i >= len(self.content):
            return None, None
        if sub == 0:
            edit = self.content[i].edit
            return urwid.AttrWrap(edit, 'edit', 'editfocus'), pos
        elif sub == 1:
            return self.div, pos
        else:
            return self.content[i].result, pos

    def get_focus(self):
        return self._get_at_pos(self.focus)

    def set_focus(self, focus):
        self.focus = focus

    def get_next(self, start_from):
        i, sub = start_from
        assert sub in (0,1,2)
        if sub == 0:
            show_result = self.content[i].show_result(
                self.get_cell(i+1))
            if show_result:
                return self._get_at_pos( (i, 1) )
            else:
                return self._get_at_pos( (i+1, 0) )
        elif sub == 1:
            return self._get_at_pos( (i, 2) )
        else:
            return self._get_at_pos( (i+1, 0) )

    def get_prev(self, start_from):
        i, sub = start_from
        assert sub in (0,1,2)
        if sub == 0:
            if i == 0: return None, None
            show_result = self.content[i-1].show_result(
                self.content[i])
            if show_result:
                return self._get_at_pos( (i-1, 2) )
            else:
                return self._get_at_pos( (i-1, 0) )
        elif sub == 1:
            return self._get_at_pos( (i, 0) )
        else:
            return self._get_at_pos( (i, 1) )


class CellColumn( urwid.WidgetWrap ):
    def __init__(self, letter):
        self.walker = CellWalker([Cell(None)])
        self.content = self.walker.content
        self.listbox = urwid.ListBox( self.walker )
        self.set_letter( letter )
        urwid.WidgetWrap.__init__(self, self.frame)

    def set_letter(self, letter):
        """Set the column header with letter."""

        self.letter = letter
        header = urwid.AttrWrap(
            urwid.Text( ["Column ",('key',letter)],
            layout = CALC_LAYOUT), 'colhead' )
        self.frame = urwid.Frame( self.listbox, header )

    def keypress(self, size, key):
        key = self.frame.keypress( size, key)
        if key is None:
            changed = self.update_results()
            if changed:
                raise UpdateParentEvent()
            return

        f, (i, sub) = self.walker.get_focus()
        if sub != 0:
            # f is not an edit widget
            return key
        if key in OPERATORS:
            # move trailing text to new cell below
            edit = self.walker.get_cell(i).edit
            cursor_pos = edit.edit_pos
            tail = edit.edit_text[cursor_pos:]
            edit.set_edit_text( edit.edit_text[:cursor_pos] )

            new_cell = Cell( key )
            new_cell.edit.set_edit_text( tail )
            self.content[i+1:i+1] = [new_cell]

            changed = self.update_results()
            self.move_focus_next( size )
            self.content[i+1].edit.set_edit_pos(0)
            if changed:
                raise UpdateParentEvent()
            return

        elif key == 'backspace':
            # unhandled backspace, we're at beginning of number
            # append current number to cell above, removing operator
            above = self.walker.get_cell(i-1)
            if above is None:
                # we're the first cell
                raise ColumnDeleteEvent( self.letter,
                    from_parent=False )

            edit = self.walker.get_cell(i).edit
            # check that we can combine
            if above.child is not None:
                # cell above is parent
                if edit.edit_text:
                    # ..and current not empty, no good
                    raise CalcEvent, E_cant_combine
                above_pos = 0
            else:
                # above is normal number cell
                above_pos = len(above.edit.edit_text)
                above.edit.set_edit_text( above.edit.edit_text +
                    edit.edit_text )

            self.move_focus_prev( size )
            self.content[i-1].edit.set_edit_pos(above_pos)
            del self.content[i]
            changed = self.update_results()
            if changed:
                raise UpdateParentEvent()
            return

        elif key == 'delete':
            # pull text from next cell into current
            cell = self.walker.get_cell(i)
            below = self.walker.get_cell(i+1)
            if cell.child is not None:
                # this cell is a parent
                raise CalcEvent, E_cant_combine
            if below is None:
                # nothing below
                return key
            if below.child is not None:
                # cell below is a parent
                raise CalcEvent, E_cant_combine

            edit = self.walker.get_cell(i).edit
            edit.set_edit_text( edit.edit_text +
                below.edit.edit_text )

            del self.content[i+1]
            changed = self.update_results()
            if changed:
                raise UpdateParentEvent()
            return
        return key


    def move_focus_next(self, size):
        f, (i, sub) = self.walker.get_focus()
        assert i<len(self.content)-1

        ni = i
        while ni == i:
            self.frame.keypress(size, 'down')
            nf, (ni, nsub) = self.walker.get_focus()

    def move_focus_prev(self, size):
        f, (i, sub) = self.walker.get_focus()
        assert i>0

        ni = i
        while ni == i:
            self.frame.keypress(size, 'up')
            nf, (ni, nsub) = self.walker.get_focus()


    def update_results( self, start_from=None ):
        """Update column.  Return True if final result changed.

        start_from -- Cell to start updating from or None to start from
                      the current focus (default None)
        """

        if start_from is None:
            f, (i, sub) = self.walker.get_focus()
        else:
            i = self.content.index(start_from)
            if i == None: return False

        focus_cell = self.walker.get_cell(i)

        if focus_cell.is_top:
            x = focus_cell.get_value()
            last_op = None
        else:
            last_cell = self.walker.get_cell(i-1)
            x = last_cell.get_result()

            if x is not None and focus_cell.op is not None:
                x = OPERATORS[focus_cell.op]( x,
                    focus_cell.get_value() )
            focus_cell.set_result(x)

        for cell in self.content[i+1:]:
            if cell.op is None:
                x = None
            if x is not None:
                x = OPERATORS[cell.op]( x, cell.get_value() )
            if cell.get_result() == x:
                return False
            cell.set_result(x)

        return True


    def create_child( self, letter ):
        """Return (parent cell,child column) or None,None on failure."""
        f, (i, sub) = self.walker.get_focus()
        if sub != 0:
            # f is not an edit widget
            return None, None

        cell = self.walker.get_cell(i)
        if cell.child is not None:
            raise CalcEvent, E_new_col_cell_not_empty
        if cell.edit.edit_text:
            raise CalcEvent, E_new_col_cell_not_empty

        child = CellColumn( letter )
        cell.become_parent( child, letter )

        return cell, child

    def is_empty( self ):
        """Return True if this column is empty."""

        return len(self.content)==1 and self.content[0].is_empty()


    def get_expression(self):
        """Return the expression as a printable string."""

        l = []
        for c in self.content:
            if c.op is not None: # only applies to first cell
                l.append(c.op)
            if c.child is not None:
                l.append("("+c.child.get_expression()+")")
            else:
                l.append("%d"%c.get_value())

        return "".join(l)

    def get_result(self):
        """Return the result of the last cell in the column."""

        return self.content[-1].get_result()




class HelpColumn(urwid.BoxWidget):
    help_text = [
        ('title', "Column Calculator"),
        "",
        [ "Numbers: ", ('key', "0"), "-", ('key', "9") ],
        "" ,
        [ "Operators: ",('key', "+"), ", ", ('key', "-"), ", ",
            ('key', "*"), " and ", ('key', "/")],
        "",
        [ "Editing: ", ('key', "BACKSPACE"), " and ",('key', "DELETE")],
        "",
        [ "Movement: ", ('key', "UP"), ", ", ('key', "DOWN"), ", ",
            ('key', "LEFT"), ", ", ('key', "RIGHT"), ", ",
            ('key', "PAGE UP"), " and ", ('key', "PAGE DOWN") ],
        "",
        [ "Sub-expressions: ", ('key', "("), " and ", ('key', ")") ],
        "",
        [ "Columns: ", ('key', COLUMN_KEYS[0]), " and ",
            ('key',COLUMN_KEYS[1]), "-",
            ('key',COLUMN_KEYS[-1]) ],
        "",
        [ "Exit: ", ('key', "Q") ],
        "",
        "",
        ["Column Calculator does operations in the order they are ",
            "typed, not by following usual precedence rules.  ",
            "If you want to calculate ", ('key', "12 - 2 * 3"),
            " with the multiplication happening before the ",
            "subtraction you must type ",
            ('key', "12 - (2 * 3)"), " instead."],
        ]

    def __init__(self):
        self.head = urwid.AttrWrap(
            urwid.Text(["Help Column ", ('key',"?")],
                layout = CALC_LAYOUT),
            'help')
        self.foot = urwid.AttrWrap(
            urwid.Text(["[text continues.. press ",
            ('key',"?"), " then scroll]"]), 'helpnote' )
        self.items = [urwid.Text(x) for x in self.help_text]
        self.listbox = urwid.ListBox(urwid.SimpleListWalker(self.items))
        self.body = urwid.AttrWrap( self.listbox, 'help' )
        self.frame = urwid.Frame( self.body, header=self.head)

    def render(self, size, focus=False):
        maxcol, maxrow = size
        head_rows = self.head.rows((maxcol,))
        if "bottom" in self.listbox.ends_visible(
            (maxcol, maxrow-head_rows) ):
            self.frame.footer = None
        else:
            self.frame.footer = self.foot

        return self.frame.render( (maxcol, maxrow), focus)

    def keypress( self, size, key ):
        return self.frame.keypress( size, key )


class CalcDisplay:
    palette = [
        ('body','white', 'dark blue'),
        ('edit','yellow', 'dark blue'),
        ('editfocus','yellow','dark cyan', 'bold'),
        ('key','dark cyan', 'light gray', ('standout','underline')),
        ('title', 'white', 'light gray', ('bold','standout')),
        ('help', 'black', 'light gray', 'standout'),
        ('helpnote', 'dark green', 'light gray'),
        ('colhead', 'black', 'light gray', 'standout'),
        ('event', 'light red', 'black', 'standout'),
        ('confirm', 'yellow', 'black', 'bold'),
        ]

    def __init__(self):
        self.columns = urwid.Columns([HelpColumn(), CellColumn("A")], 1)
        self.col_list = self.columns.widget_list
        self.columns.set_focus_column( 1 )
        view = urwid.AttrWrap(self.columns, 'body')
        self.view = urwid.Frame(view) # for showing messages
        self.col_link = {}

    def main(self):
        self.loop = urwid.MainLoop(self.view, self.palette, screen=Screen(),
            input_filter=self.input_filter)
        self.loop.run()

        # on exit write the formula and the result to the console
        expression, result = self.get_expression_result()
        print "Paste this expression into a new Column Calculator session to continue editing:"
        print expression
        print "Result:", result

    def input_filter(self, input, raw_input):
        if 'q' in input or 'Q' in input:
            raise urwid.ExitMainLoop()

        # handle other keystrokes
        for k in input:
            try:
                self.wrap_keypress(k)
                self.event = None
                self.view.footer = None
            except CalcEvent, e:
                # display any message
                self.event = e
                self.view.footer = e.widget()

        # remove all input from further processing by MainLoop
        return []

    def wrap_keypress(self, key):
        """Handle confirmation and throw event on bad input."""

        try:
            key = self.keypress(key)

        except ColumnDeleteEvent, e:
            if e.letter == COLUMN_KEYS[1]:
                # cannot delete the first column, ignore key
                return

            if not self.column_empty( e.letter ):
                # need to get two in a row, so check last event
                if not isinstance(self.event,ColumnDeleteEvent):
                    # ask for confirmation
                    raise e
            self.delete_column(e.letter)

        except UpdateParentEvent, e:
            self.update_parent_columns()
            return

        if key is None:
            return

        if self.columns.get_focus_column() == 0:
            if key not in ('up','down','page up','page down'):
                raise CalcEvent, E_invalid_in_help_col

        if key not in EDIT_KEYS and key not in MOVEMENT_KEYS:
            raise CalcEvent, E_invalid_key % key.upper()

    def keypress(self, key):
        """Handle a keystroke."""

        self.loop.process_input([key])

        if key.upper() in COLUMN_KEYS:
            # column switch
            i = COLUMN_KEYS.index(key.upper())
            if i >= len( self.col_list ):
                raise CalcEvent, E_no_such_column % key.upper()
            self.columns.set_focus_column( i )
            return
        elif key == "(":
            # open a new column
            if len( self.col_list ) >= len(COLUMN_KEYS):
                raise CalcEvent, E_no_more_columns
            i = self.columns.get_focus_column()
            if i == 0:
                # makes no sense in help column
                return key
            col = self.col_list[i]
            new_letter = COLUMN_KEYS[len(self.col_list)]
            parent, child = col.create_child( new_letter )
            if child is None:
                # something invalid in focus
                return key
            self.col_list.append(child)
            self.set_link( parent, col, child )
            self.columns.set_focus_column(len(self.col_list)-1)

        elif key == ")":
            i = self.columns.get_focus_column()
            if i == 0:
                # makes no sense in help column
                return key
            col = self.col_list[i]
            parent, pcol = self.get_parent( col )
            if parent is None:
                # column has no parent
                raise CalcEvent, E_no_parent_column

            new_i = self.col_list.index( pcol )
            self.columns.set_focus_column( new_i )
        else:
            return key

    def set_link( self, parent, pcol, child ):
        """Store the link between a parent cell and child column.

        parent -- parent Cell object
        pcol -- CellColumn where parent resides
        child -- child CellColumn object"""

        self.col_link[ child ] = parent, pcol

    def get_parent( self, child ):
        """Return the parent and parent column for a given column."""

        return self.col_link.get( child, (None,None) )

    def column_empty(self, letter):
        """Return True if the column passed is empty."""

        i = COLUMN_KEYS.index(letter)
        col = self.col_list[i]
        return col.is_empty()


    def delete_column(self, letter):
        """Delete the column with the given letter."""

        i = COLUMN_KEYS.index(letter)
        col = self.col_list[i]

        parent, pcol = self.get_parent( col )

        f = self.columns.get_focus_column()
        if f == i:
            # move focus to the parent column
            f = self.col_list.index(pcol)
            self.columns.set_focus_column(f)

        parent.remove_child()
        pcol.update_results(parent)
        del self.col_list[i]

        # delete children of this column
        keep_right_cols = []
        remove_cols = [col]
        for rcol in self.col_list[i:]:
            parent, pcol = self.get_parent( rcol )
            if pcol in remove_cols:
                remove_cols.append( rcol )
            else:
                keep_right_cols.append( rcol )
        for rc in remove_cols:
            # remove the links
            del self.col_link[rc]
        # keep only the non-children
        self.col_list[i:] = keep_right_cols

        # fix the letter assignments
        for j in range(i, len(self.col_list)):
            col = self.col_list[j]
            # fix the column heading
            col.set_letter( COLUMN_KEYS[j] )
            parent, pcol = self.get_parent( col )
            # fix the parent cell
            parent.edit.set_letter( COLUMN_KEYS[j] )

    def update_parent_columns(self):
        "Update the parent columns of the current focus column."

        f = self.columns.get_focus_column()
        col = self.col_list[f]
        while 1:
            parent, pcol = self.get_parent(col)
            if pcol is None:
                return

            changed = pcol.update_results( start_from = parent )
            if not changed:
                return
            col = pcol


    def get_expression_result(self):
        """Return (expression, result) as strings."""

        col = self.col_list[1]
        return col.get_expression(), "%d"%col.get_result()



class CalcNumLayout(urwid.TextLayout):
    """
    TextLayout class for bottom-right aligned numbers with a space on
    the last line for the cursor.
    """
    def layout( self, text, width, align, wrap ):
        """
        Return layout structure for calculator number display.
        """
        lt = len(text) + 1 # extra space for cursor
        r = (lt) % width # remaining segment not full width wide
        linestarts = range( r, lt, width )
        l = []
        if linestarts:
            if r:
                # right-align the remaining segment on 1st line
                l.append( [(width-r,None),(r, 0, r)] )
            # fill all but the last line
            for x in linestarts[:-1]:
                l.append( [(width, x, x+width)] )
            s = linestarts[-1]
            # add the last line with a cursor hint
            l.append( [(width-1, s, lt-1), (0, lt-1)] )
        elif lt-1:
            # all fits on one line, so right align the text
            # with a cursor hint at the end
            l.append( [(width-lt,None),(lt-1,0,lt-1), (0,lt-1)] )
        else:
            # nothing on the line, right align a cursor hint
            l.append( [(width-1,None),(0,0)] )

        return l




def main():
    """Launch Column Calculator."""
    global CALC_LAYOUT
    CALC_LAYOUT = CalcNumLayout()

    urwid.web_display.set_preferences("Column Calculator")
    # try to handle short web requests quickly
    if urwid.web_display.handle_short_request():
        return

    CalcDisplay().main()

if '__main__'==__name__ or urwid.web_display.is_web_request():
    main()