Tutorial: Build a Portable Web Browser

Writing portable code has been a primary goal of programmers for many years. The idea that you can write your application once and use it almost everywhere appeals to a programmer’s sense of frugality, and avoids continually having to reinvent the wheel. Join us as we create a webkit-based browser on multiple platforms to prove just how easy it is.

Portability was the driving factor behind Java. In the words of the Java developers, it was designed to be as ‘architecture-neutral’ as possible. As a result, the Java language and its applications have gone on to change the face of computing, running on everything from mobile phones to NASA’s 3D reconstruction engines for the Mars Rover mission. But Java achieves this by using a virtual machine – a middle layer that translates the programmer’s instructions into machine-specific instructions on the fly. The advantage of this approach is that you only ever need to port the virtual machine to your platform, and you can immediately access your entire library of Java. The downside is that Java applications seldom feel like native applications, and there’s very little direct hardware control.

1. Find a toolkit

There’s nothing stopping you writing your portable applications using Python, Perl, Ruby or even C and C++. These languages are widespread, and you can find compilers for most platforms. But when your applications are of a certain size, portability becomes more than just a matter of finding a suitable compiler. It’s about being able use OS-specific components without writing OS-specific code. If your application has a main window, a toolbar and help system, for instance, you’d need a separate implementation for each platform. And that’s a lot of duplicated effort.

The answer to this problem is to use a portable programmer’s toolkit. This is typically an API – a series of pre-built functions and libraries – which can be compiled and used on any compatible platform. You program the main window, toolbar and help system code using the portable toolkit, and this can then be compiled on any other compatible platform with very little extra effort. Linux has several cross-platform toolkits, each with their own strengths and weaknesses. For example, the popular cross-platform instant messaging client, Pidgin, uses a toolkit called GTK+, which has been ported from Linux to Windows. One of the best cross-platform toolkits we’ve come across, however, is Qt.

2. The Linux Development Environment

Qt is the toolkit at the heart of the KDE desktop environment. It was developed by Trolltech before it was acquired by Nokia late last year. The great thing about Qt is that it’s both commercial and open-source. This means that it’s generally of a much higher quality than pure open-source solutions. It’s also packed full of features, and as long as you’ve got a little C++ experience, you’ll find it well documented and relatively easy to use. You could code a music player using just a handful of lines, for example. Thanks to its portability, you can recompile the same application on Windows, or even OS X, with very little extra effort.

Creating a Qt development environment on your Linux machine is straightforward. Most installations will include a working toolchain built around the GCU Compiler Collection (GCC). Type ‘make’ on the command line to see if it’s installed. If it isn't, simply find and install the GCC in your distro’s package manager. This will include everything you need to build C and C++ applications from your Linux desktop. Similarly, if you're using a recent distribution release, you’ll find development libraries for Qt 4 within your distro’s package manager. You will need to install these along with a tool called Qt Designer.

To check that everything is installed, type ‘qmake --version’ on the command line. You should see something similar to the following:

Using Qt version 4.4.3 in /usr/lib

This displays the version of Qt you’re using, as well as the location of the libraries. For our small project to work, you’ll need a version equal to or later than Qt 4.4.

Finally, we need to install one more piece of software. This is Qt Creator, a free Integrated Development Environment that makes creating graphical Qt applications considerably easier that typing lines of code by hand. The Linux version of Qt Creator is a large binary file that should be executed to install it into your home directory. Running the application is then as simple as navigating to that directory (‘qtcreator’), and running the qtcreator tool from the ‘bin’ directory. If you’re lucky, you may also find an icon for Qt Creator in your Development menu.

3. Create the GUI

With Qt Creator running, it’s now time to create our application. When Creator first starts, it begins by asking what kind of project you want to start. You need to select ‘Qt4 GUI Application’. This will populate Creator with a basic framework of code for a simple application. Clicking on the large green ‘Play’ button in the bottom left of the screen will compile the code and execute the application. You should see an empty window, which is where we’re going to dump some functionality.

Quit the application and go back to Creator. In the file list in the left panel, you’ll see five separate files. The first has a ‘.pro’ postfix – meaning project file – which is used by Creator to manage your project. The second file is ‘main.cpp’, the launch function for all C++ applications. Following this, there’s ‘mainwindow.cpp’ and ‘mainwindow.h’. These classes inherit the Qt classes within your project, and allow you to add your own functionality. Finally, there’s ‘mainwindow.ui’. This is an XML file that contains the various GUI elements within the application. Click on this file to open the GUI constructor within Creator.

We need three elements, all of which should be dragged from the widget palette in the left panel and onto the main window area in the middle of the screen. Add a ‘lineEdit’ widget, a ‘pushButton’ widget, and a ‘QwebView’. Double-click on the pushButton and change the text to something like ‘Go’. You can rearrange these widgets in the window. We’d recommend doing the following: hold down [CTRL] and select both the lineEdit and pushButton widgets, then select ‘Layout horizontally’ from the right-click Layout menu. Holding [CTRL] again, select this new grouped widget as well as webView, and click on 'Layout vertically’ in the same Layout menu. Finally, select the background window and click on ‘Layout in a grid’. All the widgets should now be adjusted into the scaling application window.

4. Write some code

The idea behind this application is that when the user clicks on pushButton, the web page pointed at in the lineEdit widget will be loaded into Qwebview. To add this functionality, we need to use what Qt calls a system of signals and slots. Clicking on the button will emit a signal, which will activate a slot in our main application to update the web site. But we first need to add the slot that will connect the two. Right-click on your application’s window background, and select ‘Change signals/slots’ from the context menu. A window will open listing all the signals and slots Qt pre-defines for the Window class of object. Click on the upper ‘plus’ symbol to add a new slot, and call this ‘updateWeb()’, before clicking on ‘OK’.

We now need to attach the clicked signal from the pushButton widget to the slot we’ve just created. Click on ‘Edit Signals/Slots’ from the Edit menu, then click on the button widgets and drag the cursor to the main window background and let go. That sets the source and destination. A new window will appear, from which you can select a signal on the button to attach to a slot in the application window. You need to select ‘clicked()’ for the signal, and our newly created ‘updateWeb()’ for the slot. Now the only thing left to do is add the actual code to perform the action. Click on the mainwindow.h header file, and add the following under the ‘~MainWindow();’ line:
private slots: void updateWeb();
Click on mainwindow.cpp, and add the following chunk of code to the bottom of the file:

void MainWindow::updateWeb(){QUrl url;url = ui->lineEdit->displayText();ui->webView->setUrl(url); }

Even if this is your first time using Qt, it’s easy to see what we’re doing here: when the button is clicked, we simply grab the text from the lineEdit widget, and use this as a new URL in webView. You can find out which signals, slots, classes and functions are supported by Qt’s widgets from the excellent documentation. Finally, save everything from the File menu and click on the ‘Run’ icon to build your application and make sure it displays web pages correctly.

5. Building on Windows

Before you quit Creator on Linux, click on ‘Clean Project’ from the Build menu. This will remove any system specific files for Linux. This is because we’re now going to build the same application for Microsoft Windows. First we need to create a working Qt development environment for Windows. Fortunately, Nokia/Trolltech provides Windows binaries of the Qt package which include the MiniGW compiler, pre-configured and ready to run. Ideally, you should try to get hold of the same version you were running on Linux. But if this isn’t possible, any later release should work. The installation can take a while, as the MiniGW compiler is downloaded as part of the installation process. MiniGW is a cut-down version of the GNU Compiler Collection we were using on our Linux system, and performs the same task – building an executable from the C++ source files of our project.

You will also need to add the locations of both the Qt and MiniGW installations to your Windows’ path variable. This can be done by opening the Control Panel, clicking on ‘System’ and selecting the Advanced tab. Click on the ‘Environmental variables’ button, select the ‘PATH’ variable in the top panel and click ‘Edit’. You will need to add the two locations, each separated by a semicolon. For example, we needed to add ‘;C:\Qt\4.4.3\bin;C:\MinGW\bin’. After that, you're ready to build your Qt application.

Open a command prompt and ‘cd’ to the directory that contains your Qt project. If you type ‘qmake -v’, you should see the same output we had on the Linux system. If not, then there’s likely a problem with your PATH variable. All being well, you now need to type ‘qmake -win32’ followed by the name of your ‘.pro’ file. This will regenerate the makefile, which itself contains the dependencies for the Windows system. The final step is now to type ‘make’, which will build your project using the contents of the makefile as a guide. A few moments later, you’ll find the Windows executable for your application tucked within the Debug directory. Congratulations - you’ve just created a cross-platform web browser!

This article originally appeared in Issue 280 of PC Plus.

Check out the an anime project solely made through Free and Open Source software click here.
To subscribe to the "Guy WhoSteals" feed, click here.
You can add yourself to the GuyWhoSteals fanpage on Facebook or follow GuyWhoSteals on Twitter.


Post a Comment

Related Posts Plugin for WordPress, Blogger...