-
Notifications
You must be signed in to change notification settings - Fork 16
/
ister_gui.py
3452 lines (2971 loc) · 130 KB
/
ister_gui.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
#!/usr/bin/env python3
"""Clear Linux OS installation gui"""
#
# This file is part of ister.
#
# Copyright (C) 2015 Intel Corporation
#
# ister is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 3 of the License, or (at your
# option) any later version.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
# The array as default value is too handy here to worry about
# pylint: disable=dangerous-default-value
# Intended manipulation of internal state of the UI
# pylint: disable=protected-access
# global is handy here for now, but this could be fixed up
# pylint: disable=global-statement
# broad exceptions are fine
# pylint: disable=broad-except
# yeah this is pretty big
# pylint: disable=too-many-lines
# arguments differ is fine for the child classes
# pylint: disable=arguments-differ
import argparse
import crypt
import json
import logging
import os
import re
import subprocess
import threading
import sys
import pprint
import tempfile
import ipaddress
import signal
import time
import itertools
import netifaces
import pycurl
import urwid
import ister
PALETTE = [
('header', 'white', 'dark red', 'bold'),
('banner', 'white', 'dark gray'),
('bg', 'black', 'black'),
('p1', 'white', 'dark red'),
('p2', 'white', 'dark green'),
('p3', 'white', 'dark cyan'),
('p4', 'white', 'dark magenta'),
('reversed', 'light cyan', 'black'),
('I say', 'black,bold', 'dark gray', 'bold'),
('success', 'dark green', 'dark gray'),
('warn', 'dark red', 'dark gray'),
('button', 'light cyan', 'dark gray'),
('ex', 'light gray', 'dark gray'),
('popbg', 'white', 'dark blue')]
MIN_WIDTH = 80
MIN_HEIGHT = 24
MAX_WIDTH = 136
MAX_HEIGHT = 42
PERCENTAGE_W = 90
PERCENTAGE_H = 70
LINES = 0
COLUMNS = 0
def get_disk_info(disk):
"""Return dictionary with disk information"""
info = {'partitions': []}
cmd = ['/usr/bin/fdisk', '-l', disk]
try:
output = subprocess.check_output(cmd).decode('utf-8')
except:
return info
lines = output.split('\n')
expr = re.compile('^Device')
# discard header...
while lines:
match = expr.match(lines[0])
if match:
break
else:
lines.pop(0)
if lines:
lines.pop(0) # header - add this back manually
expr = re.compile(r'(\S+)\s+\S+\s+\S+\s+\S+\s+(\S+)\s+(\S.*)')
for line in lines:
match = expr.match(line)
if match:
info['partitions'].append({
'name': match.group(1),
'size': match.group(2),
'type': match.group(3),
'number': match.group(1)[len(disk):]
})
else:
break
return info
def get_part_devname(part):
"""
Return the parent device of the partition
If called on a device name, we could get a list of identical strings for
each partition the device contains:
$ lsblk -no pkname /dev/sda
# note the blank line here
sda
sda
sda
Just return the first one
"""
cmd = ['/usr/bin/lsblk', '-no', 'pkname', os.path.join('/dev', part)]
try:
# need to strip out leading blank line for the case that lsblk is
# called on a device name
output = subprocess.check_output(cmd).decode('utf-8').strip()
except subprocess.CalledProcessError:
return None
return output.splitlines()[0]
def get_list_of_disks():
""""
Queries for the available disks discarding the installer root disk
Parses lsblk output to find list of disks and to find where / is mounted.
The disk with a partition mounted to / is the installer disk and is
ignored. A list of available disks by name (sdb, sdc, vda, etc.) is
returned.
The lsblk command `lsblk -lo NAME,TYPE,MOUNTPOINT outputs the following
format.
NAME TYPE MOUNTPOINT
sda disk <--- disk, identified as current by sda3 mount point
sda1 part
sda2 part [SWAP]
sda3 part / <--- root partition
sdb disk <--- disk, valid target because no root partition mounted
sdb1 part
sdb2 part
For the above case this function would return ['sdb']
"""
disks = []
root_disk = ''
try:
output = subprocess.check_output([
'/usr/bin/lsblk', '-lo', 'NAME,TYPE,MOUNTPOINT']).decode('utf-8')
except:
return []
parts = output.split('\n')
for part in parts:
part = part.strip()
# This filter prevents the installer to stop on /dev/mmcblk0rpmb
# More on https://lwn.net/Articles/682276/
if part.startswith('mmc') and 'rpm' in part:
continue
if 'disk' in part:
disks.append(part.split()[0])
elif part.endswith('/'):
root_disk = part.split()[0]
# remove installer disk and return
return [dsk for dsk in disks if dsk not in root_disk]
def compute_mask(mask_ip):
"""Compute the /<mask> notation from mask IP"""
return sum([bin(int(x)).count("1") for x in mask_ip.split(".")])
def network_service_ready():
"""Check network status with increasing sleep times on each failure"""
for i in [.1, 1, 2, 4]:
try:
out = subprocess.check_output(['/usr/bin/systemctl',
'status',
'systemd-networkd',
'systemd-resolved'])
except subprocess.CalledProcessError:
return False
if out.decode('utf-8').count('Active: active (running)') == 2:
return True
time.sleep(i)
return False
def find_current_disk():
"""
Find the current disk so it can be skipped when searching for a Linux
root
"""
cmd = ['lsblk', '-l', '-o', 'NAME,MOUNTPOINT']
try:
output = subprocess.check_output(cmd).decode('utf-8')
except:
return ''
for line in output.split('\n'):
if '/' in line:
return line.split()[0]
return ''
def find_dns():
"""Find active DNS server by searching /etc/resolv.conf if it exists"""
content = ''
if os.path.exists('/etc/resolv.conf'):
with open('/etc/resolv.conf', 'r') as resolv:
content = resolv.readlines()
# just report the first nameserver
for line in content:
if 'nameserver' in line:
return line.split(' ')[1].strip()
def get_keyboards():
"""
Get list of keyboards from localectl to create dropdown selection
"""
try:
out = subprocess.check_output(['localectl',
'list-keymaps']).decode('utf-8')
except subprocess.CalledProcessError:
return ['us']
# 'us' is default and should be first in the list
kbs = ['us']
# remove trailing empty line with [:-1]
# extend by each keyboard in localectl list-keymaps output
kbs.extend(k for k in out.split('\n')[:-1] if k != 'us')
return kbs
def set_keyboard(keyboard):
"""
Set system keymapping to keyboard
"""
subprocess.call(['localectl', 'set-keymap', keyboard])
def restart_networkd_resolved():
"""Restart the network services then poll systemctl status output until
both are back up"""
# restart systemd-networkd and systemd-resolved
subprocess.call(['/usr/bin/systemctl', 'restart',
'systemd-networkd', 'systemd-resolved'])
if not network_service_ready():
raise Exception('Unable to restart network services')
def static_set():
""" Return a True if static has been configured on machine """
return os.path.exists('/etc/systemd/network/10-en-static.network')
def setup():
"""Initialization method for getting screen dimensions"""
global PERCENTAGE_W, PERCENTAGE_H, LINES, COLUMNS
rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = int(rows), int(columns)
if rows < MIN_HEIGHT:
PERCENTAGE_H = 100
if columns < MIN_WIDTH:
PERCENTAGE_W = 100
LINES = int(rows * PERCENTAGE_H / 100)
COLUMNS = int(columns * PERCENTAGE_W / 100)
if LINES > MAX_HEIGHT:
LINES = int(MAX_HEIGHT)
if COLUMNS > MAX_WIDTH:
COLUMNS = int(MAX_WIDTH)
def ister_wrapper(fn_name, *args):
"""Wrapper to dynamically call ister validations"""
# pylint: disable=no-member
try:
ister.__getattribute__(fn_name)(*args)
except Exception as exc:
return exc
return None
# pylint: disable=too-many-arguments
# six is reasonable since this function in turn calls three other functions
def ister_button(message, on_press=None, user_data=None,
align='left', left=0, right=0):
"""
Wrapper for ister_gui button creation since these are the steps nearly
always taken
"""
width = len(message) + 4
button = urwid.Button(message, on_press=on_press, user_data=user_data)
button = urwid.AttrMap(button, 'button', focus_map='reversed')
return urwid.Padding(button, align=align, width=width,
left=left, right=right)
def required_bundles(config):
"""
Determines the required bundles list from options set in the configuration
dictionary. Returns a list of bundle dictionaries containing 'name' and
'desc' fields.
"""
reqd_bundles = []
# configure core bundles (kernel, os-core, and os-core-update)
# detect virtualization technology to determine which kernel to require
try:
output = subprocess.check_output('systemd-detect-virt',
shell=True).decode('utf-8')
except Exception:
output = 'none'
if 'qemu' in output or 'kvm' in output:
kernel = {'name': 'kernel-kvm',
'desc': 'Required to run Clear Linux OS on kvm'}
else:
kernel = {'name': 'kernel-native',
'desc': 'Required to run Clear Linux OS on baremetal'}
reqd_bundles.extend([
{'name': 'os-core',
'desc': 'Minimal packages to have Clear Linux OS fully '
'functional'},
kernel,
{'name': 'os-core-update',
'desc': 'Required to update the system'}])
for partition in config['PartitionMountPoints']:
if 'encryption' in partition and partition['mount'] == '/':
reqd_bundles.extend([{
'name':'bootloader-extras',
'desc':'Required to boot encrypted root partition'}])
# configure dynamically required bundles (sysadmin-basic, telemetrics)
sysadmin_basic = {'name': 'sysadmin-basic',
'desc': 'Run common utilities useful for managing a '
'system (required when creating an admin user)'}
telemetrics = {'name': 'telemetrics',
'desc': 'Collects anonymous reports to improve system '
'stability (opted in)'}
# 'telemetrics' will exist in config['Bundles'] if the user opted in. This
# is the only way to select the telemetrics bundle, so make it required.
if 'telemetrics' in config['Bundles']:
reqd_bundles.append(telemetrics)
# if an administrative user is defined, that user will need sudo to operate
# the system.
if config.get('Users'):
reqd_bundles.append(sysadmin_basic)
return reqd_bundles
def search_swap(choices, config, mount_d):
"""
Search for the name of the swap partition to add to config
"""
for choice in choices:
is_swap = True
part = choice.split()[0]
for point in mount_d:
if part == mount_d[point]['part']:
is_swap = False
break
if is_swap:
try:
output = subprocess.check_output('fdisk -l | grep {0}'
.format(part),
shell=True).decode('utf-8')
except:
continue
if 'Linux swap' in output:
# first try to set using lsblk -no pkname part
disk = get_part_devname(part)
# if that fails, alert and fallback to old
# (unreliable) method
if not disk:
Alert('Partition error',
'Unable to detect device name for {}. '
'Falling back to path parsing. This method is '
'unreliable and may result in a failed install.'
.format(part)).do_alert()
disk = ''.join(x for x in part if not x.isdigit())
part = part[len(disk):]
# strip prefix if it exists. Not needed here and ister.py
# will add it back
prefix = part[0] if not part[0].isdigit() else ''
part = part.lstrip(prefix)
config['PartitionLayout'].append({
'disk': disk,
'partition': part,
'size': '1M',
'type': 'swap'})
config['FilesystemTypes'].append({
'disk': disk,
'partition': part,
'type': 'swap'})
def interface_list():
"""List all interface names"""
# pylint: disable=no-member
return [ifc for ifc in netifaces.interfaces() if ifc.startswith('e')]
def get_swupd_content_url():
"""
Find and return the content url that swupd determines
"""
cmd = ['swupd', 'mirror']
try:
output = subprocess.check_output(cmd).decode('utf-8')
except:
return None
for line in output.split('\n'):
if re.match('^Content URL:\s+', line):
return (re.split(r'\s+',line)[-1]).strip()
return None
def get_swupd_version_url():
"""
Find and return the version url that swupd determines
"""
cmd = ['swupd', 'mirror']
try:
output = subprocess.check_output(cmd).decode('utf-8')
except:
return None
for line in output.split('\n'):
if re.match('^Version URL:\s+', line):
return (re.split(r'\s+',line)[-1]).strip()
return None
class Alert(object):
"""Class to display alerts or confirm boxes"""
# pylint: disable=R0902
# pylint: disable=R0903
def __init__(self, title, msg, **kwargs):
self._frame = [('pack', urwid.Divider()),
('pack', urwid.Text(msg)),
('pack', urwid.Divider(u' ', 1))]
self._block = kwargs.get('block', True)
self._labels = kwargs.get('labels', [u'Ok'])
self._title = title
self.response = None
self.loop = None
if self._block:
self._add_nav_bar()
self._set_ui()
def _on_click(self, button):
self.response = button.label
raise urwid.ExitMainLoop()
def _add_nav_bar(self):
buttons = list()
for label in self._labels:
button = ister_button(label,
on_press=self._on_click,
align='center')
buttons.append(button)
# Add to frame
nav = NavBar(buttons)
# Nav Bar always starts with focus in
nav.have_focus = True
self._frame.append(('pack', nav))
self._frame.append(('pack', urwid.Divider()))
def _set_ui(self):
self._frame = FormController(self._frame)
self._frame = urwid.LineBox(self._frame, title=self._title)
self._frame = urwid.Filler(self._frame, valign='middle')
self._fgwin = urwid.Padding(self._frame, 'center', ('relative', 75))
self._ui = urwid.Overlay(self._fgwin,
urwid.AttrMap(urwid.SolidFill(u' '), 'bg'),
align='center',
width=('relative', PERCENTAGE_W),
valign='middle',
height=('relative', PERCENTAGE_H))
self._ui = urwid.AttrMap(self._ui, 'banner')
def do_alert(self):
"""It creates the loop, if synchronous it will block"""
self.loop = urwid.MainLoop(self._ui, palette=PALETTE)
if self._block:
self.loop.run()
else:
self.loop.start()
self.loop.draw_screen()
class AlertLoggerHandler(logging.StreamHandler):
def __init__(self, title):
self.title = title
self.text = ''
self.block = False
super().__init__()
def emit(self, record):
try:
self.block = hasattr(record, 'block')
self.text += '{0}{1}'.format(record.msg, self.terminator)
Alert(self.title, self.text, block=self.block).do_alert()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
class AlertPass(object):
"""Class to display alerts or confirm boxes"""
# pylint: disable=R0902
# pylint: disable=R0903
def __init__(self, title, msg, **kwargs):
self.passphrase = urwid.Edit(msg, mask='*')
self._frame = [('pack', urwid.Divider()),
('pack', self.passphrase),
('pack', urwid.Divider(u' ', 1))]
self._block = kwargs.get('block', True)
self._labels = kwargs.get('labels', [u'Ok'])
self._title = title
self.response = None
self.loop = None
if self._block:
self._add_nav_bar()
self._set_ui()
def _on_click(self, button):
self.response = button.label
raise urwid.ExitMainLoop()
def _add_nav_bar(self):
buttons = list()
for label in self._labels:
button = ister_button(label,
on_press=self._on_click,
align='center')
buttons.append(button)
# Add to frame
nav = NavBar(buttons)
# Nav Bar always starts with focus in
nav.have_focus = True
self._frame.append(('pack', nav))
self._frame.append(('pack', urwid.Divider()))
def _set_ui(self):
self._frame = FormController(self._frame)
self._frame = urwid.LineBox(self._frame, title=self._title)
self._frame = urwid.Filler(self._frame, valign='middle')
self._fgwin = urwid.Padding(self._frame, 'center', ('relative', 75))
self._ui = urwid.Overlay(self._fgwin,
urwid.AttrMap(urwid.SolidFill(u' '), 'bg'),
align='center',
width=('relative', PERCENTAGE_W),
valign='middle',
height=('relative', PERCENTAGE_H))
self._ui = urwid.AttrMap(self._ui, 'banner')
def do_alert(self):
"""It creates the loop, if synchronous it will block"""
self.loop = urwid.MainLoop(self._ui, palette=PALETTE)
if self._block:
self.loop.run()
else:
self.loop.start()
self.loop.draw_screen()
return self.passphrase.get_edit_text()
class Terminal(object):
"""UI object that enables the installer to run external commands"""
def __init__(self, cmd):
self.term = urwid.Terminal(cmd)
self.init_widget()
def init_widget(self):
"""Initializes the minimal widgets to run"""
mainframe = urwid.LineBox(
urwid.Pile([('weight', 70, self.term)]))
urwid.connect_signal(self.term, 'closed', self.quit)
loop = urwid.MainLoop(
mainframe,
handle_mouse=False,
unhandled_input=lambda: None)
self.term.main_loop = loop
self.term.keygrab = True
@staticmethod
def quit(*args, **kwargs):
"""Breaks the loop to continue"""
del args, kwargs
raise urwid.ExitMainLoop()
def main_loop(self):
"""Enters the loop to grab focus on the terminal UI"""
self.term.main_loop.run()
class PopUpDialog(urwid.WidgetWrap):
"""Pop up dialog box"""
signals = ['close']
def __init__(self, popup_msg, button_text):
close_button = ister_button(button_text, on_press=self._emit, left=2)
pile = urwid.Pile([urwid.Text(popup_msg), close_button])
fill = urwid.Filler(pile)
super(PopUpDialog, self).__init__(urwid.AttrWrap(fill, 'popbg'))
def _emit(self, _):
"""Override urwid.WidgetWrap emit to always close"""
super(PopUpDialog, self)._emit('close')
class PopUpWidget(urwid.PopUpLauncher):
"""Launches a pop up dialog box"""
def __init__(self, button_text, popup_msg, close_button_text):
super(PopUpWidget, self).__init__(
ister_button(button_text, on_press=self.open_pop_up))
self.popup_msg = popup_msg
self.close_button_text = close_button_text
def create_pop_up(self):
"""Initiate a pop up menu"""
pop_up = PopUpDialog(self.popup_msg, self.close_button_text)
urwid.connect_signal(pop_up, 'close',
lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
"""Override urwid.PopUpLauncher.get_pop_up_parameters to set our own"""
return {'left': 0, 'top': 1,
'overlay_width': 32,
'overlay_height': len(interface_list()) + 3}
def open_pop_up(self, _):
"""
Override urwid.PopUpLauncher.open_pop_up so we can pass it to
ister_button
"""
super(PopUpWidget, self).open_pop_up()
class ButtonMenu(object):
"""Assemble the button menu - ultimately store it in self._ui"""
# pylint: disable=R0903
def __init__(self, title, choices, selection):
self._response = '' # The choice made by the user is stored here.
self.choices = choices
self.selection = selection
self.construct(title)
def construct(self, title):
"""Construct the Button menu widgets"""
# These will sit above the list box
frame_contents = [('pack', urwid.Divider()),
('pack', urwid.Text(title)),
('pack', urwid.Divider())]
self._menu = []
for choice in self.choices:
label = choice if self.selection != choice else '* ' + choice
button = ister_button(label,
on_press=self._item_chosen,
user_data=choice)
self._menu.append(button)
self._lb = NavListBox(urwid.SimpleFocusListWalker(self._menu), self)
frame_contents.append(self._lb)
frame_contents = urwid.Pile(frame_contents)
self._fgwin = urwid.Padding(frame_contents, left=2, right=2)
self._ui = urwid.Overlay(self._fgwin,
urwid.AttrMap(urwid.SolidFill(u' '), 'bg'),
align='center',
width=('relative', PERCENTAGE_W),
valign='middle',
height=('relative', PERCENTAGE_H))
self._ui = urwid.AttrMap(self._ui, 'banner')
# This callback is registered with urwid.MainLoop and gives us the
# opportunity to intercept keystrokes and handle things like tabs.
# In theory the callback for each keystroke should be function
# fragment or class method but I just handled them in-line here.
# Unhandled input is returned back to MainLoop for default handlers to
# deal with. Another way to effect this would be to subclass the
# ListBox class and override the keypress method.
def _input_filter(self, keys, raw):
# pylint: disable=W0212
del raw
i = self._lb.focus_position
max_pos = len(self._menu)
if 'tab' in keys or 'down' in keys:
self._lb.focus_position = (i + 1) % max_pos
self._lb._invalidate()
else:
return keys
def _item_chosen(self, button, _):
""" Callback trigged by button activation """
del button
self._response = 'Next'
raise urwid.ExitMainLoop()
def run_ui(self):
""" Runs the button menu and returns the choice made by the user. """
main_loop = urwid.MainLoop(self._ui, palette=PALETTE,
input_filter=self._input_filter)
main_loop.run()
return self._response
class NavBar(urwid.Columns):
""" Builds and manages a nav-bar of buttons """
# pylint: disable=R0903
def __init__(self, buttons):
self.have_focus = False
super(NavBar, self).__init__(buttons, dividechars=5)
def keypress(self, size, key):
""" Get the key that was pressed """
# self.focus_position defined in parent
# pylint: disable=E0203
# pylint: disable=W0201
max_cols = len(self.contents)
pos = self.focus_position
# we will handle the following keys ourselves, don't call super
if key not in ['tab', 'down', 'up', 'shift tab']:
key = super(NavBar, self).keypress(size, key)
# up and shift tab should behave like right in the navbar (so that the
# Next option is selected first)
elif key in ['up', 'shift tab']:
key = super(NavBar, self).keypress(size, 'right')
if key in ['tab', 'down']:
if self.have_focus is False:
self.have_focus = True
# first focus should be the Next button in the last column if
# it is present
self.focus_position = max_cols - 1
elif pos > 0:
self.focus_position = pos - 1
elif pos == 0:
self.have_focus = False
return key
else:
return key
class FormBody(urwid.ListBox):
""" Adds a list of widgets to a list box.
Includes navigation management """
# pylint: disable=R0903
def __init__(self, fields):
self._lost_focus = False
self._num_fields = len(fields)
self._body = urwid.SimpleFocusListWalker(fields)
super(FormBody, self).__init__(self._body)
def keypress(self, size, key):
"""Manages key press event"""
# self.focus_position defined in parent
# pylint: disable=E0203
# pylint: disable=W0201
# pylint: disable=R0912
# we will handle the following keys ourselves, don't call super
if key not in ['tab', 'down', 'shift tab']:
key = super(FormBody, self).keypress(size, key)
# shift tab should behave like the up arrow
elif key == 'shift tab':
key = super(FormBody, self).keypress(size, 'up')
pos = self.focus_position
if key in ['tab', 'enter', 'down']:
if self._lost_focus:
self._lost_focus = False
self.focus_position = 0
pos = 0
while pos <= (self._num_fields - 1):
if self._body[pos].selectable():
self.focus_position = pos
self._invalidate()
break
else:
pos += 1
if pos > (self._num_fields - 1):
self._lost_focus = True
return 'tab'
elif pos < (self._num_fields - 1):
pos += 1
while pos <= (self._num_fields - 1):
if self._body[pos].selectable():
self.focus_position = pos
self._invalidate()
break
else:
pos += 1
if pos > (self._num_fields - 1):
self._lost_focus = True
return 'tab'
elif pos >= (self._num_fields - 1):
self._lost_focus = True
return 'tab'
else:
return key
class FormController(urwid.Pile):
""" Manages Focus navigation between a FormBody and NavBar """
# pylint: disable=R0903
def keypress(self, size, key):
"""Manages keypress event"""
# self.focus_position defined in parent
# pylint: disable=E0203
# pylint: disable=W0201
key = super(FormController, self).keypress(size, key)
pos = self.focus_position
if key in ['tab', 'down']:
start = self.focus_position
# Skip the header
while True:
pos = (pos + 1) % len(self.contents)
self.focus_position = pos
if self.focus.selectable():
break
# guard against infinite spinning
if pos == start:
break
# Send the key into the newly focused widget
self.focus.keypress(size, key)
else:
return key
class SimpleForm(object):
""" Creates a Form with a Header, FormBody (which contains form fields)
And a NavBar, which contains buttons for previous and next.
Prompt for input for one or more fields """
# pylint: disable=R0902
# pylint: disable=R0903
def __init__(self, title, fields, buttons=["Previous", "Next"],
align_title='left'):
self._title = title
self._questions = fields
self._answers = dict()
self._clicked = ''
self._next_id = 0
self.button_labels = buttons
self._nav_bar_has_focus = True
self.nav = None
# Build the forum
self._frame = [('pack', urwid.Divider()),
('pack', urwid.Text(title, align=align_title)),
('pack', urwid.Divider())]
self._form_body = FormBody(fields)
self._frame.append(self._form_body)
for field in fields:
if field.selectable():
self._nav_bar_has_focus = False
# This helps push the default focus to the NavBar
if self._nav_bar_has_focus:
self._form_body._selectable = False
# Add the navigation buttons - for the installer common to
# all forms. <previous> <next> """
self._add_nav_bar()
self._set_ui()
def _on_click(self, button):
self._clicked = button.label
raise urwid.ExitMainLoop()
def _add_nav_bar(self):
buttons = []
for label in self.button_labels:
button = ister_button(label,
on_press=self._on_click,
align='center')
buttons.append(button)
# Add to frame
self.nav = NavBar(buttons)
self.nav.have_focus = self._nav_bar_has_focus
self._frame.append(('pack', self.nav))
self._frame.append(('pack', urwid.Divider()))
def _set_ui(self):
self._frame = FormController(self._frame)
self._fgwin = urwid.Padding(self._frame, left=2, right=2)
self._ui = urwid.Overlay(self._fgwin,
urwid.AttrMap(urwid.SolidFill(u' '), 'bg'),
align='center',
width=('relative', PERCENTAGE_W),
valign='middle',
height=('relative', PERCENTAGE_H))
self._ui = urwid.AttrMap(self._ui, 'banner')
def do_form(self, pop_ups=False):
"""Creates the loop and enter to it, to focus the UI"""
main_loop = urwid.MainLoop(self._ui, palette=PALETTE, pop_ups=pop_ups)
main_loop.run()
return self._clicked
class HostnameEdit(urwid.Edit):
"""Widget to ask for hostname input"""
# pylint: disable=R0903
def keypress(self, size, key):
"""Manages key press event to validate input"""
first = re.compile('[a-zA-Z0-9]')
rest = re.compile('[a-zA-Z0-9-.]')
# Only allow valid hostnames. Only letters, numbers,
# '.' and '-' allowed. Can't start with '.' or '-', Max length 63 """
i = len(self.get_edit_text())
if i == 0:
match = first.match(key)
if match:
key = super(HostnameEdit, self).keypress(size, key)
elif i < 63:
match = rest.match(key)
if match:
key = super(HostnameEdit, self).keypress(size, key)
elif key == 'backspace':
key = super(HostnameEdit, self).keypress(size, key)
return key
class UsernameEdit(urwid.Edit):
"""Widget to ask for username input"""
# pylint: disable=R0903
def keypress(self, size, key):
"""Manages key press event to validate input"""
first = re.compile(r'[a-z]')
rest = re.compile(r'[a-z0-9\-_]')
# Only allow valid usernamces. Only lower letters, numbers,
# and '-' allowed. Can't start with '-', Max length 63
i = len(self.get_edit_text())
if i == 0:
match = first.match(key)
if match:
key = super(UsernameEdit, self).keypress(size, key)
elif i < 63:
match = rest.match(key)
if match:
key = super(UsernameEdit, self).keypress(size, key)
return key
class IpEdit(urwid.Edit):
"""Widget to ask for ip input"""
# pylint: disable=R0903
def keypress(self, size, key):
"""Manages key press event to validate input"""