|
| 1 | +# whiptail.py - Use whiptail to display dialog boxes from shell scripts |
| 2 | +# Copyright (C) 2013 Marwan Alsabbagh |
| 3 | +# license: BSD, see LICENSE for more details. |
| 4 | + |
| 5 | +import sys |
| 6 | +import shlex |
| 7 | +from utile import save_args, flatten |
| 8 | +from subprocess import Popen, PIPE |
| 9 | +from collections import namedtuple |
| 10 | + |
| 11 | +Response = namedtuple('Response', 'returncode value') |
| 12 | + |
| 13 | + |
| 14 | +class Whiptail(object): |
| 15 | + def __init__(self, title='', backtitle='', height=10, width=50, auto_exit=True): |
| 16 | + save_args(self, vars()) |
| 17 | + |
| 18 | + def run(self, control, msg, extra=(), exit_on=(1, 255)): |
| 19 | + cmd = ['whiptail', '--title', self.title, '--backtitle', self.backtitle, |
| 20 | + '--' + control, msg, str(self.height), str(self.width)] + list(extra) |
| 21 | + p = Popen(cmd, stderr=PIPE) |
| 22 | + out, err = p.communicate() |
| 23 | + if self.auto_exit and p.returncode in exit_on: |
| 24 | + print 'User cancelled operation.' |
| 25 | + sys.exit(p.returncode) |
| 26 | + return Response(p.returncode, err) |
| 27 | + |
| 28 | + def prompt(self, msg, default='', password=False): |
| 29 | + control = 'passwordbox' if password else 'inputbox' |
| 30 | + return self.run(control, msg, [default]).value |
| 31 | + |
| 32 | + def confirm(self, msg, default='yes'): |
| 33 | + defaultno = '--defaultno' if default == 'no' else '' |
| 34 | + return self.run('yesno', msg, [defaultno], [255]).returncode == 0 |
| 35 | + |
| 36 | + def alert(self, msg): |
| 37 | + self.run('msgbox', msg) |
| 38 | + |
| 39 | + def view_file(self, path): |
| 40 | + self.run('textbox', path, ['--scrolltext']) |
| 41 | + |
| 42 | + def calc_height(self, msg): |
| 43 | + height_offset = 8 if msg else 7 |
| 44 | + return [str(self.height - height_offset)] |
| 45 | + |
| 46 | + def menu(self, msg='', items=(), prefix=' - '): |
| 47 | + if isinstance(items[0], basestring): |
| 48 | + items = [(i, '') for i in items] |
| 49 | + else: |
| 50 | + items = [(k, prefix + v) for k, v in items] |
| 51 | + extra = self.calc_height(msg) + flatten(items) |
| 52 | + return self.run('menu', msg, extra).value |
| 53 | + |
| 54 | + def showlist(self, control, msg, items, prefix): |
| 55 | + if isinstance(items[0], basestring): |
| 56 | + items = [(i, '', 'OFF') for i in items] |
| 57 | + else: |
| 58 | + items = [(k, prefix + v, s) for k, v, s in items] |
| 59 | + extra = self.calc_height(msg) + flatten(items) |
| 60 | + return shlex.split(self.run(control, msg, extra).value) |
| 61 | + |
| 62 | + def radiolist(self, msg='', items=(), prefix=' - '): |
| 63 | + return self.showlist('radiolist', msg, items, prefix) |
| 64 | + |
| 65 | + def checklist(self, msg='', items=(), prefix=' - '): |
| 66 | + return self.showlist('checklist', msg, items, prefix) |
0 commit comments