As Big As This

Alalalalala

Sorry I haven’t been posting….

Hello Everyone,

Sorry I haven’t been able to post as much as I’ve been wanting to. I’ve been studying a lot, and well, just very busy. I do have a little good news, I’m trying to make a “Pong” like game in Gtk+, and when it’s done, I’ll post the source code for everyone to see 😀

June 25, 2009 Posted by | GTK Programming | , , | Leave a comment

Why Gtk+ May be the Greatest GUI Toolkit Ever!

This is an article I wrote a while back, it’s been published an spread around a little.

When it comes to programming a lot of people look to C/C++ for answers. They’re pretty straightforward languages that are general-purpose(they aren’t really good at anything in particular, but can be used to do just about anything). The only strike against these languages is that unlike Java, they don’t bring a GUI API built in. Instead, C/C++ coders must rely on other libraries and even system APIs to get the job done.

Introduction
Nowadays almost every application has to have a GUI. Users rely on graphical interfaces, and a programmers job isn’t only to code up an app, but to also make it best for the consumer. Now this leads one to wonder, “What should I use to make the GUI part of my program?”.

Well, the answer isn’t always straightforward, but there is one toolkit that looks a little better than the rest. It’s Gtk+. GTK+, or The GIMP Toolkit, is a cross-platform GUI toolkit and, is one of the most popular toolkits for the X Window System, along with Qt.

So what makes Gtk+ so speacial? Why could it possibly deserve the title of “Greatest GUI Toolkit Ever”? That is the point of this article. Here we will discuss a little bit about it, and see why it is a very good choice for developers.

1. Simple Syntax
One of the best features of Gtk+ is its simplicity of syntax. Almost everything is predefined, you just gotta point everything in the right direction.

For example, this little snippet below creates a pretty basic window (300px wide, 150px high, aligned to the center of screen, and says “A Window” in the titlebar):

#include

int main( int argc, char *argv[])
{
GtkWidget *window; // creates the window object

gtk_init(&argc, &argv); // this handles commandline arguments, don’t worry to much about it

/* Here we setup the window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 300, 150);
gtk_window_set_title(GTK_WINDOW(window), “A Window”);

gtk_widget_show(window); // this makes it appear

gtk_main(); // this puts the program in a loop waiting for events

return 0;
}

Amazing. That was all done in about twenty lines of code, and you could even reduce that more by getting rid of whitespace. Just for fun, I tried making something similar in Win32; my result was more than 70 lines of code, and that was just for the basics.

In case you’re wondering why you would choose a toolkit just because of syntax ease (or if you should even care), you must consider that the easier it is to write a program, the easier it would be to take care of it, as well as find bugs. As you will see later, Gtk+ has many features that help to make maintenance easier.

2. Great Structure
Not does only does Gtk+ have sytax that’s easy to follow, but is also designed in a way that makes it easier to work with. For example, you define the objects and widgets (a button or window, or dialogue), you pass it parameters and set it up, and you then either pack it into the window, or a box etc. Then all that’s left is to make it show up. Of course a real application would have callbacks so that widgets would respond to events, but still that’s pretty good.

It’s structure like this that helps programs for becoming “code soup” and lets developers worry less about “how they’re gonna setup the application”, and more about “when they are gonna code that badboy up”.

3. Lightweight and Fast
One of the best things about Gtk+ is its weight and execution times. This toolkit is especially good if resources are a concern to you. Applications written with Gtk+ are far less likely to crash due to not enough memory, freeze up, etc.

Here’s a good example: I’m working on creating a open source project right now. So far all I’ve coded is the GUI, and while I still have a long way to go before it has full functionality, the bare-bones app is only 30.4KB and executes in well under a second. Now it’s been a while since I’ve done a lot in Win32, but from what I remember even very simple applications were in the “200KB” range. That’s more than 6 times as big. In the long run, that could really add up.

4. Portable
Last but not least is the fact that Gtk+ is portable. It’s pretty much write once, work anywhere (Of course the users have to have the right stuff to run you’re program, but this generally wouldn’t be an issue).

This is a great thing for programmers. A lot of programmers are turning to Java because of its “multi-platformism”; but this gives C/C++ coders a real alternative to learning a whole new language, or having to be greatly limited by another language. The portability of Gtk+ is a truly great advantage and is also a good explanation for success of toolkits like “WxWidgets” and “QT”

Conclusion
In conclusion I hope you considered many of the things I’ve mentioned here, and are now looking into getting to know/use Gtk+. My goal here was to show you that Gtk+ is an amazing resource for C/C++ developers, and I hope I did so in as best as I could. If you find any errors, or have any suggestions, etc. please comment (I love it when people comment :D).

June 6, 2009 Posted by | GTK Programming | , | 1 Comment

We Have A New Writer

Negavite posted a comment the other day on one of my posts telling me that he could contribute his knowledge and experience in GTK+ programming.

The reason I started this blog was to keep track of my own progress, as well as maybe providing some useful information to the Internet community by sharing my learning experiences.

Naturally, I told Negavite that yes, he would be welcome to contribute articles to this blog. Because what helps me learn GTK+ will undoubtedly help others as well.

So, without further ado, here’s Negavite (on the next post) with his introductory first article!

June 6, 2009 Posted by | Ramblings | 1 Comment

Changing the Basic Window

In the last lesson, we learned the basic structure of a GTK Window. We also learned how to set the text that appears in the title bar. This time, we’ll go a small step further; we’ll change the window size as well as its position, set an icon for our program, create a basic menu, and finally destroy the program properly,

Center and Set Window Size

The code to do this is:

gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

You may have already guessed, 400 is the width and 300 is the height, which we will set as the default size of our window. For the initial position, you may have noticed that one of the parameters is the constant GTK_WIN_POS_CENTER, which, you guessed it, centers the window.

Set Window Icon

The following is the function used for setting the window icon, using 2 parameters: the window, and a Gdk Pixelbuffer object.

gtk_window_set_icon(GTK_WINDOW(window), pixbuf);

The problem is converting your desired graphic into something useable as an icon. Here we borrow a function from Zetcode’s First Programs tutorial (see References) which accepts a filename as a parameter and returns a GdkPixbuf object:

GdkPixbuf *create_pixbuf(const gchar * filename)
{
GdkPixbuf *pixbuf;
GError *error = NULL;
pixbuf = gdk_pixbuf_new_from_file(filename, &error);
if(!pixbuf) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
}
return pixbuf;
}

The gdk_pixbuf_new_from_file() functions takes two parameters–the filename of the image, and a GError object where it’ll put an error message if something goes wrong. It automatically detects the filetype of the file and convert it into a GdkPixbuf object.

We make a call to the create_pixbuf() function as follows:

gtk_window_set_icon(GTK_WINDOW(window), create_pixbuf("mylogo.gif"));

You can replace mylogo.gif with your own GIF, PNG, BMP, or JPG file.

Create a Menu

As mentioned in the first post, GTK uses hierarchies and containers quite extensively, and menus and submenus are no different. A menu is basically a container where you can put in items or even other containers i.e. submenus. The basic logic behind putting a menu into your GTK application is that the window itself is a container, and you attach a box container that will hold your menubar (itself a container), which will hold your menu (another container), which holds your menu items or even submenus (yet another container).

I did not grasp this relationship immediately when I studied it, so here I present the sample code relating to that hierarchical relationship. It may not be the best coding standard (personally, I prefer to put all my variable declarations together at the beginning), but for the sake of easier understanding, we’ll put relevant objects as they are needed and being built.

First, we create the menu items like so by creating new GtkWidgets and initializing them like so:

//Initialize the File menu items
GtkWidget *file;
GtkWidget *open;
GtkWidget *quit;
file = gtk_menu_item_new_with_label("File");
open = gtk_menu_item_new_with_label("Open...");
quit = gtk_menu_item_new_with_label("Quit");

Next, we create the File menu to hold our menu items:

//Initialize File menu and put in the menu items
GtkWidget *filemenu;
filemenu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), filemenu);
gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), open);
gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quit);

Take note that we are actually setting first item (file) as a submenu. The open and quit menu items are then added to the filemenu using the gtk_menu_shell_append() function.

Next, we put our File menu into the menu bar:

//Initialize the menu bar and put in the File menu we created
GtkWidget *menubar;
menubar = gtk_menu_bar_new();
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), file);

Now that everything’s almost set, we have to put our menubar on to the window itself:

//Put the menu bar into the window
GtkWidget *vbox;
vbox = gtk_vbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 3);

vbox is initialized into a GtkVBox object, which is a vertical container box. No, I don’t know either why they called a horizontal-looking box a vertical container box. I guess we’ll learn that soon enough. Anyway, gtk_container_add() adds the vbox container to the window (our big, main container) and gtk_box_pack_start() packs our menu bar into our box.

Closing the Window Properly

In our last lesson, although clicking on the close button makes the window disappear, it doesn’t actually destroy the program. We have to connect the destroy signal to the gtk_main_quit function().

g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

If you noticed, the Quit button doesn’t close our program, even if we have just set the callback for the destroy signal event. That’s because the Quit menu item is just a menu item like Open. Until we tell it what to do, it does nothing. The signal we actually have to listen for is not the destroy signal, but the activate signal, which is sent whenever you click on a menu item. So we connect the quit object’s “activate” signal to the gtk_main_quit() function, which we already know will terminate our program nicely.

g_signal_connect(G_OBJECT(quit), "activate", G_CALLBACK(gtk_main_quit), NULL);

Summing Up

Our program which contains the previous Hello Wolrd lesson, as well as the new window size and position, icon, menu, and proper destruction on exit should look something similar to this:

#include <gtk/gtk.h>

GdkPixbuf *create_pixbuf(const gchar * filename)
{
GdkPixbuf *pixbuf;
GError *error = NULL;
pixbuf = gdk_pixbuf_new_from_file(filename, &error);
if(!pixbuf) {
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
}
return pixbuf;
}

int main (int argc, char **argv) {
gtk_init(&argc, &argv);

//Basic Window Setup
GtkWidget *window;
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Hello, World");
gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_icon(GTK_WINDOW(window), create_pixbuf("mylogo.gif"));

//Initialize the File menu items
GtkWidget *file;
GtkWidget *open;
GtkWidget *quit;
file = gtk_menu_item_new_with_label("File");
open = gtk_menu_item_new_with_label("Open...");
quit = gtk_menu_item_new_with_label("Quit");

//Initialize File menu and put in the menu items
GtkWidget *filemenu;
filemenu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), filemenu);
gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), open);
gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), quit);

//Initialize the menu bar and put in the File menu we created
GtkWidget *menubar;
menubar = gtk_menu_bar_new();
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), file);

//Put the menu bar into the window
GtkWidget *vbox;
vbox = gtk_vbox_new(FALSE, 0);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 3);

//All set. Display all.
gtk_widget_show_all (window);

//Connect the destroy signal to the gtk_main_quit() function
g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);

//Connect the "quit" object's "activate" signal to the gtk_main_quit() function
g_signal_connect(G_OBJECT(quit), "activate", G_CALLBACK(gtk_main_quit), NULL);

gtk_main();
return 0;
}

References:

October 19, 2008 Posted by | GTK Programming, GTK Tutorials | 5 Comments

Saying Hello World With GTK

So now we’ re going to start nice and easy by making a common, household Hello World application. Here I’ll lay out a bare-essentials GTK application which I will try to explain as breifly as I can so fire up your text editor and create a base.c file:

This tells your compiler to include the gtk header files which includes the variables, structures, and other neat stuff in the GTK toolkit.

#include <gtk/gtk.h>

Here we have your main application function declaration. It has two parameters, which are pretty much standard:

int main(int argc, char **argv)
{

Here we declare an instance of GtkWidget which is a storage type for widgets and we’ll name it window:

GtkWidget *window;

Next, we call gtk_init, which as the name implies initializes GTK, initializing such stuff like color space, libararies, default signal handlers, etc. Here we see argc and argv again, which contain the arguments passed from the command line. gtk_init parses these arguments for special reserved arguments and removes them from the argument list. That’ll be useful in our future programs, so take note:

gtk_init (&argc, argv);

This creates a new window:

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

And this one shows the window:

gtk_widget_show (window);

Last, but certainly not the least, calling this gets us into the main processing loop:

gtk_main ();

And, then we elegantly close off our function

return 0;
}

Ok, put that all together and compile using the following basic compile command:

gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0`

After it compiles, you’ll have a program that you can either double-click, or in terminal type

./base

This will open up a window with the default 200×200 size because we didn’t specify a size. But wait, it say’s base on it’s title bar, not “Hello World”! Yes, that’s just the bare-essential base application we did. We need to add these right before gtk_window_show:

gtk_window_set_title (GTK_WINDOW (window), "Hello, World");

Compile it again, and we have our extremely easy Hello World program.

Hello World In Three Flavors

In one of my previous posts I mentioned that GTK is language-neutral, so you may be wondering why this code looks an awful lot like C. That’s because I prefer to code in C, but you can just as easily code this in C#, Ruby, Perl, or others by referring to the GTK Hello World In Six Different Languages article on which this tutorial was based on. Just scroll down and click on the link in my references below.

Next >> Changing The Basic Window

References:

February 29, 2008 Posted by | GTK Programming, GTK Tutorials | Leave a comment

Setting Up Your GTK Workspace

Alright, so onto the meat of things! Before any of the magic happens, I need to set up my system so that I can actually build something.

Several months ago, I first tried doing this by reading the GTK Tutorial (also in my links), and it said I needed to download GTK source from the GTK website and install it from source. Needless to say, I had too much power in my hands than I knew what to do with and I trashed my Ubuntu box. Ok, so we’ll do this the easy way: Synaptic

Installing GTK Packages Via SynapticOpen up your Synaptic Package Manager and look for libgtk2.0-0, it should already be installed. Check to be sure. There should be several similar packages already installed, but the most important package is the libgtk2.0-0-dev. Hmm, I’ll install libgtk2.0-0-doc for good measure as well. Iwas going to install the libgtk2.0-0-dbg, too, but the package description says most people won’t need this, so scrap that.There are several more, but I think this is enough to get started.

After marking the packages (Synaptic will prompt you that it needs several more packages to install libgtk2.0-0-dev), click on the Apply button and we’re done! Man, this tutorial could be more interesting if it was just a little bit harder. On the other hand, at least I’m sure this won’t trash my desktop. Oh well.

[Edit] I forgot to say thanks to Kostkon and Compyx in the Ubuntu Forums for pointing me in this direction. Thanks!

Next >> Saying Hello World with GTK

February 28, 2008 Posted by | GTK Tutorials | Leave a comment

A Short Introduction to GTK

What is GTK And Why Would I Want To Learn It?

I’ll try to keep this really short. First, GTK stands for the Gimp Toolkit and is the main toolkit used by GNOME (GNU Network Object Model Environment), although it is an object-oriented cross-platform toolkit that can be used to create applications independent of GNOME. Why is it called the Gimp Toolkit you ask? Well, it was originally written for the Gimp (GNU Image Manipulation Program, basically the equivalent of Photoshop in Linux). But since GTK had support for several languages, GTK was chosen as the toolkit for GNOME.

It uses LGPL, which means you won’t have to pay a penny for licenses and royalties, EVEN IF you’re program is not for personal or educational use e.g. commercial, paid programs. Programming with a toolkit allows your program to integrate well with your GNOME desktop, which means your program will have the same look and feel as your desktop theme. The toolkit also features high-level and easy to use widgets which are built on the concept of hierarchies and containers, which I’ll probably find out to be more useful than I think (think class hierarchies and inheritance, change the parent, change the children, et cetera).

Well, that was longer than I had wanted. So without further ado, I’m just gonna dive in and get ready to set up my GTK workspace.

Next >> Setting Up Your GTK Workspace

February 28, 2008 Posted by | GTK Programming | Leave a comment

As Big As This

I created this blog as a sort of personal journal in which I would write all my discoveries as I try to learn how to program an application in GNOME using GTK, from scratch. While I’ve been coding in quite a few languages, I am not adept at GUI programming, mostly working on the internal subsystems of a software project.

Thus I am hoping that by putting this blog up I can more easily monitor my progress (via frequency of my posts) and track what I have learned so far. I’ll be making a syllabus page somewhere, outlining what I plan to learn and accomplish, and use that page to link to the individual posts as they are created. If there are some out there who might find this information useful, or who would like to contribute to this undertaking, you are all welcome. Please leave me a message in the comments.

With that, let’s start building some neat-o Linux Apps!

February 23, 2008 Posted by | Ramblings | Leave a comment