Un visor de imágenes Clutter
Chris Kühl
chrisk@openismus.com
Johannes Schmid
jhs@gnome.org

# Mural de fotos

      Para este ejemplo se construirá un sencillo visor de imágenes usando Clutter. Aprenderá:

        Cómo dimensionar y posicionar varios ClutterActor
        Cómo situar una imagen en un ClutterActor
        Cómo hacer transiciones sencillas usando el entorno de trabajo de animaciones de Clutter
        Cómo hacer que un ClutterActor responda a los eventos del ratón
        Cómo obtener nombres de archivos de una carpeta

# Introducción

Clutter es una biblioteca para crear interfaces de usuarios dinámicas usando OpenGL para la aceleración gráfica. Este ejemplo demuestra una pequeña, pero importante parte de la biblioteca Clutter para crear un sencillo pero atractivo programa para ver imágenes.

To help us reach our goal we will be utilising a few other common pieces of GLib as well. Most importantly, we'll use one `GSList`, a singly-linked list, to hold our `ClutterActor`s and another one for file path names. We will also use `GDir`, a utility for working with directories, to access our image directory and gather file paths.

# Crear un proyecto en Anjuta

Antes de empezar a programar, deberá configurar un proyecto nuevo en Anjuta. Esto creará todos los archivos que necesite para construir y ejecutar el código más adelante. También es útil para mantener todo ordenado.

Inicie Anjuta y pulse Archivo Nuevo Proyecto para abrir el asistente de proyectos.

Seleccione Gtk+ (simple) en la pestaña C, pulse Siguiente, y rellene los detalles en las siguientes páginas. Use mural-de-fotos como nombre del proyecto y de la carpeta.

Asegúrese de que Usar GtkBuilder para la interfaz del usuario está desactivado, ya que, en este tutorial, crearemos la IU manualmente. Revise el tutorial del afinador de guitarra usando el constructor de interfaces.

Active Configurar paquetes externos. En la página siguiente, seleccione clutter-1.0 de la lista para incluir la biblioteca Clutter en su proyecto.

Pulse Aplicar y se creará el proyecto. Abra src/main.c desde las pestañas Proyecto o Archivo. Debería ver algo de código que comience con las líneas:

#include <config.h> #include <gtk/gtk.h>

# Un vistazo al mural de fotos

El visor de imágenes muestra al usuario un mural de imágenes.

Cuando se pulsa una imagen, esta se anima para que rellene el área de visualización. Cuando se pulsa la imagen que tiene el foco, vuelve a su tamaño original usando una animación que dura 500 milisegundos.

# Configuración inicial

El siguiente fragmento de código contiene muchas definiciones y variables que se usarán en las siguientes secciones. Úselo como referencia para las próximas secciones. Copie este código al principio de src/main.c:

#include <clutter/clutter.h>

#define STAGE_WIDTH 800 #define STAGE_HEIGHT 600

#define THUMBNAIL_SIZE 200 #define ROW_COUNT (STAGE_HEIGHT / THUMBNAIL_SIZE) #define COL_COUNT (STAGE_WIDTH / THUMBNAIL_SIZE) #define THUMBNAIL_COUNT (ROW_COUNT * COL_COUNT)

#define ANIMATION_DURATION_MS 500

#define FOCUS_DEPTH 100.0 #define UNFOCUS_DEPTH 0.0

#define IMAGE_DIR_PATH "./berlin_images/"

static GSList *actor_list = NULL; static GSList *img_path_list = NULL;

typedef struct Position { float x; float y; } Position;

static Position origin = {0, 0};

# Jumping into the code

We will start by taking a look at the `main()` function as a whole. Then we'll discuss the other code sections in detail. Change the src/main.c to contain this `main()` function. You can delete the `create_window()` function as we don't need it in this example.

int main(int argc, char *argv[]) { ClutterColor stage_color = { 16, 16, 16, 255 }; ClutterActor *stage = NULL;

clutter_init(&argc, &argv);

stage = clutter_stage_get_default(); clutter_actor_set_size(stage, STAGE_WIDTH, STAGE_HEIGHT); clutter_stage_set_color(CLUTTER_STAGE (stage), &stage_color);

load_image_path_names();

guint row = 0; guint col = 0; for(row=0; row < ROW_COUNT; ++row) { for(col=0; col < COL_COUNT; ++col) { GSList *img_path_node = g_slist_nth(img_path_list, (row * COL_COUNT) + col); ClutterActor *actor = clutter_texture_new_from_file((gchar *)(img_path_node->data), NULL); initialize_actor(actor, row, col); clutter_container_add_actor(CLUTTER_CONTAINER(stage), actor); actor_list = g_slist_prepend(actor_list, actor); } }

/* Show the stage. */ clutter_actor_show(stage);

/* Start the clutter main loop. */ clutter_main();

return 0; }

Line 4: `ClutterColor` is defined by setting the red, green, blue and transparency (alpha) values. The values range from 0-255. For transparency a value of 255 is opaque.

Línea 7: debe inicializar Clutter. Si olvida hacerlo, obtendrá mensajes muy extraños. Queda advertido.

Lines 9‒11: Here we get the default `ClutterStage` that was provided by `clutter_init`. We then set the size using the defines from the previous section and the address of the `ClutterColor` we just defined.

Un `ClutterStage` es el nivel superior de un `ClutterActor` en el que se ubican otros `ClutterActor`.

Línea 12: aquí se llama a la función para obtener las rutas de las imágenes. Esto se verá en breve.

Lines 14‒26: This is where we set up the `ClutterActor`s, load the images and place them into their spot in the image wall. We will look at this in detail in the next section.

Línea 29: mostrar el escenario y todos sus hijos, es decir, las imágenes.

Línea 32: iniciar el bucle principal de Clutter.

# Configurar los actores de imagen

En Clutter, un actor es el elemento visual más simple. Básicamente, todo lo que ve es un actor.

In this section, we are going to take a closer look at the loop used for setting up the `ClutterActor`s that will display our images.

for(row=0; row < ROW_COUNT; ++row) { for(col=0; col < COL_COUNT; ++col) { GSList *img_path_node = g_slist_nth(img_path_list, (row * COL_COUNT) + col); ClutterActor *actor = clutter_texture_new_from_file((gchar *)(img_path_node->data), NULL); initialize_actor(actor, row, col); clutter_container_add_actor(CLUTTER_CONTAINER(stage), actor); actor_list = g_slist_prepend(actor_list, actor); } }

Line 5: Here we want to get the path at the nth location in the `GSList` that is holding our image path names. The nth position is calculated based on `row` and `col`. The return value is a pointer to a `GSList` which is just a node in the list. We will use this to get the actual path in the next line. The first parameter is a pointer to the head of the list.

Line 6: This is where we actually create the `ClutterActor` and place the image into the actor. The first argument is the path which we access through our `GSList` node. The second argument is for error reporting but we are ignoring that to keep things short.

Línea 7: está función se verá en una sección posterior.

Line 8: This adds the `ClutterActor` to the stage, which is a container. It also assumes ownership of the `ClutterActor` which is something you'll want to look into as you get deeper into GNOME development. See the `GObject` documentation for the gory details.

Línea 9: esto añade el `ClutterActor` a una `GSList` por lo que luego se podrá iterar sobre los `ClutterActor`.

Interesting to note is that we want to prepend the `ClutterActor`s rather than append so that we avoid traversing the list upon each insertion. You will often see `g_slist_prepend` followed by `g_slist_reverse` because it faster than inserting many objects at the end of the list.

# Cargar las imágenes

Let's take a short break from Clutter to see how we can get the file names from our image directory.

static void load_image_path_names() { /* Ensure we can access the directory. */ GError *error = NULL; GDir *dir = g_dir_open(IMAGE_DIR_PATH, 0, &error); if(error) { g_warning("g_dir_open() failed with error: %s\n", error->message); g_clear_error(&error); return; }

const gchar *filename = g_dir_read_name(dir); while(filename) { if(g_str_has_suffix(filename, ".jpg") || g_str_has_suffix(filename, ".png")) { gchar *path = g_build_filename(IMAGE_DIR_PATH, filename, NULL); img_path_list = g_slist_prepend(img_path_list, path); } filename = g_dir_read_name(dir); } }

Lines 5 and 12: This opens our directory or, if an error occured, returns after printing an error message.

Lines 14‒23: The first line gets another file name from the `GDir` we opened earlier. If there was an image file (which we check by looking at its extension, ".png" or ".jpg") in the directory we proceed to prepend the image directory path to the filename and prepend that to the list we set up earlier. Lastly we attempt to get the next path name and reenter the loop if another file was found.

# Configurar los actores

We now take a look at the sizing and positioning of `ClutterActor`s and also readying the `ClutterActor` for user interaction.

/* This function handles setting up and placing the rectangles. */ static void initialize_actor(ClutterActor *actor, guint row, guint col) { clutter_actor_set_size(actor, THUMBNAIL_SIZE, THUMBNAIL_SIZE); clutter_actor_set_position(actor, col * THUMBNAIL_SIZE, row * THUMBNAIL_SIZE); clutter_actor_set_reactive(actor, TRUE);

g_signal_connect(actor, "button-press-event", G_CALLBACK(actor_clicked_cb), NULL); }

Line 7: Setting an actor reactive means that it reacts to events, such as `button-press-event` in our case. For Photo Wall, all `ClutterActor`s in the wall should initially be reactive.

Line 9‒12: Now we connect the `button-press-event` to the `actor_clicked_cb` callback which we will look at next.

En este punto tiene un mural de fotos que está listo para verse.

# Reaccionar a las pulsaciones

static gboolean actor_clicked_cb(ClutterActor *actor, ClutterEvent *event, gpointer user_data) { /* Flag to keep track of our state. */ static gboolean is_focused = FALSE;

g_slist_foreach(actor_list, foreach_set_focus_state, &is_focused);

if(is_focused) { clutter_actor_animate(actor, CLUTTER_LINEAR, ANIMATION_DURATION_MS, "x", origin.x, "y", origin.y, "depth", UNFOCUS_DEPTH, "width", (float) THUMBNAIL_SIZE, "height", (float) THUMBNAIL_SIZE, NULL); } else { /*Save the current location before animating. */ clutter_actor_get_position(actor, &origin.x, &origin.y); clutter_actor_set_reactive(actor, TRUE); clutter_actor_animate(actor, CLUTTER_LINEAR, ANIMATION_DURATION_MS, "x", (STAGE_WIDTH - STAGE_HEIGHT) / 2.0, "y", 0.0, "depth", FOCUS_DEPTH, "width", (float) STAGE_HEIGHT, "height", (float) STAGE_HEIGHT, NULL); }

/* Toggle our flag. */ is_focused = !is_focused;

return TRUE; }

Lines 1‒4: We have to make sure our callback function matches the signature required for the `button_clicked_event` signal. For our example, we will only use the first argument, the `ClutterActor` that is actually clicked.

A few words on the arguments we are not using in this example. The `ClutterEvent` is different depending on what event is being handled. For example, a key event produces a `ClutterKeyEvent` from which you can get the key being pressed among other information. For mouse click events you get a `ClutterButtonEvent` from which you can get the `x` and `y` values. See the Clutter documentation for other `ClutterEvent` types.

The `user_data` is what one uses to pass data into the the function. A pointer to any data type can be passed in. If you need multiple data to be passed into the callback, you can place the data into a struct and pass its address in.

Line 7: We set up a static flag to track which state we are in: wall mode or focus mode. We start out in wall mode so no image has focus. Thus, we set the flag to `FALSE` initially.

Line 9: This line of code runs a custom function, `foreach_set_focus_state`, for each element in our `actor_list`, passing it the address to the `is_focused` flag. We'll see the definition of the `foreach_set_focus_state` function in the next section.

Lines 13‒19: Reaching this code means that one image currently has focus and we want to return to wall mode. The `clutter_actor_animate` function is used to animate a `ClutterActor`'s property or properties from the current state(s) to the specified state(s). The arguments are as follows:

La dirección del `ClutterActor` que animar

El modo de animación que usar. Aquí se ha usado `CLUTTER_LINEAR` por lo que se tiene una velocidad constante en la animación.

La duración de la animación, en milisegundos. Se ha escogido 500 ms para este ejemplo.

The remaining arguments are property/value pairs. Here we want to set the `x` value to the starting `x` value this `ClutterActor` was at before being brought into focus.

El último argumento debe ser siempre `NULL` para indicar que no hay más propiedades que configurar.

The `depth` property needs a little more explaining. We need to raise the focused image so that it doesn't slide behind other `ClutterActor`s. In this section we are returning it to the same depth as the others on the wall.

La profundidad también determina qué `ClutterActor` recibe eventos. Un `ClutterActor` con una profundidad alta recibe los eventos de las pulsaciones y puede elegir si el evento se envía a un `ClutterActor` que esté debajo de él. Se verá cómo funciona esto en pocos pasos.

Line 24: Reaching this line of code means we are currently in the wall state and are about to give a `ClutterActor` focus. Here we save the starting position so that we can return to it later.

Line 25: Setting the `ClutterActor`'s `reactive` property to `TRUE` makes this `ClutterActor` react to events. In this focused state the only `ClutterActor` that we want to receive events will be the `ClutterActor` being viewed. Clicking on the `ClutterActor` will return it to its starting position.

Lines 27‒33: This is similar to the above block of code. Notice that we are setting the the depth to raise it above the other images.

Line 37: Here we toggle the `is_focused` flag to the current state.

As mentioned previously, the `ClutterActor`s with higher `depth` values receive events but can allow `ClutterActor`s below them to also receive events. Returning `TRUE` will stop events from being passed down, while `FALSE` will pass events down.

Remember, however, that to receive events the `ClutterActor`s must be set `reactive`.

The following is the convenience function passed to `g_slist_foreach`.

static void foreach_set_focus_state(gpointer data, gpointer user_data) { ClutterActor *actor = CLUTTER_ACTOR(data); gboolean is_reactive = *((gboolean*)user_data);

clutter_actor_set_reactive(actor, is_reactive); }

Lines 2‒5: The signature of this function requires two `gpointer`s. The first is a pointer to the `ClutterActor` that our `GSList` holds and the other is the `is_focused` flag that we've passed in the previous section. We want to cast these and store them for easy use.

Line 7: Depending on which boolean value is passed in, the `ClutterActor` will be set to respond to events or not.

# Construir y ejecutar la aplicación

All of the code should now be ready to go. All you need now is some pictures to load. By default, the pictures are loaded from a berlin_images directory. If you want, you can change the `#define IMAGE_DIR_PATH` line near the top to refer to your photo directory, or create a berlin_images directory by clicking Project New Directory... and creating a berlin_images directory as a subdirectory of the photo-wall directory. Make sure to put at least twelve images in the directory!

When you have done that, click Build Build Project to build everything again, then Run Execute to start the application.

Si todavía no lo ha hecho, elija la aplicación Debug/src/photo-wall en el diálogo que aparece. Finalmente, pulse Ejecutar y disfrute.

# Implementación de referencia

Si tiene problemas con este tutorial, compare su código con este código de referencia.