How to add a powerful graphical user interface to Perl scripts
As you have seen in various recent issues of Linux Journal, the Xforms library allows you to add a powerful GUI to your C or C++ programs using a simple, intuitive API. The functionality and elegance of Xforms GUI is comparable to Motif's, yet the Xforms libraries are free if used non-commercially. Thanks to Martin Bartlett (martin@nitram.demon.co.uk), the Xforms' GUI can be used from Perl scripts to run complicated graphical applications or to provide a simple “please wait while loading” status bar so the user doesn't get bored waiting (see Figure 1). This article will discuss how to install Xforms4Perl (version 0.5) and how to write a simple address book program with it.
In order to install Xforms4Perl, first you must have installed the following:
Perl version 5.003 (or higher), compiled to load libraries dynamically.
XForms Library, version 0.86 or 0.88, which can be found at http://bragg.phys.uwm.edu/xforms.
Next you need to obtain the source code for Xforms4Perl, which you can do from either the author's primary site, ftp://ftp.demon.co.uk/pub/perl/perl/, or any of the CPAN mirror sites under the directory /authors/Martin_Bartlett/. You can also get an RPM from ftp://ftp.redhat.com/pub/contrib or CPAN, and skip the next few sections.
Once you have Xforms4Perl downloaded, unpack it into a convenient directory (i.e., /usr/local/src) using tar zxvf Xforms4Perl-0.8.4tgz. This command creates the subdirectory Xforms4Perl-0.8.4.
Xforms allows for the support of OpenGL, and if you want to access it from Xforms4Perl, or if you need to modify some default paths or library locations, you will need to edit the Makefile.PL files located in the subdirectories X11/XEvent, X11/XFontStruct and X11/Xforms.
Then enter the X11 subdirectory and do the following:
Type perl Makefile.PL.
Type make.
Type make install (as root).
Copy fd2Perl to a directory that is in your PATH.
Once installation is complete, you can then start writing Perl code which uses Xforms. You might also check out some of the demos that come with PerlXForms, such as the author's XFtool which is similar to the Microsoft Office Toolbar. The rest of this article assumes you have an existing fundamental understanding of Xforms and Perl, although both are so easy to use you can probably pick them up from looking at a few examples.
In order to help explain how to use the Xforms4Perl Library, I will use as an example the development of a simple phone book application from start to finish. The best place to start is with the fdesign application that comes with the Xforms library. It allows you to build the components of your application visually. Rather than trying to figure out if your button should be 33 by 55 pixels or 30 by 50 pixels, you just draw it how you want it, and fdesign deals with all the numbers and details. In order to make things even easier, fdesign is able to output Perl code (thanks to the fd2Perl script mentioned above). We invoke fdesign as fdesign -perl, and create a new form called “list” (see Figure 2).
First, we add an object called browser where the phone book name entries get indexed. Under the attributes section, we specify that we want this to be a HOLD_BROWSER, which allows a selection from the browser to remain highlighted after selection. Then we give it an obvious name, such as browser, and set up a callback function. This function will be executed when some action takes place in the browser—using callback functions is fairly standard in programming GUIs. We randomly pick the name browser_clicked for the callback function.
We now add five text input fields, all with the same callback function, named data_change. These fields will display the personal information from the phone book entries and are also the locations where the user can make data modifications. These fields are labeled and given the following names in the attributes section:
Label | Name |
Name | name_field |
Phone Number | phone_field |
Address | address1_field |
Address | address2_field |
email_field |
Next, we add four buttons. A pull-down menu could have been used here, but four buttons shouldn't clutter the interface and will be easier to access than a menu. The buttons are labeled “Quit!”, “Clear”, “Update” and “Delete Entry”. The purpose of the Quit button should be obvious. The Clear button is used to clear the text input fields, the Update button is used to save or update whatever is in the text input fields, and the Delete Entry button is used to remove the selected entry from the browser listing. These buttons each have a callback, as listed below.
Finally, we can add a title such as “PhoneBook” or anything else to improve the appearance, which is quite simple to do using fdesign—you just place it and you're done. I also thought it might be nice to give some of the buttons a shadow effect, which is done from the respective button's attributes menu.
Now we have finished designing the application, and we can save it as a file called pbook. This operation generates four (or more, based on how you set it up) files. The one of interest to us is called pbook.pl (Listing 1). If we ever want to modify our design, the .pl file is regenerated; thus, we should not modify this file, as any changes to it would be lost. Rather, in our code, we need to require the file to set up our form for us.
For a Perl script to use Xforms4Perl, all you have to do is add the line:
use X11::Xforms;
to the top of your Perl script. This command dynamically loads everything that needs to be loaded. If you want to access the XFontStruct or XEvent structures, then you will also need to add use X11::XFontStruct or use X11::XEvent. Before doing anything involving the Xforms library, you must call a function so that Xforms can initialize all of its internal variables, etc. This is done by calling
fl_initialize('Phone Book');and giving it the title of the application you want. You set up all the forms you need by making calls to subroutines, such as:
create_form_list();which have been generated by fdesign and fd2perl. Then, add whatever initialization code you need. For example, if you make a “slider” using fdesign and need to set the range of values of the slider based on some input, you will need to call fl_set_slider_bounds with the proper parameters. After you have finished configuration, you're ready to show the form to the user. To accomplish this, make the call:
fl_show_form($list,FL_PLACE_FREE,FL_FULLBORDER, "Phone Book");There are also commands to make the form disappear, so it's fairly easy to handle multiple forms. The options you feed fl_show_form include the specific form you wish to display (remember we called ours “list”), options for the window manager and a title. Once everything is set up and you're ready for the user to interact with the GUI, you then keep calling the function fl_do_forms. Thus, the minimal amount of code you need to display this form is:
#!/usr/local/bin/perl use X11::Xforms; require "pbook.pl"; fl_initialize('Phone Book'); create_form_list(); fl_show_form($list, FL_PLACE_FREE, FL_FULLBORDER, 'Phone Book'); while(1) {fl_do_forms};The actual interaction the user has with the GUI is accomplished via callback functions. Keep in mind this represents the bare essentials of a basic mode of using Xforms4Perl, and there are many other ways of using the libraries. The Xforms manual should be consulted for more advanced methods.
Let's look at how our phone book program is now pieced together. A full listing can be found in Listing 2. First, look at the entire main routine. In addition to the above listing, we've added the calls to two subroutines to initialize the browser before displaying it with the fl_show_form function.
load_data(); update_browser()
As you can see, most of the program is handled in subroutines. First, we load the libraries and initialize the program. The call to create_form_list sets up the form we pieced together using fdesign. The call to load_data loads the data from a file in the user's home directory called .pbook. The format for this file has been arbitrarily set up to contain one phone book entry per line with the data delimited by colons. (Assume the user would never use a colon in any entry. See Figure 3.) A sample entry (one line) from .pbook would look like this:
Suhad:414 555-1234:2014 S 102nd St:Milwaukee, WI 53227:sniazi@ucsd.edu
Now that the data is loaded, the update_browser call clears the browser and adds the newly loaded names to the browser list. To show the phone book to the user, we make the call to fl_show_form, and then loop through fl_do_forms to let Xforms take over.
The rest of the interaction with the user is handled through callbacks, which include adding or updating entries, saving the new entries, displaying information and quitting the application. The complete code is shown in Listing 2, and it's fairly evident how the callbacks work together, given Xforms' verbose function names. For example, fl_get_input gets the data from an input field, and fl_set_input sets it to some value. To get a better feeling for all the functions available, you can print out the 200-page manual that comes with Xforms; it makes an invaluable reference.
Although it should be fairly easy to guess what the code in Listing 2 does, there are a few things I'd like to mention and clarify. First of all, when the data is loaded, it is kept in a data structure called $DATA which is a pointer to an anonymous hash containing the names of the people in the address book. In turn, each of those names is a pointer to another anonymous hash containing the phone number, address, etc. For example, to access Tom's phone number, you would use $DATA->{'Tom'}->{pnumber}. Because we chose to handle the storage and organization of data using this method, we run into a slight problem. If we modify the name of an entry (i.e., change Tom to Tommy), the program thinks it is dealing with a new entry (because the hash's key is changed), and thus, two entries are made: one based on the name Tom and one based on the name Tommy. I leave it as an exercise for the reader to find a solution for this problem.
Most subroutines use either the fl_set_input or fl_get_input calls to manipulate the data you see. The only complicated call is
$name=fl_get_browser_line($browser, fl_get_browser($browser));
This call is used to determine the highlighted name from the browser. For example, in Figure 2, the highlighted name is Suhad. In order to do that, we need to give fl_get_browser the line number in which the entry appears. To get that number, we make a call to fl_get_browser_line which returns with the current highlighted line number.
Another thing to note is that rather than having a “save” button, this phone book assumes you wouldn't make a mistake. Thus, it saves the data every time you click on either the Update button or the Delete Entry button. A backup of the last saved file is kept as .pbook.bak in case of a problem, but the user has to restore the backup himself—it's not automatic.
All listings referred to in this article are available by anonymous download in the file ftp.linuxjournal.com/pub/lj/listings/issue55/2024.tgz.