Image viewer (C) Un pouco máis que un simple aplicativo Gtk «Ola mundo». Proxecto de documentación de GNOME gnome-doc-list@gnome.org Johannes Schmid jhs@gnome.org Marta Maria Casetti mmcasetti@gmail.com 2013 Fran Dieguez frandieguez@gnome.org 2012-2013. Image viewer

Neste titorial aprenderá:

Algúns conceptos básicos de programación de C/GObject

Como escribir un aplicativo GTK en C

Cree un proxecto de Anjuta

Antes de comezar a programar, deberá configurar un proxecto novo en Anjuta. Isto creará todos os ficheiros que precise para construír e executar o código máis adiante. Tamén é útil para manter todo ordenado.

Inicie Anjuta e prema FicheiroNovoProxecto para abrir o asistente de proxectos.

Choose GTK+ (Simple) from the C tab, click Continue, and fill out your details on the next few pages. Use image-viewer as project name and directory.

Asegúrese que Usar GtkBuilder para a interface de usuario está desactivado xa que crearemos a UI manualmente neste titorial. Comprobe o titorial Guitar-Tuner se quere aprender como usar o construtor de interface.

Prema Aplicar para crear o proxecto. Abra src/main.c desde as lapelas Proxecto ou Ficheiro. Debería ver algún código que comeza coas liñas:

#include ]]>
Construír o código por primeira vez

C is a rather verbose language, so don't be surprised that the file contains quite a lot of code. Most of it is template code. It loads an (empty) window and shows it. More details are given below; skip this list if you understand the basics:

The three #include lines at the top include the config (useful autoconf build defines), gtk (user interface) and gi18n (internationalization) libraries. Functions from these libraries are used in the rest of the code.

A función create_window crea unha xanela (baleira) nova e conecta un sinal para saír do aplicativo péchase esa xanela.

Connecting signals is how you define what happens when you push a button, or when some other event happens. Here, the destroy function is called (and quits the app) when you close the window.

The main function is run by default when you start a C application. It calls a few functions which set up and then run the application. The gtk_main function starts the GTK main loop, which runs the user interface and starts listening for events (like clicks and key presses).

The ENABLE_NLS conditional definition sets up gettext, which is a framework for translating applications. These functions specify how translation tools should handle your app when you run them.

This code is ready to be used, so you can compile it by clicking BuildBuild Project (or press ShiftF7).

Prema Executar na seguinte xanela que aparece para configurar a compilación de depuración. Só precisa facer isto unha vez para a primeira compilación.

Crear a interface de usuario

Now we will bring life into the empty window. GTK organizes the user interface with GtkContainers that can contain other widgets and even other containers. Here we will use the simplest available container, a GtkBox:

The first lines create the widgets we want to use: a button for opening up an image, the image view widget itself and the box we will use as a container. The macros like GTK_BOX are used for dynamic type checking and casting which is needed as C doesn't support object-orientation out-of-the-box.

The calls to gtk_box_pack_start add the two widgets to the box and define their behaviour. The image will expand into any available space while the button will just be as big as needed. You will notice that we don't set explicit sizes on the widgets. In GTK this is usually not needed as it makes it much easier to have a layout that looks good in different window sizes. Next, the box is added to the window.

We need to define what happens when the user clicks on the button. GTK uses the concept of signals. When the button is clicked, it fires the clicked signal, which we can connect to some action. This is done using the g_signal_connect function which tells GTK to call the on_image_open function when the button is clicked and to pass the image as an additional argument to that function. We will define the callback in the next section.

The last g_signal_connect() makes sure that the application exits when the window is closed.

As a last step, make sure to replace the gtk_widget_show call in the main() function by gtk_widget_show_all() to show the window and all the widgets it contains.

Mostrar a imaxe

We will now define the signal handler for the clicked signal or the button we mentioned before. Add this code before the create_window() method.

This is a bit more complicated than anything we've attempted so far, so let's break it down:

The first argument of the signal is always the widget that sent the signal. Sometimes other arguments related to the signal come after that, but clicked doesn't have any. Next is the user_data argument which is a pointer to the data we passed when connecting the signal. In this case it is our GtkImage object.

The next interesting line is where the dialog for choosing the file is created using gtk_file_chooser_dialog_new. The function takes the title of the dialog, the parent window of the dialog and several options like the number of buttons and their corresponding values.

Notice that we are using stock button names from Gtk, instead of manually typing "Cancel" or "Open". The advantage of using stock names is that the button labels will already be translated into the user's language.

The next two lines restrict the Open dialog to only display files which can be opened by GtkImage. A filter object is created first; we then add all kinds of files supported by GdkPixbuf (which includes most image formats like PNG and JPEG) to the filter. Finally, we set this filter to be the Open dialog's filter.

gtk_dialog_run displays the Open dialog. The dialog will wait for the user to choose an image; when they do, gtk_dialog_run will return the value GTK_RESPONSE_ACCEPT (it would return GTK_RESPONSE_CANCEL if the user clicked Cancel). The switch statement tests for this.

Assuming that the user did click Open, the next line sets the file property of the GtkImage to the filename of the image selected by the user. The GtkImage will then load and display the chosen image.

In the final line of this method, we destroy the Open dialog because we don't need it any more. Destroying automatically hides the dialog.

Construír e executar o aplicativo

All of the code should now be ready to go. Click BuildBuild Project to build everything again, and then RunExecute to start the application.

Se non o fixo aínda, seleccione o aplicativo Debug/src/image-viewer no diálogo que aparece. Finalmente, prema Executar e desfrute!

Implementación de referencia

If you run into problems with the tutorial, compare your code with this reference code.

Seguintes pasos

Aquí hai algunhas ideas sobre como pode estender esta sinxela demostración:

Have the user select a directory rather than a file, and provide controls to cycle through all of the images in a directory.

Aplicar filtros aleatorios e efectos á imaxe cando se carga e permitir ao usuario gardar a imaxe modificada.

GEGL fornece capacidades moi potentes de manipulación de imaxes.

Permitir ao usuario cargar imaxes desde recursos de rede compartidos, escáneres e outras fontes máis complicadas.

You can use GIO to handle network file transfers and the like, and GNOME Scan to handle scanning.