pythondialog-2.7/0000755000175000017500000000000010116020761013627 5ustar gandalfgandalfpythondialog-2.7/TODO0000644000175000017500000000060210024656350014324 0ustar gandalfgandalf* Add code so that the input buffer is flushed before a dialog box is shown. This would make the UI more predictable for users. This feature could be turned on and off through an instance method. -> Unclear to me (Florent). * Try detecting the terminal window size in order to make reasonable height and width defaults. Hmmm -- should also then check for terminal resizing... pythondialog-2.7/demo.py0000755000175000017500000002524310116020735015137 0ustar gandalfgandalf#! /usr/bin/env python # demo.py --- A simple demonstration program for pythondialog # Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov # Copyright (C) 2002, 2004 Florent Rougon # # This program is in the public domain. """Demonstration program for pythondialog. This is a simple program demonstrating 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). Please have a look at the documentation for the `handle_exit_code' function in order to understand the somewhat relaxed error checking policy for pythondialog calls in this demo. """ import sys, os, os.path, time, string, dialog FAST_DEMO = 0 # XXX We should handle the new DIALOG_HELP and DIALOG_EXTRA return codes here. def handle_exit_code(d, code): """Sample function showing how to interpret the dialog exit codes. This function is not used after every call to dialog in this demo for two reasons: 1. For some boxes, unfortunately, dialog returns the code for ERROR when the user presses ESC (instead of the one chosen for ESC). As these boxes only have an OK button, and an exception is raised and correctly handled here in case of real dialog errors, there is no point in testing the dialog exit status (it can't be CANCEL as there is no CANCEL button; it can't be ESC as unfortunately, the dialog makes it appear as an error; it can't be ERROR as this is handled in dialog.py to raise an exception; therefore, it *is* OK). 2. To not clutter simple code with things that are demonstrated elsewhere. """ # d is supposed to be a Dialog instance if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): if code == d.DIALOG_CANCEL: msg = "You chose cancel in the last dialog box. Do you want to " \ "exit this demo?" else: msg = "You pressed ESC in the last dialog box. Do you want to " \ "exit this demo?" # "No" or "ESC" will bring the user back to the demo. # DIALOG_ERROR is propagated as an exception and caught in main(). # So we only need to handle OK here. if d.yesno(msg) == d.DIALOG_OK: sys.exit(0) return 0 else: return 1 # code is d.DIALOG_OK def infobox_demo(d): # Exit code thrown away to keey this demo code simple (however, real # errors are propagated by an exception) d.infobox("One moment, please. Just wasting some time here to " "show you the infobox...") if FAST_DEMO: time.sleep(0.5) else: time.sleep(3) def gauge_demo(d): d.gauge_start("Progress: 0%", title="Still testing your patience...") for i in range(1, 101): if i < 50: d.gauge_update(i, "Progress: %d%%" % i, update_text=1) elif i == 50: d.gauge_update(i, "Over %d%%. Good." % i, update_text=1) elif i == 80: d.gauge_update(i, "Yeah, this boring crap will be over Really " "Soon Now.", update_text=1) else: d.gauge_update(i) if FAST_DEMO: time.sleep(0.01) else: time.sleep(0.1) d.gauge_stop() def yesno_demo(d): # Return the answer given to the question (also specifies if ESC was # pressed) return d.yesno("Do you like this demo?") def msgbox_demo(d, answer): if answer == d.DIALOG_OK: d.msgbox("Excellent! Press OK to see the source code.") else: d.msgbox("Well, feel free to send your complaints to /dev/null!") def textbox_demo(d): d.textbox("demo.py", width=76) def inputbox_demo(d): # If the user presses Cancel, he is asked (by handle_exit_code) if he # wants to exit the demo. We loop as long as he tells us he doesn't want # to do so. while 1: (code, answer) = d.inputbox("What's your name?", init="Snow White") if handle_exit_code(d, code): break return answer def menu_demo(d): while 1: (code, tag) = d.menu( "What's your favorite day of the week?", width=60, 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")]) if handle_exit_code(d, code): break return tag def checklist_demo(d): while 1: # We could put non-empty items here (not only the tag for each entry) (code, tag) = d.checklist(text="What sandwich toppings do you like?", height=15, width=54, list_height=7, choices=[("Catsup", "", 0), ("Mustard", "", 0), ("Pesto", "", 0), ("Mayonaise", "", 1), ("Horse radish","", 1), ("Sun-dried tomatoes", "", 1)], title="Do you prefer ham or spam?", backtitle="And now, for something " "completely different...") if handle_exit_code(d, code): break return tag def radiolist_demo(d): while 1: (code, tag) = d.radiolist( "What's your favorite kind of sandwich?", width=65, choices=[("Hamburger", "2 slices of bread, a steak...", 0), ("Hotdog", "doesn't bite any more", 0), ("Burrito", "no se lo que es", 0), ("Doener", "Huh?", 0), ("Falafel", "Erm...", 0), ("Bagel", "Of course!", 0), ("Big Mac", "Ah, that's easy!", 1), ("Whopper", "Erm, sorry", 0), ("Quarter Pounder", 'called "le Big Mac" in France', 0), ("Peanut Butter and Jelly", "Well, that's your own " "business...", 0), ("Grilled cheese", "And nothing more?", 0)]) if handle_exit_code(d, code): break return tag def calendar_demo(d): while 1: (code, date) = d.calendar("When do you think Debian sarge will be " "released?", year=0) if handle_exit_code(d, code): break return date def passwordbox_demo(d): while 1: (code, password) = d.passwordbox("What is your root password, " "so that I can crack your system " "right now?") if handle_exit_code(d, code): break return password def comment_on_sarge_release_date(day, month, year): if year < 2004 or (year == 2004 and month <= 3): return "Mmm... what about a little tour on http://www.debian.org/?" elif year == 2004 and month <= 4: return """\ Damn, how optimistic! You don't know much about Debian, do you?""" elif year == 2004 and month <= 7: return """\ Well, good guess. But who knows what the future reserves to us? ;-)""" elif year == 2004: return """\ Oh, well. That's plausible. But please, please don't depress other people with your pronostics... ;-)""" else: return "Hey, you're a troll! (or do you know Debian *so* well? ;-)" def scrollbox_demo(d, name, favorite_day, toppings, sandwich, date, password): day, month, year = date msg = """\ Here are some vital statistics about you: Name: %s Favorite day of the week: %s Favorite sandwich toppings:%s Favorite sandwich: %s You estimate Debian sarge's release to happen around %04u-%02u-%02u. %s Your root password is: ************************** (looks good!)""" \ % (name, favorite_day, string.join([''] + toppings, "\n "), sandwich, year, month, day, comment_on_sarge_release_date(day, month, year)) d.scrollbox(msg, height=20, width=75, title="Great Report of the Year") def fselect_demo(d): while 1: root_dir = os.sep # This is OK for UNIX systems dir = os.getenv("HOME", root_dir) # Make sure the directory we chose ends with os.sep() so that dialog # shows its contents right away if dir and dir[-1] != os.sep: dir = dir + os.sep (code, path) = d.fselect(dir, 10, 50, title="Cute little file to show as " "in a `tail -f'") if handle_exit_code(d, code): if not os.path.isfile(path): d.scrollbox("Hmm. Didn't I ask you to select a *file*?", width=50, height=10) else: break return path def tailbox_demo(d, file): d.tailbox(file, 20, 60, title="You are brave. You deserve the " "right to rest, now." ) def demo(): # If you want to use Xdialog (pathnames are also OK for the 'dialog' # argument) # d = dialog.Dialog(dialog="Xdialog", compat="Xdialog") d = dialog.Dialog(dialog="dialog") d.add_persistent_args(["--backtitle", "pythondialog demo"]) infobox_demo(d) gauge_demo(d) answer = yesno_demo(d) msgbox_demo(d, answer) textbox_demo(d) name = inputbox_demo(d) favorite_day = menu_demo(d) toppings = checklist_demo(d) sandwich = radiolist_demo(d) date = calendar_demo(d) password = passwordbox_demo(d) scrollbox_demo(d, name, favorite_day, toppings, sandwich, date, password) d.scrollbox("""\ Haha. You thought it was over. Wrong. Even More fun is to come! (well, depending on your definition on "fun") Now, please select a file you would like to see growing (or not...).""", width=75) file = fselect_demo(d) tailbox_demo(d, file) d.scrollbox("""\ Now, you're done. No, I'm not kidding. So, why the hell are you sitting here instead of rushing on that EXIT button? Ah, you did like the demo. Hmm... are you feeling OK? ;-)""", width=75) def main(): """This demo shows the main features of the pythondialog Dialog class. """ try: demo() except dialog.error, exc_instance: sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message()) sys.exit(1) sys.exit(0) if __name__ == "__main__": main() pythondialog-2.7/README0000644000175000017500000000675410115631743014532 0ustar gandalfgandalfOverview -------- pythondialog is a Python wrapper for the UNIX "dialog" utility written by Savio Lam and modified by several people, whose home page you should find at http://dickey.his.com/dialog/dialog.html. Its purpose is to provide an easy to use, pythonic and as complete as possible interface to dialog from Python code. pythondialog is free software, licensed under the GNU LGPL. If you want to get a quick idea of what this module allows you to do, you should run demo.py: python demo.py What is pythondialog good for? What are its limitations? -------------------------------------------------------- As you might infer from the name, dialog is a high-level program that generates dialog boxes. So is pythondialog. They allow you to build nice interfaces quickly and easily, but you don't have full control over the widgets, nor can you create new widgets without modifying dialog itself. If you need to do low-level stuff, you should have a look at ncurses or slang instead. Documentation ------------- pythondialog is fully documented through Python docstrings. Handy ways to access to this documentation are to use the pydoc standalone program or Python module. You can type "pydoc dialog" at the command prompt in pythondialog base directory. Alternatively, you can type: - "import dialog; help(dialog)" at at a Python 2.2 command prompt (and probably any later version) To browse it in HTML format, you can launch an HTTP server listening on port 1234 with "pydoc -p 1234 &" (yes, it is damn easy!) and simply browse on http://localhost:1234/ afterwards. Alternatively, you can dump the current dialog.py documentation (as found by Python if you did "import dialog") as an html file with "pydoc -w dialog". This will generate dialog.html in the current directory. See the pydoc module's documentation for more information. Using Xdialog instead of dialog ------------------------------- Starting with 2.06, there is an "Xdialog" compatibility mode that you can use if you want pythondialog to run the graphical Xdialog program (which *should* be found under http://xdialog.free.fr/) instead of dialog (text-mode, based on the ncurses library). The primary supported platform is still dialog, but as long as only small modifications are enough to make pythondialog work with Xdialog, I am willing to support Xdialog if people are interested in it (which turned out to be the case for Xdialog). The demo.py from pythondialog 2.06 has been tested with Xdialog 2.0.6 and found to work well (barring Xdialog's annoying behaviour with the file selection dialog box). Troubleshooting --------------- * pythondialog seems not to work very well with whiptail. Well, whiptail is not very compatible with dialog any more. Although you can tell pythondialog the program you want it to invoke, only programs that are mostly dialog-compatible are supported. * It is said that there is a bug in (at least) the Mandrake 7.0 Russian Edition running on AMD K6-2 3D that causes core dump when `dialog' is run with the --gauge option; in this case you'll have to recompile the `dialog' program. History ------- pythondialog was originally written by Robb Shecter. Sultanbek Tezadov added some features to it (mainly the first gauge implementation, I guess). Florent Rougon rewrote most parts of the program to make it more robust and flexible so that it can give access to most features of the dialog program. Finally, I (Peter Astrand) took over maintainership for both the original version and Florents updated version. pythondialog-2.7/PKG-INFO0000644000175000017500000000117310116020761014726 0ustar gandalfgandalfMetadata-Version: 1.0 Name: pythondialog Version: 2.7 Summary: A Python interface to the UNIX dialog utility and mostly-compatible programs Home-page: http://pythondialog.sourceforge.net/ Author: Peter Astrand Author-email: peter@cendio.se License: LGPL Description: A Python interface to the UNIX dialog utility, designed to provide an easy, pythonic and as complete as possible way to use the dialog features from Python code. Back-end programs that are almost compatible with dialog are also supported if someone cares about them. Keywords: dialog,Xdialog,whiptail,text-mode interface Platform: UNIX pythondialog-2.7/dialog.py0000644000175000017500000016766210116015602015460 0ustar gandalfgandalf# dialog.py --- A python interface to the Linux "dialog" utility # Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov # Copyright (C) 2002, 2003, 2004 Florent Rougon # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """Python interface to dialog-like programs. This module provides a Python interface to dialog-like programs such as `dialog', `Xdialog' and `whiptail'. It provides a Dialog class that retains some parameters such as the program name and path as well as the values to pass as DIALOG* environment variables to the chosen program. For a quick start, you should look at the demo.py file that comes with pythondialog. It demonstrates a simple use of each widget offered by the Dialog class. See the Dialog class documentation for general usage information, list of available widgets and ways to pass options to dialog. Notable exceptions ------------------ Here is the hierarchy of notable exceptions raised by this module: error ExecutableNotFound BadPythonDialogUsage PythonDialogSystemError PythonDialogIOError PythonDialogOSError PythonDialogErrorBeforeExecInChildProcess PythonDialogReModuleError UnexpectedDialogOutput DialogTerminatedBySignal DialogError UnableToCreateTemporaryDirectory PythonDialogBug ProbablyPythonBug As you can see, every exception `exc' among them verifies: issubclass(exc, error) so if you don't need fine-grained error handling, simply catch `error' (which will probably be accessible as dialog.error from your program) and you should be safe. """ from __future__ import nested_scopes import sys, os, tempfile, random, string, re, types # Python < 2.3 compatibility if sys.hexversion < 0x02030000: # The assignments would work with Python >= 2.3 but then, pydoc # shows them in the DATA section of the module... True = 0 == 0 False = 0 == 1 # Exceptions raised by this module # # When adding, suppressing, renaming exceptions or changing their # hierarchy, don't forget to update the module's docstring. class error(Exception): """Base class for exceptions in pythondialog.""" def __init__(self, message=None): self.message = message def __str__(self): return "<%s: %s>" % (self.__class__.__name__, self.message) def complete_message(self): if self.message: return "%s: %s" % (self.ExceptionShortDescription, self.message) else: return "%s" % self.ExceptionShortDescription ExceptionShortDescription = "pythondialog generic exception" # For backward-compatibility # # Note: this exception was not documented (only the specific ones were), so # the backward-compatibility binding could be removed relatively easily. PythonDialogException = error class ExecutableNotFound(error): """Exception raised when the dialog executable can't be found.""" ExceptionShortDescription = "Executable not found" class PythonDialogBug(error): """Exception raised when pythondialog finds a bug in his own code.""" ExceptionShortDescription = "Bug in pythondialog" # Yeah, the "Probably" makes it look a bit ugly, but: # - this is more accurate # - this avoids a potential clash with an eventual PythonBug built-in # exception in the Python interpreter... class ProbablyPythonBug(error): """Exception raised when pythondialog behaves in a way that seems to \ indicate a Python bug.""" ExceptionShortDescription = "Bug in python, probably" class BadPythonDialogUsage(error): """Exception raised when pythondialog is used in an incorrect way.""" ExceptionShortDescription = "Invalid use of pythondialog" class PythonDialogSystemError(error): """Exception raised when pythondialog cannot perform a "system \ operation" (e.g., a system call) that should work in "normal" situations. This is a convenience exception: PythonDialogIOError, PythonDialogOSError and PythonDialogErrorBeforeExecInChildProcess all derive from this exception. As a consequence, watching for PythonDialogSystemError instead of the aformentioned exceptions is enough if you don't need precise details about these kinds of errors. Don't confuse this exception with Python's builtin SystemError exception. """ ExceptionShortDescription = "System error" class PythonDialogIOError(PythonDialogSystemError): """Exception raised when pythondialog catches an IOError exception that \ should be passed to the calling program.""" ExceptionShortDescription = "IO error" class PythonDialogOSError(PythonDialogSystemError): """Exception raised when pythondialog catches an OSError exception that \ should be passed to the calling program.""" ExceptionShortDescription = "OS error" class PythonDialogErrorBeforeExecInChildProcess(PythonDialogSystemError): """Exception raised when an exception is caught in a child process \ before the exec sytem call (included). This can happen in uncomfortable situations like when the system is out of memory or when the maximum number of open file descriptors has been reached. This can also happen if the dialog-like program was removed (or if it is has been made non-executable) between the time we found it with _find_in_path and the time the exec system call attempted to execute it... """ ExceptionShortDescription = "Error in a child process before the exec " \ "system call" class PythonDialogReModuleError(PythonDialogSystemError): """Exception raised when pythondialog catches a re.error exception.""" ExceptionShortDescription = "'re' module error" class UnexpectedDialogOutput(error): """Exception raised when the dialog-like program returns something not \ expected by pythondialog.""" ExceptionShortDescription = "Unexpected dialog output" class DialogTerminatedBySignal(error): """Exception raised when the dialog-like program is terminated by a \ signal.""" ExceptionShortDescription = "dialog-like terminated by a signal" class DialogError(error): """Exception raised when the dialog-like program exits with the \ code indicating an error.""" ExceptionShortDescription = "dialog-like terminated due to an error" class UnableToCreateTemporaryDirectory(error): """Exception raised when we cannot create a temporary directory.""" ExceptionShortDescription = "unable to create a temporary directory" # Values accepted for checklists try: _on_rec = re.compile(r"on", re.IGNORECASE) _off_rec = re.compile(r"off", re.IGNORECASE) _calendar_date_rec = re.compile( r"(?P\d\d)/(?P\d\d)/(?P\d\d\d\d)$") _timebox_time_rec = re.compile( r"(?P\d\d):(?P\d\d):(?P\d\d)$") except re.error, v: raise PythonDialogReModuleError(v) # This dictionary allows us to write the dialog common options in a Pythonic # way (e.g. dialog_instance.checklist(args, ..., title="Foo", no_shadow=1)). # # Options such as --separate-output should obviously not be set by the user # since they affect the parsing of dialog's output: _common_args_syntax = { "aspect": lambda ratio: ("--aspect", str(ratio)), "backtitle": lambda backtitle: ("--backtitle", backtitle), "beep": lambda enable: _simple_option("--beep", enable), "beep_after": lambda enable: _simple_option("--beep-after", enable), # Warning: order = y, x! "begin": lambda coords: ("--begin", str(coords[0]), str(coords[1])), "cancel": lambda string: ("--cancel-label", string), "clear": lambda enable: _simple_option("--clear", enable), "cr_wrap": lambda enable: _simple_option("--cr-wrap", enable), "create_rc": lambda file: ("--create-rc", file), "defaultno": lambda enable: _simple_option("--defaultno", enable), "default_item": lambda string: ("--default-item", string), "help": lambda enable: _simple_option("--help", enable), "help_button": lambda enable: _simple_option("--help-button", enable), "help_label": lambda string: ("--help-label", string), "ignore": lambda enable: _simple_option("--ignore", enable), "item_help": lambda enable: _simple_option("--item-help", enable), "max_input": lambda size: ("--max-input", str(size)), "no_kill": lambda enable: _simple_option("--no-kill", enable), "no_cancel": lambda enable: _simple_option("--no-cancel", enable), "nocancel": lambda enable: _simple_option("--nocancel", enable), "no_shadow": lambda enable: _simple_option("--no-shadow", enable), "ok_label": lambda string: ("--ok-label", string), "print_maxsize": lambda enable: _simple_option("--print-maxsize", enable), "print_size": lambda enable: _simple_option("--print-size", enable), "print_version": lambda enable: _simple_option("--print-version", enable), "separate_output": lambda enable: _simple_option("--separate-output", enable), "separate_widget": lambda string: ("--separate-widget", string), "shadow": lambda enable: _simple_option("--shadow", enable), "size_err": lambda enable: _simple_option("--size-err", enable), "sleep": lambda secs: ("--sleep", str(secs)), "stderr": lambda enable: _simple_option("--stderr", enable), "stdout": lambda enable: _simple_option("--stdout", enable), "tab_correct": lambda enable: _simple_option("--tab-correct", enable), "tab_len": lambda n: ("--tab-len", str(n)), "timeout": lambda secs: ("--timeout", str(secs)), "title": lambda title: ("--title", title), "trim": lambda enable: _simple_option("--trim", enable), "version": lambda enable: _simple_option("--version", enable)} def _simple_option(option, enable): """Turn on or off the simplest dialog Common Options.""" if enable: return (option,) else: # This will not add any argument to the command line return () def _find_in_path(prog_name): """Search an executable in the PATH. If PATH is not defined, the default path ":/bin:/usr/bin" is used. Return a path to the file or None if no readable and executable file is found. Notable exception: PythonDialogOSError """ try: # Note that the leading empty component in the default value for PATH # could lead to the returned path not being absolute. PATH = os.getenv("PATH", ":/bin:/usr/bin") # see the execvp(3) man page for dir in string.split(PATH, ":"): file_path = os.path.join(dir, prog_name) if os.path.isfile(file_path) \ and os.access(file_path, os.R_OK | os.X_OK): return file_path return None except os.error, v: raise PythonDialogOSError(v.strerror) def _path_to_executable(f): """Find a path to an executable. Find a path to an executable, using the same rules as the POSIX exec*p functions (see execvp(3) for instance). If `f' contains a '/', it is assumed to be a path and is simply checked for read and write permissions; otherwise, it is looked for according to the contents of the PATH environment variable, which defaults to ":/bin:/usr/bin" if unset. The returned path is not necessarily absolute. Notable exceptions: ExecutableNotFound PythonDialogOSError """ try: if '/' in f: if os.path.isfile(f) and \ os.access(f, os.R_OK | os.X_OK): res = f else: raise ExecutableNotFound("%s cannot be read and executed" % f) else: res = _find_in_path(f) if res is None: raise ExecutableNotFound( "can't find the executable for the dialog-like " "program") except os.error, v: raise PythonDialogOSError(v.strerror) return res def _to_onoff(val): """Convert boolean expressions to "on" or "off" This function converts every non-zero integer as well as "on", "ON", "On" and "oN" to "on" and converts 0, "off", "OFF", etc. to "off". Notable exceptions: PythonDialogReModuleError BadPythonDialogUsage """ if type(val) == types.IntType: if val: return "on" else: return "off" elif type(val) == types.StringType: try: if _on_rec.match(val): return "on" elif _off_rec.match(val): return "off" except re.error, v: raise PythonDialogReModuleError(v) else: raise BadPythonDialogUsage("invalid boolean value: %s" % val) def _compute_common_args(dict): """Compute the list of arguments for dialog common options. Compute a list of the command-line arguments to pass to dialog from a keyword arguments dictionary for options listed as "common options" in the manual page for dialog. These are the options that are not tied to a particular widget. This allows to specify these options in a pythonic way, such as: d.checklist(, title="...", backtitle="...") instead of having to pass them with strings like "--title foo" or "--backtitle bar". Notable exceptions: None """ args = [] for key in dict.keys(): args.extend(_common_args_syntax[key](dict[key])) return args def _create_temporary_directory(): """Create a temporary directory (securely). Return the directory path. Notable exceptions: - UnableToCreateTemporaryDirectory - PythonDialogOSError - exceptions raised by the tempfile module (which are unfortunately not mentioned in its documentation, at least in Python 2.3.3...) """ find_temporary_nb_attempts = 5 for i in range(find_temporary_nb_attempts): try: # Using something >= 2**31 causes an error in Python 2.2... tmp_dir = os.path.join(tempfile.gettempdir(), "%s-%u" \ % ("pythondialog", random.randint(0, 2**30-1))) except os.error, v: raise PythonDialogOSError(v.strerror) try: os.mkdir(tmp_dir, 0700) except os.error: continue else: break else: raise UnableToCreateTemporaryDirectory( "somebody may be trying to attack us") return tmp_dir # DIALOG_OK, DIALOG_CANCEL, etc. are environment variables controlling # dialog's exit status in the corresponding situation. # # Note: # - 127 must not be used for any of the DIALOG_* values. It is used # when a failure occurs in the child process before it exec()s # dialog (where "before" includes a potential exec() failure). # - 126 is also used (although in presumably rare situations). _dialog_exit_status_vars = { "OK": 0, "CANCEL": 1, "ESC": 2, "ERROR": 3, "EXTRA": 4, "HELP": 5 } # Main class of the module class Dialog: """Class providing bindings for dialog-compatible programs. This class allows you to invoke dialog or a compatible program in a pythonic way to build quicky and easily simple but nice text interfaces. An application typically creates one instance of the Dialog class and uses it for all its widgets, but it is possible to use concurrently several instances of this class with different parameters (such as the background title) if you have the need for this. The exit code (exit status) returned by dialog is to be compared with the DIALOG_OK, DIALOG_CANCEL, DIALOG_ESC, DIALOG_ERROR, DIALOG_EXTRA and DIALOG_HELP attributes of the Dialog instance (they are integers). Note: although this class does all it can to allow the caller to differentiate between the various reasons that caused a dialog box to be closed, its backend, dialog 0.9a-20020309a for my tests, doesn't always return DIALOG_ESC when the user presses the ESC key, but often returns DIALOG_ERROR instead. The exit codes returned by the corresponding Dialog methods are of course just as wrong in these cases. You've been warned. Public methods of the Dialog class (mainly widgets) --------------------------------------------------- The Dialog class has the following methods: add_persistent_args calendar checklist fselect gauge_start gauge_update gauge_stop infobox inputbox menu msgbox passwordbox radiolist scrollbox tailbox textbox timebox yesno clear (obsolete) setBackgroundTitle (obsolete) Passing dialog "Common Options" ------------------------------- Every widget method has a **kwargs argument allowing you to pass dialog so-called Common Options (see the dialog(1) manual page) to dialog for this widget call. For instance, if `d' is a Dialog instance, you can write: d.checklist(args, ..., title="A Great Title", no_shadow=1) The no_shadow option is worth looking at: 1. It is an option that takes no argument as far as dialog is concerned (unlike the "--title" option, for instance). When you list it as a keyword argument, the option is really passed to dialog only if the value you gave it evaluates to true, e.g. "no_shadow=1" will cause "--no-shadow" to be passed to dialog whereas "no_shadow=0" will cause this option not to be passed to dialog at all. 2. It is an option that has a hyphen (-) in its name, which you must change into an underscore (_) to pass it as a Python keyword argument. Therefore, "--no-shadow" is passed by giving a "no_shadow=1" keyword argument to a Dialog method (the leading two dashes are also consistently removed). Exceptions ---------- Please refer to the specific methods' docstrings or simply to the module's docstring for a list of all exceptions that might be raised by this class' methods. """ def __init__(self, dialog="dialog", DIALOGRC=None, compat="dialog", use_stdout=None): """Constructor for Dialog instances. dialog -- name of (or path to) the dialog-like program to use; if it contains a '/', it is assumed to be a path and is used as is; otherwise, it is looked for according to the contents of the PATH environment variable, which defaults to ":/bin:/usr/bin" if unset. DIALOGRC -- string to pass to the dialog-like program as the DIALOGRC environment variable, or None if no modification to the environment regarding this variable should be done in the call to the dialog-like program compat -- compatibility mode (see below) The officially supported dialog-like program in pythondialog is the well-known dialog program written in C, based on the ncurses library. It is also known as cdialog and its home page is currently (2004-03-15) located at: http://dickey.his.com/dialog/dialog.html If you want to use a different program such as Xdialog, you should indicate the executable file name with the `dialog' argument *and* the compatibility type that you think it conforms to with the `compat' argument. Currently, `compat' can be either "dialog" (for dialog; this is the default) or "Xdialog" (for, well, Xdialog). The `compat' argument allows me to cope with minor differences in behaviour between the various programs implementing the dialog interface (not the text or graphical interface, I mean the "API"). However, having to support various APIs simultaneously is a bit ugly and I would really prefer you to report bugs to the relevant maintainers when you find incompatibilities with dialog. This is for the benefit of pretty much everyone that relies on the dialog interface. Notable exceptions: ExecutableNotFound PythonDialogOSError """ # DIALOGRC differs from the other DIALOG* variables in that: # 1. It should be a string if not None # 2. We may very well want it to be unset if DIALOGRC is not None: self.DIALOGRC = DIALOGRC # After reflexion, I think DIALOG_OK, DIALOG_CANCEL, etc. # should never have been instance attributes (I cannot see a # reason why the user would want to change their values or # even read them), but it is a bit late, now. So, we set them # based on the (global) _dialog_exit_status_vars.keys. for var in _dialog_exit_status_vars.keys(): varname = "DIALOG_" + var setattr(self, varname, _dialog_exit_status_vars[var]) self._dialog_prg = _path_to_executable(dialog) self.compat = compat self.dialog_persistent_arglist = [] # Use stderr or stdout? if self.compat == "Xdialog": # Default to stdout if Xdialog self.use_stdout = True else: self.use_stdout = False if use_stdout != None: # Allow explicit setting self.use_stdout = use_stdout if self.use_stdout: self.add_persistent_args(["--stdout"]) def add_persistent_args(self, arglist): self.dialog_persistent_arglist.extend(arglist) # For compatibility with the old dialog... def setBackgroundTitle(self, text): """Set the background title for dialog. This method is obsolete. Please remove calls to it from your programs. """ self.add_persistent_args(("--backtitle", text)) def _call_program(self, redirect_child_stdin, cmdargs, **kwargs): """Do the actual work of invoking the dialog-like program. Communication with the dialog-like program is performed through one or two pipes, depending on `redirect_child_stdin'. There is always one pipe that is created to allow the parent process to read what dialog writes on its standard error stream. If `redirect_child_stdin' is True, an additional pipe is created whose reading end is connected to dialog's standard input. This is used by the gauge widget to feed data to dialog. Beware when interpreting the return value: the length of the returned tuple depends on `redirect_child_stdin'. Notable exception: PythonDialogOSError (if pipe() or close() system calls fail...) """ # We want to define DIALOG_OK, DIALOG_CANCEL, etc. in the # environment of the child process so that we know (and # even control) the possible dialog exit statuses. new_environ = {} new_environ.update(os.environ) for var in _dialog_exit_status_vars: varname = "DIALOG_" + var new_environ[varname] = str(getattr(self, varname)) if hasattr(self, "DIALOGRC"): new_environ["DIALOGRC"] = self.DIALOGRC # Create: # - a pipe so that the parent process can read dialog's output on # stdout/stderr # - a pipe so that the parent process can feed data to dialog's # stdin (this is needed for the gauge widget) if # redirect_child_stdin is True try: # rfd = File Descriptor for Reading # wfd = File Descriptor for Writing (child_rfd, child_wfd) = os.pipe() if redirect_child_stdin: (child_stdin_rfd, child_stdin_wfd) = os.pipe() except os.error, v: raise PythonDialogOSError(v.strerror) child_pid = os.fork() if child_pid == 0: # We are in the child process. We MUST NOT raise any exception. try: # The child process doesn't need these file descriptors os.close(child_rfd) if redirect_child_stdin: os.close(child_stdin_wfd) # We want: # - dialog's output on stderr/stdout to go to child_wfd # - data written to child_stdin_wfd to go to dialog's stdin # if redirect_child_stdin is True if self.use_stdout: os.dup2(child_wfd, 1) else: os.dup2(child_wfd, 2) if redirect_child_stdin: os.dup2(child_stdin_rfd, 0) arglist = [self._dialog_prg] + \ self.dialog_persistent_arglist + \ _compute_common_args(kwargs) + \ cmdargs # Insert here the contents of the DEBUGGING file if you want # to obtain a handy string of the complete command line with # arguments quoted for the shell and environment variables # set. os.execve(self._dialog_prg, arglist, new_environ) except: os._exit(127) # Should not happen unless there is a bug in Python os._exit(126) # We are in the father process. # # It is essential to close child_wfd, otherwise we will never # see EOF while reading on child_rfd and the parent process # will block forever on the read() call. # [ after the fork(), the "reference count" of child_wfd from # the operating system's point of view is 2; after the child exits, # it is 1 until the father closes it itself; then it is 0 and a read # on child_rfd encounters EOF once all the remaining data in # the pipe has been read. ] try: os.close(child_wfd) if redirect_child_stdin: os.close(child_stdin_rfd) return (child_pid, child_rfd, child_stdin_wfd) else: return (child_pid, child_rfd) except os.error, v: raise PythonDialogOSError(v.strerror) def _wait_for_program_termination(self, child_pid, child_rfd): """Wait for a dialog-like process to terminate. This function waits for the specified process to terminate, raises the appropriate exceptions in case of abnormal termination and returns the exit status and standard error output of the process as a tuple: (exit_code, stderr_string). `child_rfd' must be the file descriptor for the reading end of the pipe created by self._call_program() whose writing end was connected by self._call_program() to the child process's standard error. This function reads the process's output on standard error from `child_rfd' and closes this file descriptor once this is done. Notable exceptions: DialogTerminatedBySignal DialogError PythonDialogErrorBeforeExecInChildProcess PythonDialogIOError PythonDialogBug ProbablyPythonBug """ exit_info = os.waitpid(child_pid, 0)[1] if os.WIFEXITED(exit_info): exit_code = os.WEXITSTATUS(exit_info) # As we wait()ed for the child process to terminate, there is no # need to call os.WIFSTOPPED() elif os.WIFSIGNALED(exit_info): raise DialogTerminatedBySignal("the dialog-like program was " "terminated by signal %u" % os.WTERMSIG(exit_info)) else: raise PythonDialogBug("please report this bug to the " "pythondialog maintainers") if exit_code == self.DIALOG_ERROR: raise DialogError("the dialog-like program exited with " "code %d (was passed to it as the DIALOG_ERROR " "environment variable)" % exit_code) elif exit_code == 127: raise PythonDialogErrorBeforeExecInChildProcess( "perhaps the dialog-like program could not be executed; " "perhaps the system is out of memory; perhaps the maximum " "number of open file descriptors has been reached") elif exit_code == 126: raise ProbablyPythonBug( "a child process returned with exit status 126; this might " "be the exit status of the dialog-like program, for some " "unknown reason (-> probably a bug in the dialog-like " "program); otherwise, we have probably found a python bug") # We might want to check here whether exit_code is really one of # DIALOG_OK, DIALOG_CANCEL, etc. However, I prefer not doing it # because it would break pythondialog for no strong reason when new # exit codes are added to the dialog-like program. # # As it is now, if such a thing happens, the program using # pythondialog may receive an exit_code it doesn't know about. OK, the # programmer just has to tell the pythondialog maintainer about it and # can temporarily set the appropriate DIALOG_* environment variable if # he wants and assign the corresponding value to the Dialog instance's # DIALOG_FOO attribute from his program. He doesn't even need to use a # patched pythondialog before he upgrades to a version that knows # about the new exit codes. # # The bad thing that might happen is a new DIALOG_FOO exit code being # the same by default as one of those we chose for the other exit # codes already known by pythondialog. But in this situation, the # check that is being discussed wouldn't help at all. # Read dialog's output on its stderr try: child_output = os.fdopen(child_rfd, "rb").read() # Now, since the file object has no reference anymore, the # standard IO stream behind it will be closed, causing the # end of the the pipe we used to read dialog's output on its # stderr to be closed (this is important, otherwise invoking # dialog enough times will eventually exhaust the maximum number # of open file descriptors). except IOError, v: raise PythonDialogIOError(v) return (exit_code, child_output) def _perform(self, cmdargs, **kwargs): """Perform a complete dialog-like program invocation. This function invokes the dialog-like program, waits for its termination and returns its exit status and whatever it wrote on its standard error stream. Notable exceptions: any exception raised by self._call_program() or self._wait_for_program_termination() """ (child_pid, child_rfd) = \ self._call_program(False, *(cmdargs,), **kwargs) (exit_code, output) = \ self._wait_for_program_termination(child_pid, child_rfd) return (exit_code, output) def _strip_xdialog_newline(self, output): """Remove trailing newline (if any), if using Xdialog""" if self.compat == "Xdialog" and output.endswith("\n"): output = output[:-1] return output # This is for compatibility with the old dialog.py def _perform_no_options(self, cmd): """Call dialog without passing any more options.""" return os.system(self._dialog_prg + ' ' + cmd) # For compatibility with the old dialog.py def clear(self): """Clear the screen. Equivalent to the dialog --clear option. This method is obsolete. Please remove calls to it from your programs. """ self._perform_no_options('--clear') def calendar(self, text, height=6, width=0, day=0, month=0, year=0, **kwargs): """Display a calendar dialog box. text -- text to display in the box height -- height of the box (minus the calendar height) width -- width of the box day -- inititial day highlighted month -- inititial month displayed year -- inititial year selected (0 causes the current date to be used as the initial date) A calendar box displays month, day and year in separately adjustable windows. If the values for day, month or year are missing or negative, the current date's corresponding values are used. You can increment or decrement any of those using the left, up, right and down arrows. Use tab or backtab to move between windows. If the year is given as zero, the current date is used as an initial value. Return a tuple of the form (code, date) where `code' is the exit status (an integer) of the dialog-like program and `date' is a list of the form [day, month, year] (where `day', `month' and `year' are integers corresponding to the date chosen by the user) if the box was closed with OK, or None if it was closed with the Cancel button. Notable exceptions: - any exception raised by self._perform() - UnexpectedDialogOutput - PythonDialogReModuleError """ (code, output) = self._perform( *(["--calendar", text, str(height), str(width), str(day), str(month), str(year)],), **kwargs) if code == self.DIALOG_OK: try: mo = _calendar_date_rec.match(output) except re.error, v: raise PythonDialogReModuleError(v) if mo is None: raise UnexpectedDialogOutput( "the dialog-like program returned the following " "unexpected date with the calendar box: %s" % output) date = map(int, mo.group("day", "month", "year")) else: date = None return (code, date) def checklist(self, text, height=15, width=54, list_height=7, choices=[], **kwargs): """Display a checklist box. text -- text to display in the box height -- height of the box width -- width of the box list_height -- number of entries displayed in the box (which can be scrolled) at a given time choices -- a list of tuples (tag, item, status) where `status' specifies the initial on/off state of each entry; can be 0 or 1 (integers, 1 meaning checked, i.e. "on"), or "on", "off" or any uppercase variant of these two strings. Return a tuple of the form (code, [tag, ...]) with the tags for the entries that were selected by the user. `code' is the exit status of the dialog-like program. If the user exits with ESC or CANCEL, the returned tag list is empty. Notable exceptions: any exception raised by self._perform() or _to_onoff() """ cmd = ["--checklist", text, str(height), str(width), str(list_height)] for t in choices: cmd.extend(((t[0], t[1], _to_onoff(t[2])))) # The dialog output cannot be parsed reliably (at least in dialog # 0.9b-20040301) without --separate-output (because double quotes in # tags are escaped with backslashes, but backslashes are not # themselves escaped and you have a problem when a tag ends with a # backslash--the output makes you think you've encountered an embedded # double-quote). kwargs["separate_output"] = True (code, output) = self._perform(*(cmd,), **kwargs) # Since we used --separate-output, the tags are separated by a newline # in the output. There is also a final newline after the last tag. if output: return (code, string.split(output, '\n')[:-1]) else: # empty selection return (code, []) def fselect(self, filepath, height, width, **kwargs): """Display a file selection dialog box. filepath -- initial file path height -- height of the box width -- width of the box The file-selection dialog displays a text-entry window in which you can type a filename (or directory), and above that two windows with directory names and filenames. Here, filepath can be a file path in which case the file and directory windows will display the contents of the path and the text-entry window will contain the preselected filename. Use tab or arrow keys to move between the windows. Within the directory or filename windows, use the up/down arrow keys to scroll the current selection. Use the space-bar to copy the current selection into the text-entry window. Typing any printable character switches focus to the text-entry window, entering that character as well as scrolling the directory and filename windows to the closest match. Use a carriage return or the "OK" button to accept the current value in the text-entry window, or the "Cancel" button to cancel. Return a tuple of the form (code, path) where `code' is the exit status (an integer) of the dialog-like program and `path' is the path chosen by the user (whose last element may be a directory or a file). Notable exceptions: any exception raised by self._perform() """ (code, output) = self._perform( *(["--fselect", filepath, str(height), str(width)],), **kwargs) output = self._strip_xdialog_newline(output) return (code, output) def gauge_start(self, text="", height=8, width=54, percent=0, **kwargs): """Display gauge box. text -- text to display in the box height -- height of the box width -- width of the box percent -- initial percentage shown in the meter A gauge box displays a meter along the bottom of the box. The meter indicates a percentage. This function starts the dialog-like program telling it to display a gauge box with a text in it and an initial percentage in the meter. Return value: undefined. Gauge typical usage ------------------- Gauge typical usage (assuming that `d' is an instance of the Dialog class) looks like this: d.gauge_start() # do something d.gauge_update(10) # 10% of the whole task is done # ... d.gauge_update(100, "any text here") # work is done exit_code = d.gauge_stop() # cleanup actions Notable exceptions: - any exception raised by self._call_program() - PythonDialogOSError """ (child_pid, child_rfd, child_stdin_wfd) = self._call_program( True, *(["--gauge", text, str(height), str(width), str(percent)],), **kwargs) try: self._gauge_process = { "pid": child_pid, "stdin": os.fdopen(child_stdin_wfd, "wb"), "child_rfd": child_rfd } except os.error, v: raise PythonDialogOSError(v.strerror) def gauge_update(self, percent, text="", update_text=0): """Update a running gauge box. percent -- new percentage to show in the gauge meter text -- new text to optionally display in the box update-text -- boolean indicating whether to update the text in the box This function updates the percentage shown by the meter of a running gauge box (meaning `gauge_start' must have been called previously). If update_text is true (for instance, 1), the text displayed in the box is also updated. See the `gauge_start' function's documentation for information about how to use a gauge. Return value: undefined. Notable exception: PythonDialogIOError can be raised if there is an I/O error while writing to the pipe used to talk to the dialog-like program. """ if update_text: gauge_data = "%d\nXXX\n%s\nXXX\n" % (percent, text) else: gauge_data = "%d\n" % percent try: self._gauge_process["stdin"].write(gauge_data) self._gauge_process["stdin"].flush() except IOError, v: raise PythonDialogIOError(v) # For "compatibility" with the old dialog.py... gauge_iterate = gauge_update def gauge_stop(self): """Terminate a running gauge. This function performs the appropriate cleanup actions to terminate a running gauge (started with `gauge_start'). See the `gauge_start' function's documentation for information about how to use a gauge. Return value: undefined. Notable exceptions: - any exception raised by self._wait_for_program_termination() - PythonDialogIOError can be raised if closing the pipe used to talk to the dialog-like program fails. """ p = self._gauge_process # Close the pipe that we are using to feed dialog's stdin try: p["stdin"].close() except IOError, v: raise PythonDialogIOError(v) exit_code = \ self._wait_for_program_termination(p["pid"], p["child_rfd"])[0] return exit_code def infobox(self, text, height=10, width=30, **kwargs): """Display an information dialog box. text -- text to display in the box height -- height of the box width -- width of the box An info box is basically a message box. However, in this case, dialog will exit immediately after displaying the message to the user. The screen is not cleared when dialog exits, so that the message will remain on the screen until the calling shell script clears it later. This is useful when you want to inform the user that some operations are carrying on that may require some time to finish. Return the exit status (an integer) of the dialog-like program. Notable exceptions: any exception raised by self._perform() """ return self._perform( *(["--infobox", text, str(height), str(width)],), **kwargs)[0] def inputbox(self, text, height=10, width=30, init='', **kwargs): """Display an input dialog box. text -- text to display in the box height -- height of the box width -- width of the box init -- default input string An input box is useful when you want to ask questions that require the user to input a string as the answer. If init is supplied it is used to initialize the input string. When entering the string, the BACKSPACE key can be used to correct typing errors. If the input string is longer than can fit in the dialog box, the input field will be scrolled. Return a tuple of the form (code, string) where `code' is the exit status of the dialog-like program and `string' is the string entered by the user. Notable exceptions: any exception raised by self._perform() """ (code, tag) = self._perform( *(["--inputbox", text, str(height), str(width), init],), **kwargs) tag = self._strip_xdialog_newline(tag) return (code, tag) def menu(self, text, height=15, width=54, menu_height=7, choices=[], **kwargs): """Display a menu dialog box. text -- text to display in the box height -- height of the box width -- width of the box menu_height -- number of entries displayed in the box (which can be scrolled) at a given time choices -- a sequence of (tag, item) or (tag, item, help) tuples (the meaning of each `tag', `item' and `help' is explained below) Overview -------- As its name suggests, a menu box is a dialog box that can be used to present a list of choices in the form of a menu for the user to choose. Choices are displayed in the order given. Each menu entry consists of a `tag' string and an `item' string. The tag gives the entry a name to distinguish it from the other entries in the menu. The item is a short description of the option that the entry represents. The user can move between the menu entries by pressing the UP/DOWN keys, the first letter of the tag as a hot-key, or the number keys 1-9. There are menu-height entries displayed in the menu at one time, but the menu will be scrolled if there are more entries than that. Providing on-line help facilities --------------------------------- If this function is called with item_help=1 (keyword argument), the option --item-help is passed to dialog and the tuples contained in `choices' must contain 3 elements each : (tag, item, help). The help string for the highlighted item is displayed in the bottom line of the screen and updated as the user highlights other items. If item_help=0 or if this keyword argument is not passed to this function, the tuples contained in `choices' must contain 2 elements each : (tag, item). If this function is called with help_button=1, it must also be called with item_help=1 (this is a limitation of dialog), therefore the tuples contained in `choices' must contain 3 elements each as explained in the previous paragraphs. This will cause a Help button to be added to the right of the Cancel button (by passing --help-button to dialog). Return value ------------ Return a tuple of the form (exit_info, string). `exit_info' is either: - an integer, being the the exit status of the dialog-like program - or the string "help", meaning that help_button=1 was passed and that the user chose the Help button instead of OK or Cancel. The meaning of `string' depends on the value of exit_info: - if `exit_info' is 0, `string' is the tag chosen by the user - if `exit_info' is "help", `string' is the `help' string from the `choices' argument corresponding to the item that was highlighted when the user chose the Help button - otherwise (the user chose Cancel or pressed Esc, or there was a dialog error), the value of `string' is undefined. Notable exceptions: any exception raised by self._perform() """ cmd = ["--menu", text, str(height), str(width), str(menu_height)] for t in choices: cmd.extend(t) (code, output) = self._perform(*(cmd,), **kwargs) output = self._strip_xdialog_newline(output) if "help_button" in kwargs.keys() and output.startswith("HELP "): return ("help", output[5:]) else: return (code, output) def msgbox(self, text, height=10, width=30, **kwargs): """Display a message dialog box. text -- text to display in the box height -- height of the box width -- width of the box A message box is very similar to a yes/no box. The only difference between a message box and a yes/no box is that a message box has only a single OK button. You can use this dialog box to display any message you like. After reading the message, the user can press the ENTER key so that dialog will exit and the calling program can continue its operation. Return the exit status (an integer) of the dialog-like program. Notable exceptions: any exception raised by self._perform() """ return self._perform( *(["--msgbox", text, str(height), str(width)],), **kwargs)[0] def passwordbox(self, text, height=10, width=60, init='', **kwargs): """Display an password input dialog box. text -- text to display in the box height -- height of the box width -- width of the box init -- default input password A password box is similar to an input box, except that the text the user enters is not displayed. This is useful when prompting for passwords or other sensitive information. Be aware that if anything is passed in "init", it will be visible in the system's process table to casual snoopers. Also, it is very confusing to the user to provide them with a default password they cannot see. For these reasons, using "init" is highly discouraged. Return a tuple of the form (code, password) where `code' is the exit status of the dialog-like program and `password' is the password entered by the user. Notable exceptions: any exception raised by self._perform() """ (code, password) = self._perform( *(["--passwordbox", text, str(height), str(width), init],), **kwargs) password = self._strip_xdialog_newline(password) return (code, password) def radiolist(self, text, height=15, width=54, list_height=7, choices=[], **kwargs): """Display a radiolist box. text -- text to display in the box height -- height of the box width -- width of the box list_height -- number of entries displayed in the box (which can be scrolled) at a given time choices -- a list of tuples (tag, item, status) where `status' specifies the initial on/off state each entry; can be 0 or 1 (integers, 1 meaning checked, i.e. "on"), or "on", "off" or any uppercase variant of these two strings. No more than one entry should be set to on. A radiolist box is similar to a menu box. The main difference is that you can indicate which entry is initially selected, by setting its status to on. Return a tuple of the form (code, tag) with the tag for the entry that was chosen by the user. `code' is the exit status of the dialog-like program. If the user exits with ESC or CANCEL, or if all entries were initially set to off and not altered before the user chose OK, the returned tag is the empty string. Notable exceptions: any exception raised by self._perform() or _to_onoff() """ cmd = ["--radiolist", text, str(height), str(width), str(list_height)] for t in choices: cmd.extend(((t[0], t[1], _to_onoff(t[2])))) (code, tag) = self._perform(*(cmd,), **kwargs) tag = self._strip_xdialog_newline(tag) return (code, tag) def scrollbox(self, text, height=20, width=78, **kwargs): """Display a string in a scrollable box. text -- text to display in the box height -- height of the box width -- width of the box This method is a layer on top of textbox. The textbox option in dialog allows to display file contents only. This method allows you to display any text in a scrollable box. This is simply done by creating a temporary file, calling textbox and deleting the temporary file afterwards. Return the dialog-like program's exit status. Notable exceptions: - UnableToCreateTemporaryDirectory - PythonDialogIOError - PythonDialogOSError - exceptions raised by the tempfile module (which are unfortunately not mentioned in its documentation, at least in Python 2.3.3...) """ # In Python < 2.3, the standard library does not have # tempfile.mkstemp(), and unfortunately, tempfile.mktemp() is # insecure. So, I create a non-world-writable temporary directory and # store the temporary file in this directory. try: # We want to ensure that f is already bound in the local # scope when the finally clause (see below) is executed f = 0 tmp_dir = _create_temporary_directory() # If we are here, tmp_dir *is* created (no exception was raised), # so chances are great that os.rmdir(tmp_dir) will succeed (as # long as tmp_dir is empty). # # Don't move the _create_temporary_directory() call inside the # following try statement, otherwise the user will always see a # PythonDialogOSError instead of an # UnableToCreateTemporaryDirectory because whenever # UnableToCreateTemporaryDirectory is raised, the subsequent # os.rmdir(tmp_dir) is bound to fail. try: fName = os.path.join(tmp_dir, "text") # No race condition as with the deprecated tempfile.mktemp() # since tmp_dir is not world-writable. f = open(fName, "wb") f.write(text) f.close() # Ask for an empty title unless otherwise specified if not "title" in kwargs.keys(): kwargs["title"] = "" return self._perform( *(["--textbox", fName, str(height), str(width)],), **kwargs)[0] finally: if type(f) == types.FileType: f.close() # Safe, even several times os.unlink(fName) os.rmdir(tmp_dir) except os.error, v: raise PythonDialogOSError(v.strerror) except IOError, v: raise PythonDialogIOError(v) def tailbox(self, filename, height=20, width=60, **kwargs): """Display the contents of a file in a dialog box, as in "tail -f". filename -- name of the file whose contents is to be displayed in the box height -- height of the box width -- width of the box Display the contents of the specified file, updating the dialog box whenever the file grows, as with the "tail -f" command. Return the exit status (an integer) of the dialog-like program. Notable exceptions: any exception raised by self._perform() """ return self._perform( *(["--tailbox", filename, str(height), str(width)],), **kwargs)[0] # No tailboxbg widget, at least for now. def textbox(self, filename, height=20, width=60, **kwargs): """Display the contents of a file in a dialog box. filename -- name of the file whose contents is to be displayed in the box height -- height of the box width -- width of the box A text box lets you display the contents of a text file in a dialog box. It is like a simple text file viewer. The user can move through the file by using the UP/DOWN, PGUP/PGDN and HOME/END keys available on most keyboards. If the lines are too long to be displayed in the box, the LEFT/RIGHT keys can be used to scroll the text region horizontally. For more convenience, forward and backward searching functions are also provided. Return the exit status (an integer) of the dialog-like program. Notable exceptions: any exception raised by self._perform() """ # This is for backward compatibility... not that it is # stupid, but I prefer explicit programming. if not "title" in kwargs.keys(): kwargs["title"] = filename return self._perform( *(["--textbox", filename, str(height), str(width)],), **kwargs)[0] def timebox(self, text, height=3, width=30, hour=-1, minute=-1, second=-1, **kwargs): """Display a time dialog box. text -- text to display in the box height -- height of the box width -- width of the box hour -- inititial hour selected minute -- inititial minute selected second -- inititial second selected A dialog is displayed which allows you to select hour, minute and second. If the values for hour, minute or second are negative (or not explicitely provided, as they default to -1), the current time's corresponding values are used. You can increment or decrement any of those using the left-, up-, right- and down-arrows. Use tab or backtab to move between windows. Return a tuple of the form (code, time) where `code' is the exit status (an integer) of the dialog-like program and `time' is a list of the form [hour, minute, second] (where `hour', `minute' and `second' are integers corresponding to the time chosen by the user) if the box was closed with OK, or None if it was closed with the Cancel button. Notable exceptions: - any exception raised by self._perform() - PythonDialogReModuleError - UnexpectedDialogOutput """ (code, output) = self._perform( *(["--timebox", text, str(height), str(width), str(hour), str(minute), str(second)],), **kwargs) if code == self.DIALOG_OK: try: mo = _timebox_time_rec.match(output) if mo is None: raise UnexpectedDialogOutput( "the dialog-like program returned the following " "unexpected time with the --timebox option: %s" % output) time = map(int, mo.group("hour", "minute", "second")) except re.error, v: raise PythonDialogReModuleError(v) else: time = None return (code, time) def yesno(self, text, height=10, width=30, **kwargs): """Display a yes/no dialog box. text -- text to display in the box height -- height of the box width -- width of the box A yes/no dialog box of size `height' rows by `width' columns will be displayed. The string specified by `text' is displayed inside the dialog box. If this string is too long to fit in one line, it will be automatically divided into multiple lines at appropriate places. The text string can also contain the sub-string "\\n" or newline characters to control line breaking explicitly. This dialog box is useful for asking questions that require the user to answer either yes or no. The dialog box has a Yes button and a No button, in which the user can switch between by pressing the TAB key. Return the exit status (an integer) of the dialog-like program. Notable exceptions: any exception raised by self._perform() """ return self._perform( *(["--yesno", text, str(height), str(width)],), **kwargs)[0] pythondialog-2.7/DEBUGGING0000644000175000017500000000177110025537174015065 0ustar gandalfgandalf # The following lines are useful for debugging: they write the # full command (with arguments quoted and environment # variables set) to a file named "command.debug" in the # current directory. See Dialog.__call_program() in dialog.py. import commands envvar_settings_list = [] if new_environ.has_key("DIALOGRC"): envvar_settings_list.append( "DIALOGRC='%s'" % new_environ["DIALOGRC"]) for var in _dialog_exit_status_vars.keys(): varname = "DIALOG_" + var envvar_settings_list.append( "%s=%s" % (varname, new_environ[varname])) envvar_settings = string.join(envvar_settings_list, " ") file("command.debug", "wb").write( envvar_settings + string.join(map(commands.mkarg, arglist), "")) pythondialog-2.7/setup.cfg0000644000175000017500000000013610024656350015457 0ustar gandalfgandalf[sdist] formats=bztar,gztar,zip [bdist] formats=bztar,gztar,zip [install] prefix=/usr/local pythondialog-2.7/MANIFEST.in0000644000175000017500000000013710115630246015372 0ustar gandalfgandalfinclude COPYING INSTALL AUTHORS TODO DEBUGGING demo.py include MANIFEST.in # global-exclude *~ pythondialog-2.7/AUTHORS0000644000175000017500000000023210115630137014677 0ustar gandalfgandalfPeter Astrand (current maintainer) Robb Shecter Sultanbek Tezadov (http://sultan.da.ru/) Florent Rougon pythondialog-2.7/setup.py0000755000175000017500000000445210115630734015357 0ustar gandalfgandalf#! /usr/bin/env python # setup.py --- Setup script for pythondialog # Copyright (c) 2002, 2003, 2004 Florent Rougon # # This file is part of pythondialog. # # pythondialog is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # pythondialog is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import os, string, sys from distutils.core import setup # Note: # The Distutils included in Python 2.1 don't understand the "license" keyword # argument of setup correctly (they only understand licence); as I don't want # to mispell it, if you run the Distutils from Python 2.1, you will get # License: UNKNOWN. This problem does not appear with the version included in # Python 2.2. PACKAGE = "pythondialog" VERSION = "2.7" def main(): setup(name=PACKAGE, version=VERSION, description="A Python interface to the UNIX dialog utility and " "mostly-compatible programs", # Doesn't work great with several authors... author="Robb Shecter, Sultanbek Tezadov, Florent Rougon, Peter Astrand", author_email="robb@acm.org, http://sultan.da.ru/, flo@via.ecp.fr", maintainer="Peter Astrand", maintainer_email="peter@cendio.se", url="http://pythondialog.sourceforge.net/", license="LGPL", platforms="UNIX", long_description="""\ A Python interface to the UNIX dialog utility, designed to provide an easy, pythonic and as complete as possible way to use the dialog features from Python code. Back-end programs that are almost compatible with dialog are also supported if someone cares about them.""", keywords=["dialog", "Xdialog", "whiptail", "text-mode interface"], py_modules=["dialog"]) if __name__ == "__main__": main() pythondialog-2.7/INSTALL0000644000175000017500000000404610115631574014675 0ustar gandalfgandalfREQUIREMENTS ------------ Python 2.2 or newer. INSTALLATION ------------ pythondialog is packaged with Distutils (the current standard way to package Python extensions), so its installation should be as simple as: - make this file's directory your shell's current directory - optionally edit setup.cfg to make sure that it fits your needs (particularly the installation prefix); in the case of the prefix, you could alternatively specify it later with the --prefix, --exec-prefix, etc. arguments of setup.py---these are described in detail in the "Installing Python Modules" chapter of the Python documentation. - a) 1) type: python ./setup.py build 2) then, as root: python ./setup.py install --record /path/to/foo where foo is a file of your choice which will contain the list of all files installed on your system by the preceding command. This will make uninstallation easy (you could ommit the "--record /path/to/foo", but uninstallation could not be automated, then). OR b) type, as root: python ./setup.py install --record /path/to/foo This will automatically build the package before installing it. The observations made in a) also apply here. If this default installation is not what you wish, please read the Distutils documentation. In Python 2.1 and above, it is included in the base Python documentation and the chapter you'll need is most probably "Installing Python Modules". UNINSTALLATION -------------- Provided you have followed the instructions given in the installation section, you have a /path/to/foo file that contains all the files the installation process put on your system. Great! All you have to do is: while read file; do rm -f "$file"; done < /path/to/foo under a Bourne-compatible shell and with the appropriate privileges (maybe root, depending on where you installed pythondialog). Note: this will handle file names with spaces correctly, unlike the simpler "rm -f $(cat /path/to/foo)". pythondialog-2.7/COPYING0000644000175000017500000006365010024656350014703 0ustar gandalfgandalf GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. ^L Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. ^L GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. ^L Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. ^L 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. ^L 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. ^L 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. ^L 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS ^L How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it!