FXRuby is a powerful library for developing cross-platform graphical user interfaces (GUIs). It is based on the FOX toolkit (an open source, highly optimized library written in C++) and offers Ruby developers the possibility of coding applications in the language they love, whilst at the same time taking advantage of FOX’s underlying performance and functionality.
In this article, I’m going to show you how to get up and running with FXRuby, introduce you to some of the more commonly used widgets, and demonstrate how to build a simple application with some real world value.
Presuming you have Ruby 1.9 installed on your machine.
gem install fxruby
sudo apt-get install ruby1.9.1-dev g++ libxrandr-dev libfox-1.6-dev
sudo gem install fxruby
Mac OS X:
sudo gem install fxruby
If you run into any trouble, more detailed instructions can be found here: https://github.com/lylejohnson/fxruby/wiki
So, let’s start off with the customary “Hello, World!” application.
To do this create a new file on your computer, name it ‘hello_world.rb’ and enter the following code:
Run this file with the command ruby hello_world.rb and you should see something like this:
Let’s examine what the above code is doing:
- We start by requiring the fox16 library.
- All of FXRuby’s classes are defined within the Fox module, so including Fox in our program’s global namespace removes the need to precede these classes with a
- We then create an instance of the
FXAppclass (where App stands for Application Object). The
FXAppinstance is central to an FXRuby program and has many important tasks, such as managing the event queue and handling signals.
- Next we create an instance of
FXMainWindow, passing it the previously constructed
FXAppobject as the first argument. This associates the window we’re creating, with our application. We also pass it three further arguments: window title, window width and window height.
- A call to
FXApp#createensures that the application’s window gets created.
- Windows are however invisible by default in FXRuby, so we need to call
FXMainWindow#showfor it to be displayed. The argument
PLACEMENT_SCREENensures that it is centred on the screen.
- Finally, we start the program’s main loop by calling the
FXApp#run. This method will not return until the program exits.
Time for a little refactoring
Although the above code works just fine, it isn’t very Ruby-like and as you start to add widgets to your application, things quickly become cluttered. Therefore, a common idiom in FXRuby is to create your application’s window as a subclass of
FXMainWindow, like so:
You notice, that we have defined a
create method within our
HelloWorld class. We need this as when we call
FXApp instance will in turn call the
create method of all of the windows with which it is associated. We can also use this method to have our new
HelloWorld object call
show on itself after it has been created.
Another popular FXRuby idiom is to move the
HelloWorld construction into a start-up block, like so:
__FILE__ is the name of the current file and
$0 is the name of file where execution started. By comparing the two, we can ensure that our file is the main file being run, rather than it having been required or loaded by another file. This is definitely overkill for such a small app, but serves to demonstrate the typical style of an FXRuby program.
Something a bit more exciting
“Hello, World!” apps are great, but let’s move on to something with a little more practical value. In this next section I’m going to show you how to make a simple password generator, which, at the push of a button, will output a random password of an arbitrary length.
Before we start coding, let’s take a moment to consider which elements should be present in our GUI. We’ll need a text field into which the user can type the length of the desired password. We’ll also need a check box, so that the user can opt to include special characters in the password. The password itself should be displayed on some sort of text area and finally we’re going to need two buttons: one to generate the password and one to copy it to the clipboard.
Here is a simple mock-up of what our GUI should look like:
In FXRuby we use layout managers to control the position and size of the widgets. In this case I am going to use objects of the class
FXHorizontalFrame (which arranges its children horizontally) and
FXVerticalFrame (which arranges its children vertically). The first argument for each of these layout managers is its parent window. I also pass a layout hint to the vertical frame (
LAYOUT_FILL), which tells it to take up as much space as is available to it, both horizontally and vertically.
To create the widgets themselves I will use instances of the following FXRuby classes:
FXLabel– to create a label on which we can display some text
FXTextField– to create a text field into which the user can type a single line of input
FXCheckButton– to create a check button to allow the user to select or deselect an option
FXText– to create a text area to display the output
FXButton– to create a pushable button to execute a command
If you run this code on your computer you should see the skeleton of our application, looking something like this:
Generate a random string based on user input
To create our password we can use Ruby’s
Integer#chr method, which returns a string containing the character represented by the receiver’s value. If the user wants to include special characters in their password, then we can use any of the 93 characters from 33-126 on the ASCII chart. Otherwise we stick to values 48-57, 65-90 and 97-122 which represent numbers 1-9, uppercase A-Z and lowercase a-z respectively.
p generatePassword(25, numbers + alphabetLowerCase + alphabetUpperCase)
p generatePassword(25, allPossibleChars)
Of course, to remember such a long and random password you will need to be using a password manager such as KeePass, but everyone does that anyway, right? :-)
Connecting the two
So, we’ve got the skeleton of our GUI up and running and our
generatePassword method is doing what it should. It’s time to connect the two.
In FXRuby we use the
connect method to associate a user actions, such as mouse clicks, with blocks of code. In the case of
FXButton it sends a
SEL_COMMAND message to its target when it is clicked. The syntax is as follows:
Let’s apply this to our code.
You will notice that in the
generateButton.connect block I have done the following:
- I have added a line to clear the
FXTextwidget in which we want to display our output. If we didn’t do this, then every time we generated a new password, it would be appended to the old one.
- I then append the result of calling
generatePasswordto the now blank
- I call
generatePasswordwith the argument
chrTextField.text.to_i. This is the integer value of whatever the user has entered into the text field.
Now let’s give the user the ability to select if they want special characters to be included in the password, or not. The most straightforward way to do this is to declare an instance variable
@includeSpecialCharacters, which we can initialize to
false. Then we can connect our check box to a block of code that will update the value of this instance variable (by xoring its value with
true) whenever the box is selected or deselected.
I have also included a second method called
chooseCharset, which recieves
@includeSpecialCharacters as an argument and returns an array containing the set of characters from which the password is to be constructed.
The character sets themselves are passed to the
PasswordGenerator object upon initialization and are available in the instance variable
generatePassword method will, in turn, take the array returned by
chooseCharset as an argument and generate the password accordingly.
The finishing touches
It would be nice if the user could copy the generated password to the clipboard at the push of a button. Luckily the
FXText widget provides clipboard support out of the box (i.e. you can copy its text to the clipboard using Ctrl + C) and it doesn’t take much additional code for us to interact with the clipboard programmatically.
The first thing to do is to call
FXWindow#acquireClipboard when the ‘Copy to clipboard’ button is pressed:
We pass the method an array containing
FXWindow.stringType (one of FOX’s pre-registered drag types), to indicate that we have some string data to place on the clipboard. If successful the
acquireClipboard method will return
Now, whenever another window requests the clipboard’s contents FOX will send a
SEL_CLIPBOARD_REQUEST message to the current clipboard owner. As we called
acquireClipboard on the main window, the main window is now the owner of the clipboard and needs to respond this message type:
setDNDData method takes three arguments. The first tells FOX which kind of data transfer we’re trying to accomplish, the second is the data type and the last is the data itself.
With this done, I’m going to make two small changes to the layout of the GUI. Firstly, I’m going to place the
FXTextField and the
FXCheckButton in a group box and secondly I’m going to give the two buttons a uniform width.
The groupbox will be an object of the class
FXGroupBox. It is a layout manager and, as is the case with the other layout managers, its first argument specifies its parent window. It also accepts various layout hints as additional arguments. Here I have used
LAYOUT_FILL_X which give it a ridged frame and tell it to occupy as much space as is available to it horizontally. To add some outer padding to the groupbox, I have introduced an object of the class
FXPacker which will encapsulate all of the other layout managers.
Giving our two buttons a uniform width is slightly easier. We just include the layout hint
PACK_UNIFORM_WIDTH when creating the
FXHorizontalFrame which is their direct parent.
A final bug fix
In Ruby 1.87 entering a negative number into
chrTextField caused the interpreter to enter an endless loop. To avoid this problem we can pass
[0, chrTextField.text.to_i].max as a first argument to
generatePassword which will then take the value of 0 or whatever the user entered, depending on which is higher.
Here’s the final code
I hope that in this article I’ve been able to give you a comprehensive overview of how FXRuby works and demonstrate the ease with which you can create a cross-platform graphical user interface in the language you love. I’d like to finish by presenting several resources which have helped me enormously when using this library:
- FXRuby – Create Lean and Mean GUIs with Ruby, by Lyle Johnson (creator of FXRuby) – http://pragprog.com/book/fxruby/fxruby
- FXRuby on github – https://github.com/larskanis/fxruby (Lars Kanis is the current maintainer)
- FXRuby’s documentation – http://rubydoc.info/github/larskanis/fxruby/1.6/frames
- The FXRuby mailing list (low traffic, but a good place to ask questions) – http://rubyforge.org/mail/?group_id=300