Saturday, 15 December 2012

Vala #2: Creating Simple Applications

I'll assume that you have gone through the official tutorial and that you have worked with C,C++ or C# languages before. The code samples are pretty self-explanatory. I'll be providing comments for only those code segments that are not so obvious. First lets install the vala compiler by typing the following in a terminal window:
apt-get install valac libgtk-3-dev 
I'm assuming that you are using an Ubuntu/Debian system. If you are using something else then you'll need to do a quick search on the web for installing the vala compiler for your system.

Simple 'Hello World' program


Here's what a 'Hello World' program looks like in Vala.
int main() {
    print("Hello World\n");
    return 0;
}
Save this in a file named hello.vala and compile it with the command:
valac "hello.vala" -o hello
This will create an executable file named 'hello' in the current directory. Execute the file from a terminal:
./hello


Simple 'hello world' program using objects


Here's the same example written again using Vala's object-oriented features. The program will simply display the first argument that is passed to it.
class Example : GLib.Object {

    public static void main(string[] args) {
        var ex = new Example();
        if (args.length < 2)
            print("Hello World\n");
        else
            ex.display(args[1]);
    }

    void display(string message) {
        stdout.printf(message + "\n");
    }
}
Save this in a file named hello2.vala and compile it with the command:
valac "hello2.vala" -o hello2
Execute the program from a terminal:
./hello2 "Welcome to Vala"


Simple GUI application using GTK


Now that we are done with the customary "Hello World" examples, let's try creating something actually useful. We will create a GUI program for deleting the "Recent Documents" history on an Ubuntu/Debian PC.
using Gtk;

class MainWindow : Window  {

  public static int main (string[] args) 
  {
    Gtk.init(ref args);  //Gtk intialization

    var window = new MainWindow (); //Create a window
    window.destroy.connect (Gtk.main_quit); //Quit app after window is closed
    window.show_all (); //Makes all widgets visible

    Gtk.main(); //Start the main loop

    return 0;
  }

  public MainWindow()
  {
    this.title = "My First App";
    this.border_width = 10;
    this.set_default_size (250, 60);
    this.window_position = WindowPosition.CENTER;
    this.destroy.connect(Gtk.main_quit); //Quit app when window is closed

    var btnClear = new Button.with_label ("Clear Recent Documents");
    btnClear.clicked.connect (clear_history); //Connect event with function
    add(btnClear);  //Add button to window
  }

  public void clear_history () 
  {
    string HOME = Environment.get_home_dir ();

    try {
      Process.spawn_command_line_sync (@"rm $HOME/.local/share/recently-used.xbel");
      Process.spawn_command_line_sync (@"touch $HOME/.local/share/recently-used.xbel");
      messagebox_show ("Success", "Your recent documents history has been cleared");
    }
    catch (Error e){
      string msg = e.message;
      stderr.printf(msg);
      messagebox_show ("Error", msg);
    }
  }

  public void messagebox_show(string title, string message)
  {
    var dialog = new Gtk.MessageDialog(
   null,
   Gtk.DialogFlags.MODAL, 
   Gtk.MessageType.INFO, 
   Gtk.ButtonsType.OK, 
   message);
   
    dialog.set_title(title);
    dialog.run();
    dialog.destroy();
  }
}
We have written code for creating a simple window with a single button. The button's click event is connected to the function clear_history(). The clear_history() function executes commands for deleting a file in your home folder. This file contains the list of documents that were recently accessed by you.

Save this in a file named app1.vala and compile it with the command:
 valac --pkg gtk+-3.0 "app1.vala" -o app1 
The GTK3 library contains a collection of classes for creating widgets like windows and buttons. Since we are creating a GTK app, we need to link the executable with the GTK3 library (this is similar to adding a reference to a DLL file in C# project).

The '--pkg gtk+-3.0' argument tells the Vala compiler to do the linking. We can add multiple '--pkg' arguments for every library used by our application. You can refer to the Official ValaDoc Website for the full list of libraries that you can use in your projects.

I will recommend that you keep this webpage open in a web browser window when you are programming with Vala. It will let you quickly search for libraries and functions that you can use in your project. It contains the complete reference for everything you need to know about using the in-built classes and functions.

Execute the application from a terminal window:
./app1


Clicking the button will clear your 'Recent Documents' history.



Since this is a GUI program, we can also execute it by double-clicking the file from Nautilus or any other file manager. Executing it from a terminal window is better since you will be able to see the messages that the program writes to Standard Output (stdout) and Standard Error (stderr).

Hit the links below for some more GTK examples:
GTK Samples
More Code Samples

3 comments:

  1. Thanks for this, I've been looking for sample on how to use the GtkMessageDialog.

    ReplyDelete
  2. This is great, thanks for sharing this.

    ReplyDelete
  3. Good tuttorial but I have a simple question today all the linux distro comes with latest version of world most famous GCC compiler but you used vala compiler
    Sanjay (PHP Developer)

    ReplyDelete

If you are reporting an issue and commenting as an anonymous user, please leave your email address so that I can get in touch with you.