/
demo.py
executable file
·1665 lines (1389 loc) · 68.5 KB
/
demo.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
# -*- coding: utf-8 -*-
# demo.py --- Demonstration program and cheap test suite for pythondialog
#
# Copyright (C) 2002-2010, 2013, 2014, 2015 Florent Rougon
# Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
#
# This program is in the public domain.
"""Demonstration program for pythondialog.
This is a program demonstrating most of the possibilities offered by
the pythondialog module (which is itself a Python interface to the
well-known dialog utility, or any other program compatible with
dialog).
Executive summary
-----------------
If you are looking for a very simple example of pythondialog usage,
short and straightforward, please refer to simple_example.py. The
file you are now reading serves more as a demonstration of what can
be done with pythondialog and as a cheap test suite than as a first
time tutorial. However, it can also be used to learn how to invoke
the various widgets. The following paragraphs explain what you should
keep in mind if you read it for this purpose.
Most of the code in the MyApp class (which defines the actual
contents of the demo) relies on a class called MyDialog implemented
here that:
1. wraps all widget-producing calls in a way that automatically
spawns a "confirm quit" dialog box if the user presses the
Escape key or chooses the Cancel button, and then redisplays the
original widget if the user doesn't actually want to quit;
2. provides a few additional dialog-related methods and convenience
wrappers.
The handling in (1) is completely automatic, implemented with
MyDialog.__getattr__() returning decorated versions of the
widget-producing methods of dialog.Dialog. Therefore, most of the
demo can be read as if the module-level 'd' attribute were a
dialog.Dialog instance whereas it is actually a MyDialog instance.
The only meaningful difference is that MyDialog.<widget>() will never
return a CANCEL or ESC code (attributes of 'd', or more generally of
dialog.Dialog). The reason is that these return codes are
automatically handled by the MyDialog.__getattr__() machinery to
display the "confirm quit" dialog box.
In some cases (e.g., fselect_demo()), I wanted the "Cancel" button to
perform a specific action instead of spawning the "confirm quit"
dialog box. To achieve this, the widget is invoked using
dialog.Dialog.<widget> instead of MyDialog.<widget>, and the return
code is handled in a semi-manual way. A prominent feature that needs
such special-casing is the yesno widget, because the "No" button
corresponds to the CANCEL exit code, which in general must not be
interpreted as an attempt to quit the program!
To sum it up, you can read most of the code in the MyApp class (which
defines the actual contents of the demo) as if 'd' were a
dialog.Dialog instance. Just keep in mind that there is a little
magic behind the scenes that automatically handles the CANCEL and ESC
Dialog exit codes, which wouldn't be the case if 'd' were a
dialog.Dialog instance. For a first introduction to pythondialog with
simple stuff and absolutely no magic, please have a look at
simple_example.py.
"""
import sys, os, locale, stat, time, getopt, subprocess, traceback, textwrap
import pprint
import dialog
from dialog import DialogBackendVersion
progname = os.path.basename(sys.argv[0])
progversion = "0.9"
version_blurb = """Demonstration program and cheap test suite for pythondialog.
Copyright (C) 2002-2010, 2013, 2014 Florent Rougon
Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."""
default_debug_filename = "pythondialog.debug"
usage = """Usage: {progname} [option ...]
Demonstration program and cheap test suite for pythondialog.
Options:
-t, --test-suite test all widgets; implies --fast
-f, --fast fast mode (e.g., makes the gauge demo run faster)
--debug enable logging of all dialog command lines
--debug-file=FILE where to write debug information (default:
{debug_file} in the current directory)
--help display this message and exit
--version output version information and exit""".format(
progname=progname, debug_file=default_debug_filename)
# Global parameters
params = {}
# We'll use a module-level attribute 'd' ("global") to store the MyDialog
# instance that is used throughout the demo. This object could alternatively be
# passed to the MyApp constructor and stored there as a class or instance
# attribute. However, for the sake of readability, we'll simply use a global
# (d.msgbox(...) versus self.d.msgbox(...), etc.).
d = None
tw = textwrap.TextWrapper(width=78, break_long_words=False,
break_on_hyphens=True)
from textwrap import dedent
try:
from textwrap import indent
except ImportError:
def indent(text, prefix, predicate=None):
l = []
for line in text.splitlines(True):
if (callable(predicate) and predicate(line)) \
or (not callable(predicate) and predicate) \
or (predicate is None and line.strip()):
line = prefix + line
l.append(line)
return ''.join(l)
class MyDialog:
"""Wrapper class for dialog.Dialog.
This class behaves similarly to dialog.Dialog. The differences
are that:
1. MyDialog wraps all widget-producing methods in a way that
automatically spawns a "confirm quit" dialog box if the user
presses the Escape key or chooses the Cancel button, and
then redisplays the original widget if the user doesn't
actually want to quit.
2. MyDialog provides a few additional dialog-related methods
and convenience wrappers.
Please refer to the module docstring and to the particular
methods for more details.
"""
def __init__(self, Dialog_instance):
self.dlg = Dialog_instance
def check_exit_request(self, code, ignore_Cancel=False):
if code == self.CANCEL and ignore_Cancel:
# Ignore the Cancel button, i.e., don't interpret it as an exit
# request; instead, let the caller handle CANCEL himself.
return True
if code in (self.CANCEL, self.ESC):
button_name = { self.CANCEL: "Cancel",
self.ESC: "Escape" }
msg = "You pressed {0} in the last dialog box. Do you want " \
"to exit this demo?".format(button_name[code])
# 'self.dlg' instead of 'self' here, because we want to use the
# original yesno() method from the Dialog class instead of the
# decorated method returned by self.__getattr__().
if self.dlg.yesno(msg) == self.OK:
sys.exit(0)
else: # "No" button chosen, or ESC pressed
return False # in the "confirm quit" dialog
else:
return True
def widget_loop(self, method):
"""Decorator to handle eventual exit requests from a Dialog widget.
method -- a dialog.Dialog method that returns either a Dialog
exit code, or a sequence whose first element is a
Dialog exit code (cf. the docstring of the Dialog
class in dialog.py)
Return a wrapper function that behaves exactly like 'method',
except for the following point:
If the Dialog exit code obtained from 'method' is CANCEL or
ESC (attributes of dialog.Dialog), a "confirm quit" dialog
is spawned; depending on the user choice, either the
program exits or 'method' is called again, with the same
arguments and same handling of the exit status. In other
words, the wrapper function builds a loop around 'method'.
The above condition on 'method' is satisfied for all
dialog.Dialog widget-producing methods. More formally, these
are the methods defined with the @widget decorator in
dialog.py, i.e., that have an "is_widget" attribute set to
True.
"""
# One might want to use @functools.wraps here, but since the wrapper
# function is very likely to be used only once and then
# garbage-collected, this would uselessly add a little overhead inside
# __getattr__(), where widget_loop() is called.
def wrapper(*args, **kwargs):
while True:
res = method(*args, **kwargs)
if hasattr(method, "retval_is_code") \
and getattr(method, "retval_is_code"):
code = res
else:
code = res[0]
if self.check_exit_request(code):
break
return res
return wrapper
def __getattr__(self, name):
# This is where the "magic" of this class originates from.
# Please refer to the module and self.widget_loop()
# docstrings if you want to understand the why and the how.
obj = getattr(self.dlg, name)
if hasattr(obj, "is_widget") and getattr(obj, "is_widget"):
return self.widget_loop(obj)
else:
return obj
def clear_screen(self):
# This program comes with ncurses
program = "clear"
try:
p = subprocess.Popen([program], shell=False, stdout=None,
stderr=None, close_fds=True)
retcode = p.wait()
except os.error as e:
self.msgbox("Unable to execute program '%s': %s." % (program,
e.strerror),
title="Error")
return False
if retcode > 0:
msg = "Program %s returned exit status %d." % (program, retcode)
elif retcode < 0:
msg = "Program %s was terminated by signal %d." % (program, -retcode)
else:
return True
self.msgbox(msg)
return False
def _Yesno(self, *args, **kwargs):
"""Convenience wrapper around dialog.Dialog.yesno().
Return the same exit code as would return
dialog.Dialog.yesno(), except for ESC which is handled as in
the rest of the demo, i.e. make it spawn the "confirm quit"
dialog.
"""
# self.yesno() automatically spawns the "confirm quit" dialog if ESC or
# the "No" button is pressed, because of self.__getattr__(). Therefore,
# we have to use self.dlg.yesno() here and call
# self.check_exit_request() manually.
while True:
code = self.dlg.yesno(*args, **kwargs)
# If code == self.CANCEL, it means the "No" button was chosen;
# don't interpret this as a wish to quit the program!
if self.check_exit_request(code, ignore_Cancel=True):
break
return code
def Yesno(self, *args, **kwargs):
"""Convenience wrapper around dialog.Dialog.yesno().
Return True if "Yes" was chosen, False if "No" was chosen,
and handle ESC as in the rest of the demo, i.e. make it spawn
the "confirm quit" dialog.
"""
return self._Yesno(*args, **kwargs) == self.dlg.OK
def Yesnohelp(self, *args, **kwargs):
"""Convenience wrapper around dialog.Dialog.yesno().
Return "yes", "no", "extra" or "help" depending on the button
that was pressed to close the dialog. ESC is handled as in
the rest of the demo, i.e. it spawns the "confirm quit"
dialog.
"""
kwargs["help_button"] = True
code = self._Yesno(*args, **kwargs)
d = { self.dlg.OK: "yes",
self.dlg.CANCEL: "no",
self.dlg.EXTRA: "extra",
self.dlg.HELP: "help" }
return d[code]
# Dummy context manager to make sure the debug file is closed on exit, be it
# normal or abnormal, and to avoid having two code paths, one for normal mode
# and one for debug mode.
class DummyContextManager:
def __enter__(self):
return self
def __exit__(self, *exc):
return False
class MyApp:
def __init__(self):
# The MyDialog instance 'd' could be passed via the constructor and
# stored here as a class or instance attribute. However, for the sake
# of readability, we'll simply use a module-level attribute ("global")
# (d.msgbox(...) versus self.d.msgbox(...), etc.).
global d
# If you want to use Xdialog (pathnames are also OK for the 'dialog'
# argument), you can use:
# dialog.Dialog(dialog="Xdialog", compat="Xdialog")
self.Dialog_instance = dialog.Dialog(dialog="dialog")
# See the module docstring at the top of the file to understand the
# purpose of MyDialog.
d = MyDialog(self.Dialog_instance)
backtitle = "pythondialog demo"
d.set_background_title(backtitle)
# These variables take the background title into account
self.max_lines, self.max_cols = d.maxsize(backtitle=backtitle)
self.demo_context = self.setup_debug()
# Warn if the terminal is smaller than this size
self.min_rows, self.min_cols = 24, 80
self.term_rows, self.term_cols, self.backend_version = \
self.get_term_size_and_backend_version()
def setup_debug(self):
if params["debug"]:
debug_file = open(params["debug_filename"], "w")
d.setup_debug(True, file=debug_file)
return debug_file
else:
return DummyContextManager()
def get_term_size_and_backend_version(self):
# Avoid running '<backend> --print-version' every time we need the
# version
backend_version = d.cached_backend_version
if not backend_version:
print(tw.fill(
"Unable to retrieve the version of the dialog-like backend. "
"Not running cdialog?") + "\nPress Enter to continue.",
file=sys.stderr)
input()
term_rows, term_cols = d.maxsize(use_persistent_args=False)
if term_rows < self.min_rows or term_cols < self.min_cols:
print(tw.fill(dedent("""\
Your terminal has less than {0} rows or less than {1} columns;
you may experience problems with the demo. You have been warned."""
.format(self.min_rows, self.min_cols)))
+ "\nPress Enter to continue.")
input()
return (term_rows, term_cols, backend_version)
def run(self):
with self.demo_context:
if params["testsuite_mode"]:
# Show the additional widgets before the "normal demo", so that
# I can test new widgets quickly and simply hit Ctrl-C once
# they've been shown.
self.additional_widgets()
# "Normal" demo
self.demo()
def demo(self):
d.msgbox("""\
Hello, and welcome to the pythondialog {pydlg_version} demonstration program.
You can scroll through this dialog box with the Page Up and Page Down keys. \
Please note that some of the dialogs will not work, and cause the demo to \
stop, if your terminal is too small. The recommended size is (at least) \
{min_rows} rows by {min_cols} columns.
This script is being run by a Python interpreter identified as follows:
{py_version}
The dialog-like program displaying this message box reports version \
{backend_version} and a terminal size of {rows} rows by {cols} columns."""
.format(
pydlg_version=dialog.__version__,
backend_version=self.backend_version,
py_version=indent(sys.version, " "),
rows=self.term_rows, cols=self.term_cols,
min_rows=self.min_rows, min_cols=self.min_cols),
width=60, height=17)
self.progressbox_demo_with_file_descriptor()
# First dialog version where the programbox widget works fine
if self.dialog_version_check("1.2-20140112"):
self.programbox_demo()
self.infobox_demo()
self.gauge_demo()
answer = self.yesno_demo(with_help=True)
self.msgbox_demo(answer)
self.textbox_demo()
name = self.inputbox_demo_with_help()
size, weight, city, state, country, last_will1, last_will2, \
last_will3, last_will4, secret_code = self.mixedform_demo()
self.form_demo_with_help()
favorite_day = self.menu_demo(name, city, state, country, size, weight,
secret_code, last_will1, last_will2,
last_will3, last_will4)
if self.dialog_version_check("1.2-20130902",
"the menu demo with help facilities",
explain=True):
self.menu_demo_with_help()
toppings = self.checklist_demo()
if self.dialog_version_check("1.2-20130902",
"the checklist demo with help facilities",
explain=True):
self.checklist_demo_with_help()
sandwich = self.radiolist_demo()
if self.dialog_version_check("1.2", "the rangebox demo", explain=True):
nb_engineers = self.rangebox_demo()
else:
nb_engineers = None
if self.dialog_version_check("1.2", "the buildlist demo", explain=True):
desert_island_stuff = self.buildlist_demo()
else:
desert_island_stuff = None
if self.dialog_version_check("1.2-20130902",
"the buildlist demo with help facilities",
explain=True):
self.buildlist_demo_with_help()
date = self.calendar_demo_with_help()
time_ = self.timebox_demo()
password = self.passwordbox_demo()
self.scrollbox_demo(name, favorite_day, toppings, sandwich,
nb_engineers, desert_island_stuff, date, time_,
password)
if self.dialog_version_check("1.2", "the treeview demo", explain=True):
if self.dialog_version_check("1.2-20130902"):
self.treeview_demo_with_help()
else:
self.treeview_demo()
self.mixedgauge_demo()
self.editbox_demo("/etc/passwd")
self.inputmenu_demo()
d.msgbox("""\
Haha. You thought it was over. Wrong. Even more fun is to come!
Now, please select a file you would like to see growing (or not...).""",
width=75)
# Looks nicer if the screen is not completely filled by the widget,
# hence the -1.
self.tailbox_demo(height=self.max_lines-1,
width=self.max_cols)
directory = self.dselect_demo()
timeout = 2 if params["fast_mode"] else 20
self.pause_demo(timeout)
d.clear_screen()
if not params["fast_mode"]:
# Rest assured, this is not necessary in any way: it is only a
# psychological trick to try to give the impression of a reboot
# (cf. pause_demo(); would be even nicer with a "visual bell")...
time.sleep(1)
def additional_widgets(self):
# Requires a careful choice of the file to be of any interest
self.progressbox_demo_with_filepath()
# This can be confusing without any pause if the user specified a
# regular file.
time.sleep(1 if params["fast_mode"] else 2)
# programbox_demo is fine right after
# progressbox_demo_with_file_descriptor in demo(), but there was a
# little bug in dialog that made the first two lines disappear too
# early. This bug has been fixed in version 1.2-20140112, therefore
# we'll run the programbox_demo as part of the main demo if the dialog
# version is >= than this one, otherwise we'll keep it here.
if self.dialog_version_check("1.1", "the programbox demo", explain=True):
# First dialog version where the programbox widget works fine
if not self.dialog_version_check("1.2-20140112"):
self.programbox_demo()
# Almost identical to mixedform (mixedform being more powerful). Also,
# there is now form_demo_with_help() which uses the form widget.
self.form_demo()
# Almost identical to passwordbox
self.passwordform_demo()
def dialog_version_check(self, version_string, feature="", *, start="",
explain=False):
if d.compat != "dialog":
# non-dialog implementations are not affected by
# 'dialog_version_check'.
return True
minimum_version = DialogBackendVersion.fromstring(version_string)
res = (d.cached_backend_version >= minimum_version)
if explain and not res:
self.too_old_dialog_version(feature=feature, start=start,
min=version_string)
return res
def too_old_dialog_version(self, feature="", *, start="", min=None):
assert (feature and not start) or (not feature and start), \
(feature, start)
if not start:
start = "Skipping {0},".format(feature)
d.msgbox(
"{start} because it requires dialog {min} or later; "
"however, it appears that you are using version {used}.".format(
start=start, min=min, used=d.cached_backend_version),
width=60, height=9, title="Demo skipped")
def progressbox_demo_with_filepath(self):
widget = "progressbox"
# First, ask the user for a file (possibly FIFO)
d.msgbox(self.FIFO_HELP(widget), width=72, height=20)
path = self.fselect_demo(widget, allow_FIFOs=True,
title="Please choose a file to be shown as "
"with 'tail -f'")
if path is None:
# User chose to abort
return
else:
d.progressbox(file_path=path,
text="You can put some header text here",
title="Progressbox example with a file path")
def progressboxoid(self, widget, func_name, text, **kwargs):
# Since this is just a demo, I will not try to catch os.error exceptions
# in this function, for the sake of readability.
read_fd, write_fd = os.pipe()
child_pid = os.fork()
if child_pid == 0:
try:
# We are in the child process. We MUST NOT raise any exception.
# No need for this one in the child process
os.close(read_fd)
# Python file objects are easier to use than file descriptors.
# For a start, you don't have to check the number of bytes
# actually written every time...
# "buffering = 1" means wfile is going to be line-buffered
with os.fdopen(write_fd, mode="w", buffering=1) as wfile:
for line in text.split('\n'):
wfile.write(line + '\n')
time.sleep(0.02 if params["fast_mode"] else 1.2)
os._exit(0)
except:
os._exit(127)
# We are in the father process. No need for write_fd anymore.
os.close(write_fd)
# Call d.progressbox() if widget == "progressbox"
# d.programbox() if widget == "programbox"
# etc.
getattr(d, widget)(
fd=read_fd,
title="{0} example with a file descriptor".format(widget),
**kwargs)
# Now that the progressbox is over (second child process, running the
# dialog-like program), we can wait() for the first child process.
# Otherwise, we could have a deadlock in case the pipe gets full, since
# dialog wouldn't be reading it.
exit_info = os.waitpid(child_pid, 0)[1]
if os.WIFEXITED(exit_info):
exit_code = os.WEXITSTATUS(exit_info)
elif os.WIFSIGNALED(exit_info):
d.msgbox("%s(): first child process terminated by signal %d" %
(func_name, os.WTERMSIG(exit_info)))
else:
assert False, "How the hell did we manage to get here?"
if exit_code != 0:
d.msgbox("%s(): first child process ended with exit status %d"
% (func_name, exit_code))
def progressbox_demo_with_file_descriptor(self):
func_name = "progressbox_demo_with_file_descriptor"
text = """\
A long time ago in a galaxy far,
far away...
A NEW HOPE
It was a period of intense
sucking. Graphical toolkits for
Python were all nice and clean,
but they were, well, graphical.
And as every one knows, REAL
PROGRAMMERS ALWAYS WORK ON VT-100
TERMINALS. In text mode.
Besides, those graphical toolkits
were usually too complex for
simple programs, so most FLOSS
geeks ended up writing
command-line tools except when
they really needed the full power
of mainstream graphical toolkits,
such as Qt, GTK+ and wxWidgets.
But... thanks to people like
Thomas E. Dickey, there are now
at our disposal several free
software command-line programs,
such as dialog, that allow easy
building of graphically-oriented
interfaces in text-mode
terminals. These are good for
tasks where line-oriented
interfaces are not well suited,
as well as for the increasingly
common type who runs away as soon
as he sees something remotely
resembling a command line.
But this is not for Python! I want
my poney!
Seeing this unacceptable
situation, Robb Shecter had the
idea, back in the olden days of
Y2K (when the world was supposed
to suddenly collapse, remember?),
to wrap a dialog interface into a
Python module called dialog.py.
pythondialog was born. Florent
Rougon, who was looking for
something like that in 2002,
found the idea rather cool and
improved the module during the
following years...""" + 15*'\n'
return self.progressboxoid("progressbox", func_name, text)
def programbox_demo(self):
func_name = "programbox_demo"
text = """\
The 'progressbox' widget
has a little brother
called 'programbox'
that displays text
read from a pipe
and only adds an OK button
when the pipe indicates EOF
(End Of File).
This can be used
to display the output
of some external program.
This will be done right away if you choose "Yes" in the next dialog.
This choice will cause 'find /usr/bin' to be run with subprocess.Popen()
and the output to be displayed, via a pipe, in a 'programbox' widget."""
self.progressboxoid("programbox", func_name, text)
if d.Yesno("Do you want to run 'find /usr/bin' in a programbox widget?"):
try:
devnull = subprocess.DEVNULL
except AttributeError: # Python < 3.3
devnull_context = devnull = open(os.devnull, "wb")
else:
devnull_context = DummyContextManager()
args = ["find", "/usr/bin"]
with devnull_context:
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=devnull, close_fds=True)
# One could use title=... instead of text=... to put the text
# in the title bar.
d.programbox(fd=p.stdout.fileno(),
text="Example showing the output of a command "
"with programbox")
retcode = p.wait()
# Context manager support for subprocess.Popen objects requires
# Python 3.2 or later.
p.stdout.close()
return retcode
else:
return None
def infobox_demo(self):
d.infobox("One moment, please. Just wasting some time here to "
"show you the infobox...")
time.sleep(0.5 if params["fast_mode"] else 4.0)
def gauge_demo(self):
d.gauge_start("Progress: 0%", title="Still testing your patience...")
for i in range(1, 101):
if i < 50:
d.gauge_update(i, "Progress: {0}%".format(i), update_text=True)
elif i == 50:
d.gauge_update(i, "Over {0}%. Good.".format(i),
update_text=True)
elif i == 80:
d.gauge_update(i, "Yeah, this boring crap will be over Really "
"Soon Now.", update_text=True)
else:
d.gauge_update(i)
time.sleep(0.01 if params["fast_mode"] else 0.1)
d.gauge_stop()
def mixedgauge_demo(self):
for i in range(1, 101, 20):
d.mixedgauge("This is the 'text' part of the mixedgauge\n"
"and this is a forced new line.",
title="'mixedgauge' demo",
percent=int(round(72+28*i/100)),
elements=[("Task 1", "Foobar"),
("Task 2", 0),
("Task 3", 1),
("Task 4", 2),
("Task 5", 3),
("", 8),
("Task 6", 5),
("Task 7", 6),
("Task 8", 7),
("", ""),
# 0 is the dialog special code for
# "Succeeded", so these must not be equal to
# zero! That is why I made the range() above
# start at 1.
("Task 9", -max(1, 100-i)),
("Task 10", -i)])
time.sleep(0.5 if params["fast_mode"] else 2)
def yesno_demo(self, with_help=True):
if not with_help:
# Simple version, without the "Help" button (the return value is
# True or False):
return d.Yesno("\nDo you like this demo?", yes_label="Yes, I do",
no_label="No, I do not", height=10, width=40,
title="An Important Question")
# 'yesno' dialog box with custom Yes, No and Help buttons
while True:
reply = d.Yesnohelp("\nDo you like this demo?",
yes_label="Yes, I do", no_label="No, I do not",
help_label="Please help me!", height=10,
width=60, title="An Important Question")
if reply == "yes":
return True
elif reply == "no":
return False
elif reply == "help":
d.msgbox("""\
I can hear your cry for help, and would really like to help you. However, I \
am afraid there is not much I can do for you here; you will have to decide \
for yourself on this matter.
Keep in mind that you can always rely on me. \
You have all my support, be brave!""",
height=15, width=60,
title="From Your Faithful Servant")
else:
assert False, "Unexpected reply from MyDialog.Yesnohelp(): " \
+ repr(reply)
def msgbox_demo(self, answer):
if answer:
msg = "Excellent! Press OK to see its source code (or another " \
"file if not in the correct directory)."
else:
msg = "Well, feel free to send your complaints to /dev/null!\n\n" \
"Sincerely yours, etc."
d.msgbox(msg, width=50)
def textbox_demo(self):
# Better use the absolute path for displaying in the dialog title
filepath = os.path.abspath(__file__)
code = d.textbox(filepath, width=76,
title="Contents of {0}".format(filepath),
extra_button=True, extra_label="Stop it now!")
if code == "extra":
d.msgbox("Your wish is my command, Master.", width=40,
title="Exiting")
sys.exit(0)
def inputbox_demo(self):
code, answer = d.inputbox("What's your name?", init="Snow White")
return answer
def inputbox_demo_with_help(self):
init_str = "Snow White"
while True:
code, answer = d.inputbox("What's your name?", init=init_str,
title="'inputbox' demo", help_button=True)
if code == "help":
d.msgbox("Help from the 'inputbox' demo. The string entered "
"so far is {0!r}.".format(answer),
title="'inputbox' demo")
init_str = answer
else:
break
return answer
def form_demo(self):
elements = [
("Size (cm)", 1, 1, "175", 1, 20, 4, 3),
("Weight (kg)", 2, 1, "85", 2, 20, 4, 3),
("City", 3, 1, "Groboule-les-Bains", 3, 20, 15, 25),
("State", 4, 1, "Some Lost Place", 4, 20, 15, 25),
("Country", 5, 1, "Nowhereland", 5, 20, 15, 20),
("My", 6, 1, "I hereby declare that, upon leaving this "
"world, all", 6, 20, 0, 0),
("Very", 7, 1, "my fortune shall be transferred to Florent "
"Rougon's", 7, 20, 0, 0),
("Last", 8, 1, "bank account number 000 4237 4587 32454/78 at "
"Banque", 8, 20, 0, 0),
("Will", 9, 1, "Cantonale Vaudoise, Lausanne, Switzerland.",
9, 20, 0, 0) ]
code, fields = d.form("Please fill in some personal information:",
elements, width=77)
return fields
def form_demo_with_help(self, item_help=True):
# This function is slightly complex because it provides help support
# with 'help_status=True', and optionally also with 'item_help=True'
# together with 'help_tags=True'. For a very simple version (without
# any help support), see form_demo() above.
minver_for_helptags = "1.2-20130902"
if item_help:
if self.dialog_version_check(minver_for_helptags):
complement = """'item_help=True' is also used in conjunction \
with 'help_tags=True' in order to display per-item help at the bottom of the \
widget."""
else:
item_help = False
complement = """'item_help=True' is not used, because to make \
it consistent with the 'item_help=False' case, dialog {min} or later is \
required (for the --help-tags option); however, it appears that you are using \
version {used}.""".format(min=minver_for_helptags,
used=d.cached_backend_version)
else:
complement = """'item_help=True' is not used, because it has \
been disabled; therefore, there is no per-item help at the bottom of the \
widget."""
text = """\
This is a demo for the 'form' widget, which is similar to 'mixedform' but \
a bit simpler in that it has no notion of field type (to hide contents such \
as passwords).
This demo uses 'help_button=True' to provide a Help button \
and 'help_status=True' to allow redisplaying the widget in the same state \
when leaving the help dialog. {complement}""".format(complement=complement)
elements = [ ("Fruit", 1, 8, "mirabelle plum", 1, 20, 18, 30),
("Color", 2, 8, "yellowish", 2, 20, 18, 30),
("Flavor", 3, 8, "sweet when ripe", 3, 20, 18, 30),
("Origin", 4, 8, "Lorraine", 4, 20, 18, 30) ]
more_kwargs = {}
if item_help:
more_kwargs.update({ "item_help": True,
"help_tags": True })
elements = [ list(l) + [ "Help text for item {0}".format(i+1) ]
for i, l in enumerate(elements) ]
while True:
code, t = d.form(text, elements, height=20, width=65,
title="'form' demo with help facilities",
help_button=True, help_status=True, **more_kwargs)
if code == "help":
label, status, elements = t
d.msgbox("You asked for help concerning the field labelled "
"{0!r}.".format(label), width=50)
else:
# 't' contains the list of items as filled by the user
break
answers = '\n'.join(t)
d.msgbox("Your answers:\n\n{0}".format(indent(answers, " ")),
width=0, height=0,
title="'form' demo with help facilities", no_collapse=True)
return t
def mixedform_demo(self):
HIDDEN = 0x1
READ_ONLY = 0x2
elements = [
("Size (cm)", 1, 1, "175", 1, 20, 4, 3, 0x0),
("Weight (kg)", 2, 1, "85", 2, 20, 4, 3, 0x0),
("City", 3, 1, "Groboule-les-Bains", 3, 20, 15, 25, 0x0),
("State", 4, 1, "Some Lost Place", 4, 20, 15, 25, 0x0),
("Country", 5, 1, "Nowhereland", 5, 20, 15, 20, 0x0),
("My", 6, 1, "I hereby declare that, upon leaving this "
"world, all", 6, 20, 54, 0, READ_ONLY),
("Very", 7, 1, "my fortune shall be transferred to Florent "
"Rougon's", 7, 20, 54, 0, READ_ONLY),
("Last", 8, 1, "bank account number 000 4237 4587 32454/78 at "
"Banque", 8, 20, 54, 0, READ_ONLY),
("Will", 9, 1, "Cantonale Vaudoise, Lausanne, Switzerland.",
9, 20, 54, 0, READ_ONLY),
("Read-only field...", 10, 1, "... that doesn't go into the "
"output list", 10, 20, 0, 0, 0x0),
("\/3r`/ 53kri7 (0d3", 11, 1, "", 11, 20, 15, 20, HIDDEN) ]
code, fields = d.mixedform(
"Please fill in some personal information:", elements, width=77)
return fields
def passwordform_demo(self):
elements = [
("Secret field 1", 1, 1, "", 1, 20, 12, 0),
("Secret field 2", 2, 1, "", 2, 20, 12, 0),
("Secret field 3", 3, 1, "Providing a non-empty initial content "
"(like this) for an invisible field can be very confusing!",
3, 20, 30, 160)]
code, fields = d.passwordform(
"Please enter all your secret passwords.\n\nOn purpose here, "
"nothing is echoed when you type in the passwords. If you want "
"asterisks, use the 'insecure' keyword argument as in the "
"passwordbox demo.",
elements, width=77, height=15, title="Passwordform demo")
d.msgbox("Secret password 1: '%s'\n"
"Secret password 2: '%s'\n"
"Secret password 3: '%s'" % tuple(fields),
width=60, height=20, title="The Whole Truth Now Revealed")
return fields
def menu_demo(self, name, city, state, country, size, weight, secret_code,
last_will1, last_will2, last_will3, last_will4):
text = """\
Hello, %s from %s, %s, %s, %s cm, %s kg.
Thank you for giving us your Very Secret Code '%s'.
As expressly stated in the previous form, your Last Will reads: "%s"
All that was very interesting, thank you. However, in order to know you \
better and provide you with the best possible customer service, we would \
still need to know your favorite day of the week. Please indicate your \
preference below.""" \
% (name, city, state, country, size, weight, secret_code,
' '.join([last_will1, last_will2, last_will3, last_will4]))
code, tag = d.menu(text, height=23, width=76,
choices=[("Monday", "Being the first day of the week..."),
("Tuesday", "Comes after Monday"),
("Wednesday", "Before Thursday day"),
("Thursday", "Itself after Wednesday"),
("Friday", "The best day of all"),
("Saturday", "Well, I've had enough, thanks"),
("Sunday", "Let's rest a little bit")])