Source

vinstall / vinstall / ui / urwid.py

Full commit
  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
#-*- coding: utf-8 -*-


"""An Urwid based view."""

# pylint cant understand my relative imports
# pylint: disable-msg=E1101,W0406,W0404


from __future__ import absolute_import

import urwid
import os
from itertools import cycle
from urwid_combobox import ComboBox
from vinstall.core import core, model, command
from vinstall.backend import mountpoints


# workaround a weird unicode error
ComboBox._combobox_mark = ""


class UrwidView:
    """Base class for Urwid view."""

    # overload some methods from the interface that are not needed for this
    # view
    def show(self):
        """Toggle all the widgets visible.

        """
        pass

    def connect(self):
        """Connect signals.

        """
        pass


@core.main_window
class UrwidMainWindow(object):
    """Top level widget for Urwid views.

    """
    default_palette = [
        ('body',            'black',        'light gray',   'standout'),
        ('bg 1',            'light green',  'black',        'standout'),
        ('header',          'dark green',   'black',        'bold'),
        ('title',           'light green',  'black',        'bold'),
        ('intro',           'dark green',   'black'),
        ('background main', 'white',        'black',        'standout'),
        ('body bg',         'light green',  'dark gray',    'standout'),
        ('edit',            'light green',  'dark gray'),
        ('edit active',     'white',        'black',        'bold'),
        ('active'     ,     'white',        'dark gray',    'bold'),
        ('button normal',   'dark green',   'black',        'standout'),
        ('button select',   'light green',  'black',        'bold'),
        ('popbg',           'light green',  'black',        'bold'),
        ('pb normal',       'dark green',   'black'),
        ('pb complete',     'black',        'dark green'),
        ]

    blue_palette = [
        ('body',            'dark blue',    'light gray',   'standout'),
        ('bg 1',            'yellow',       'dark blue',    'standout'),
        ('header',          'yellow',       'dark red',     'bold'),
        ('title',           'yellow',       'dark blue',    'bold'),
        ('intro',           'yellow',       'dark blue'),
        ('background main', 'yellow',       'dark blue',    'standout'),
        ('body bg',         'yellow',       'dark gray',    'standout'),
        ('edit',            'yellow',       'dark gray'),
        ('edit active',     'white',        'dark gray',    'bold'),
        ('active'     ,     'white',        'dark gray',    'bold'),
        ('button normal',   'yellow',       'dark blue',    'standout'),
        ('button select',   'white',        'dark blue',    'bold'),
        ('popbg',           'white',        'dark blue',    'bold'),
        ('pb normal',       'yellow',       'dark red'),
        ('pb complete',     'dark blue',    'yellow'),
        ]

    urwid.command_map["esc"] = "cursor down"
    #urwid.command_map["tab"] = "cursor down"
    #urwid.command_map["shift tab"] = "cursor up"
    urwid.command_map["j"] = "cursor down"
    urwid.command_map["k"] = "cursor up"

    def __init__(self):
        """View initialization.

        """
        self.title = ""
        self.intro = ""
        self.widgets = []

        self.next_button = urwid.Button("Next")
        self.back_button = urwid.Button("Back")
        self.next_callback = None
        self.back_callback = None
        self._input_disabled = False

        self.frame = self.get_frame()
        self.loop = urwid.MainLoop(self.frame,
                unhandled_input=self.unhandled_input, pop_ups=True)
        type(self).pipe = self.loop.watch_pipe(lambda x: {'close': False}.get(x, True))

        self.palettes = cycle([self.default_palette, self.blue_palette])
        self.set_palette()

    def get_title(self):
        """Return a Text instance for the section title.

        """
        text = self.title
        return urwid.Text(('title', text), align='left')

    def get_intro(self):
        """Return a Text instance for the introductory paragraph.

        """
        text = self.intro
        return urwid.Text(('intro', text))

    def get_contents(self):
        """Return a Pile containing the central widgets.

        """
        widgets = [urwid.Divider(),]
        for i in self.widgets:
            widgets.append(i)
            widgets.append(urwid.Divider())
        container = urwid.Pile(widgets)
        container = urwid.Padding(container, "center", 60)
        container = urwid.LineBox(container)
        container = urwid.AttrWrap(container, "body bg")
        container = urwid.Padding(container, "center", 70)
        return container

    def get_buttons(self):
        """Return a GridFlow instance containing the buttons.

        """
        if self._input_disabled:
            return urwid.Divider()

        next_button = urwid.AttrWrap(self.next_button, "button normal",
                "button select")
        back_button = urwid.AttrWrap(self.back_button, "button normal",
                "button select")
        return urwid.GridFlow([back_button, next_button], 15, 2, 2,
                align="right")

    def get_body(self):
        """Return a SimpleListWalker for holding the central frame including
        the title, the introductory text, the form widgets and the buttons.

        """
        pile = urwid.SimpleListWalker([
            urwid.Divider(),
            self.get_title(),
            urwid.Divider(),
            self.get_intro(),
            urwid.Divider(),
            urwid.Divider(),
            self.get_contents(),
            urwid.Divider(),
            urwid.Divider(),
            self.get_buttons()])

        pile = urwid.ListBox(pile)
        pile = urwid.Padding(pile, "center", 79)
        pile = urwid.AttrMap(pile, "bg 1")
        return pile

    def get_frame(self):
        """Return a Frame object which will act as the top level widget of our
        application.

        """
        frame = urwid.Frame(self.get_body(),
                header=urwid.Text(("header", " VL Installer  |  F2: change"\
                        " palette \n")),
                footer=urwid.Text(("header", "\n (C)2010 - GNU LGPL3 \n" )))
        frame = urwid.AttrWrap(frame, "background main")
        return frame

    def update(self):
        """Update the frame with a new body after the next or previous button
        is clicked. Used by the controller classes to refresh the UI.

        """
        body = self.get_body()
        self.frame.w.body = body

    def disable_buttons(self):
        """Disable buttons, usefull for avoiding errors during long running
        tasks

        """
        self._input_disabled = True
        self.update()

    def enable_buttons(self):
        """Enable user input after a long running process ended

        """
        self._input_disabled = False
        self.update()

    def set_next_button_label(self, text):
        """Set next button label

        """
        self.next_button.set_label(text)
        self.update()

    def set_previous_button_label(self, text):
        """Set previous button label

        """
        self.back_button.set_label(text)
        self.update()

    def refresh(self):
        """Force an update of the screen

        """

    def add_next_callback(self, func, user_arg=None):
        """Set a callback for the next button "click" signal. This is used by
        the controller classes to process user input and setup the next state
        of the application.

        """
        self.next_callback = func
        urwid.connect_signal(self.next_button, "click", func, user_arg=user_arg)

    def add_previous_callback(self, func, user_arg=None):
        """Set a callback for the previous button "click" signal. Used by the
        controller classes for jumping to a previous state.

        """
        self.back_callback = func
        urwid.connect_signal(self.back_button, "click", func, user_arg=user_arg)

    def clear_callbacks(self):
        """Remove every callback from the buttons.

        """
        if self.next_callback:
            urwid.disconnect_signal(self.next_button, "click",
                    self.next_callback)
        if self.back_callback:
            urwid.disconnect_signal(self.back_button,
                    "click", self.back_callback)

    def set_palette(self):
        """Set the coloscheme.

        """
        palette = self.palettes.next()
        self.loop.screen.register_palette(palette)

    def unhandled_input(self, key):
        """Handle unmanaged keys.

        """
        if key == "f2":
            self.set_palette()

    def run(self):
        """Start the main loop.

        """
        self.loop.run()

    def stop(self):
        """Stop the main loop.

        """
        raise urwid.ExitMainLoop


@core.renders(model.SimpleText)
class UrwidTextLabel(UrwidView):
    """ A simple text label for information purposes only.

    """
    def __init__(self, label):
        """UrwidTextLabel initialization.

        """
        self.text = label.text

    def accept(self):
        """Return a text widget.

        """
        return urwid.Text(self.text)

    def configure(self):
        """We dont need it in this simple widget.

        """
        pass

    def get_value(self):
        """This widget has no user input. Return None.

        """
        return None


@core.renders(model.TextOption)
class UrwidTextInput(UrwidView):
    """A text input widget for rendering the TextOption model.

    """
    def __init__(self, text_option):

        # Expose the model
        self.option_name = text_option.name
        self.option_maxlen = text_option.maxlen
        self.option_short_desc = text_option.short_desc
        self.option_help = text_option.help_text

        # Widgets
        self.edit = urwid.Edit()
        self.wrap = None

    def configure(self):
        """Setup the elements composing the model view."""

        # Configure the Edit widgets
        self.edit.set_caption(self.option_name + ": ")
        self.wrap = urwid.AttrWrap(self.edit, 'edit', 'edit active')

    def get_value(self):
        """Returns the text entered by the user."""

        return self.edit.edit_text

    def accept(self):
        """Returns the configured top level container widget."""

        return self.wrap


@core.renders(model.NumericOption)
class UrwidNumericInput(UrwidView):
    """A widget accepting numeric input for rendering the NumericOption model.

    """
    def __init__(self, text_option):

        # Expose the model
        self.option_name = text_option.name
        self.option_short_desc = text_option.short_desc
        self.option_help = text_option.help_text

        # Widgets
        self.edit = urwid.IntEdit()
        self.wrap = None

    def configure(self):
        """Setup the elements composing the model view."""

        # Configure the Edit widgets
        self.edit.set_caption(self.option_name + ": ")
        self.wrap = urwid.AttrWrap(self.edit, 'edit', 'edit active')

    def get_value(self):
        """Returns the text entered by the user."""

        return self.edit.value()

    def accept(self):
        """Returns the configured top level container widget."""

        return self.wrap


@core.renders(model.BoolOption)
class UrwidBoolInput(UrwidView):
    """A a two-states widget for boolean options.

    """
    def __init__(self, bool_option):

        self.option_name = bool_option.name
        self.option_short_desc = bool_option.short_desc
        self.option_help = bool_option.help_text

        # Widgets
        self.check_box = urwid.CheckBox(self.option_name)
        self.wrap = None

    def configure(self):
        """Set up the container widget.

        """
        self.wrap = urwid.AttrWrap(self.check_box, 'edit', 'active')

    def get_value(self):
        """Return the user input.

        """
        return self.check_box.state

    def accept(self):
        """Return the toplevel widget.

        """
        return self.wrap


@core.renders(model.ExclusiveOptionList)
class UrwidExclusiveList(UrwidView):
    """A list of options, from which the user can pick only one.

    """
    def __init__(self, options_list):

        self.options_list = options_list.options

        # Widgets
        self.radio_button_list = []
        self.group = []
        self.wrap = None

    def configure(self):
        """Setup widgets.

        """
        for option in self.options_list:
            radio_button = urwid.RadioButton(self.group, option['name'])
            wrap = urwid.AttrWrap(radio_button, 'edit', 'active')
            self.radio_button_list.append(wrap)

        pile = urwid.Pile(self.radio_button_list)
        self.wrap = urwid.AttrWrap(pile, "selectable")

    def get_value(self):
        """Return the user input.

        """
        for index, radio_button in enumerate(self.radio_button_list):
            if radio_button.state:
                return index

    def accept(self):
        """Return the top level widget.

        """
        return self.wrap


@core.renders(model.DropdownOptionList)
class UrwidDropdownList(UrwidView):
    """A widget for processing long exclusive options lists

    """
    def __init__(self, options):

        self.text = options.label
        self.options = [ d["option"] for d in options.options ]
        self.combo = None
        self.columns = None

    def configure(self):
        """Setup the widgets

        """
        label = urwid.Text(self.text)
        maxlabel = max(len(i) for i in self.options)
        self.combo = ComboBox(self.options)
        self.columns = urwid.Columns(
                [("fixed", len(self.text) + 2, label),
                 ("fixed", maxlabel + 6, self.combo)], dividechars=1, min_width=1)

    def get_value(self):
        """Return user selection

        """
        return self.combo.get_selection()

    def accept(self):
        """Return the top level widget

        """
        return urwid.AttrWrap(self.columns, "edit", "active")


@core.renders(model.IPAddress)
class UrwidIPAddress(UrwidView):
    """A widget designed for entering an IP address.

    """
    def __init__(self, ip_option):

        self.option_name = ip_option.name
        self.short_desc = ip_option.short_desc
        self.help = ip_option.help_text

        # Widgets
        self.caption = None
        self.columns = None
        self.widgets = []
        self.edit_widgets = []

    def configure(self):
        """Setup the input widgets and a container.

        """
        self.caption = urwid.Text(self.option_name + ": ")
        self.widgets.append(self.caption)

        for i in xrange(4):
            edit = urwid.Edit("")
            edit = urwid.AttrWrap(edit, "edit", "edit active")
            edit.set_edit_text(255)
            edit.set_edit_pos(0)
            edit.set_align_mode("right")
            self.widgets.append(edit)
            self.edit_widgets.append(edit)
            if i != 3:
                self.widgets.append(urwid.Text("."))

        self.widgets[-1].set_edit_text(0)

        self.columns = urwid.Columns(
                [("fixed", len(self.option_name) + 2, self.widgets[0]),
                 ("fixed", 4, self.widgets[1]),
                 ("fixed", 1, self.widgets[2]),
                 ("fixed", 4, self.widgets[3]),
                 ("fixed", 1, self.widgets[4]),
                 ("fixed", 4, self.widgets[5]),
                 ("fixed", 1, self.widgets[6]),
                 ("fixed", 4, self.widgets[7])],
                dividechars=1, min_width=1)

    def get_value(self):
        """Return user input.

        """
        values = [ i.get_edit_text() for i in self.edit_widgets ]
        values = [ str(value) for value in values ]
        return ".".join(values)

    def accept(self):
        """Return the top level widget.

        """
        return self.columns


@core.renders(command.CommandExecutor)
class UrwidCommandExecutorView(UrwidView):
    """Renders a Batch Processing class in a progressbar

    """
    def __init__(self, ce):

        ce.delegate = self
        self.ce = ce
        self.finished = False
        self.running = False

        # Widgets
        self.caption = urwid.Text("")
        self.progress_bar = urwid.ProgressBar('pb normal', 'pb complete')

    def configure(self):
        """Setup widgets

        """
        pass

    def get_value(self):
        """Return user input. We return None since this widget does not accept focus

        """
        return None

    def on_execution_started(self, queue):
        """Called before starting to process the input queue

        """
        self.running = True
        self.progress_bar.set_completion(1)
        os.write(UrwidMainWindow.pipe, "update")

    def on_execution_ended(self, queue):
        """Called when the input queue is done

        """
        self.running = False
        self.finished = True
        self.progress_bar.set_completion(100)
        os.write(UrwidMainWindow.pipe, "update")
        os.write(UrwidMainWindow.pipe, "close")

    def on_command_start(self, item):
        """Called before processing the item

        """
        self.caption.set_text(item.description)
        os.write(UrwidMainWindow.pipe, "update")

    def on_command_end(self, item, total, done):
        """Called after item is complete.

        """
        self.progress_bar.set_completion(done * self.progress_bar.done / total)
        os.write(UrwidMainWindow.pipe, "update")

    def accept(self):
        """Return the top level widget.

        """
        return urwid.Pile([self.caption, urwid.Divider(), self.progress_bar])


@core.renders(mountpoints.MountPoints)
class MountPointSelection(UrwidView):
    """Interface for declaring mountpoints.

    """
    DNF = "Don't format"
    DNU = "Not use"
    columns = "Device", "Mnt", "Fs"

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

    def configure(self):
        """Setup the elements composing the model view."""

        headers = urwid.Columns(
                [("fixed", 26, urwid.Text(self.columns[0])),
                    ("fixed", 15, urwid.Text(self.columns[1])),
                    ("fixed", 18, urwid.Text(self.columns[2]))])
        self.rows = [headers, urwid.Divider()]
        for d in self.mountpoints.partitions:
            row = self.make_row(d)
            self.rows.append(urwid.Columns(row, dividechars=1, min_width=1))

    def make_row(self, device):
        """Create a row for the columns widget """

        dev = urwid.Text(str(device))
        available_mountpoints = [self.DNU]
        available_mountpoints += [str(i) for i in
                self.mountpoints.available_mountpoints()]
        mountpoints = ComboBox(available_mountpoints)

        available_filesystems = [self.DNF]
        available_filesystems += [str(i) for i in
                self.mountpoints.filesystems]
        filesystems = ComboBox(available_filesystems)

        urwid.connect_signal(mountpoints, "change",
                self.make_set_default_fs_function(filesystems, "/", "ext3"),
                user_arg=device)
        urwid.connect_signal(mountpoints, "change",
                self.make_set_default_fs_function(filesystems, "swap", "swap"),
                user_arg=device)
        urwid.connect_signal(mountpoints, "change", self.mountpoint_selected,
                user_arg=device)
        urwid.connect_signal(filesystems, "change", self.filesystem_selected,
                user_arg=device)

        row = [("fixed", 25, dev), ("fixed", 14, mountpoints), ("fixed", 18,
            filesystems)]
        return row

    def make_set_default_fs_function(self, fs_combo, part, value):
        """ Create a function enclosing the combo widget for fs.
        The returned function will set the fs combo widget to a default value
        if the partition <part> is selected

        """
        def f(combo, item, selected, partition):
            if item.get_label() == part:
                for item in fs_combo.menu.items:
                    label = item.get_label()
                    if label == value:
                        break
                item.set_state(True)
                fs_combo.item_changed(item, True)
        return f

    def mountpoint_selected(self, combo, item, selected, partition):
        """A mountpoint has been selected in the mountpoints menu

        """
        mountpoint = item.get_label()
        if mountpoint == self.DNU:
            self.mountpoints.clear_mount(partition)
        else:
            self.mountpoints.set_mount(partition, mountpoint)

    def filesystem_selected(self, combo, item, selected, partition):
        """A mountpoint has been selected in the mountpoints menu

        """
        filesystem = item.get_label()
        if filesystem == self.DNF:
            self.mountpoints.clear_filesystem(partition)
        else:
            self.mountpoints.set_filesystem(partition, filesystem)

    def get_value(self):
        """Returns the text entered by the user."""
        return self.mountpoints.mapping

    def accept(self):
        """Returns the configured top level container widget."""
        return urwid.BoxAdapter(
                urwid.ListBox(urwid.SimpleFocusListWalker(self.rows)),
                len(self.mountpoints.partitions) + 2)