Publi

Cómo insertar un elemento a la lista de documentos recientes en C

photo-1448523183439-d2ac62aca997_r

Hoy toca un código muy rápido para nuestras aplicaciones con Gtk+ (yo he usado la versión 3 para este ejemplo). Lo que haremos será incluir un archivo (el que nosotros queramos) en la lista de «Usados recientemente» de forma que cuando vayamos a algún diálogo de apertura de archivo veamos añadido dicho documento.
Esto puede ser muy útil cuando nuestra aplicación salve o cargue archivos y queramos que el usuario pueda utilizarlos rápidamente desde otra aplicación.
Screenshot 12-02-2016-030229
Seré breve, lo único que necesitamos es obtener acceso al recent manager, crear un acceso al recurso y añadírselo al recent manager.

Luego, debemos hacer que Gtk+ realice algunas llamadas internas durante un periodo ínfimo de tiempo y listo.

Versión super-reducida

Esta versión es sólo una prueba de concepto, para ver que todo funciona. El programa no tiene entorno gráfico alguno, sólo parece que se queda colgado, y de hecho se limita a esperar llamadas a sistema, y dichas llamadas no llegan nunca.
Si has trabajado con Gtk anteriormente, sabrás integrar esto en tus programas.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <gtk-3.0/gtk/gtk.h>

int main(int argc, char*argv[])
{
  gtk_init(&argc, &argv);
  g_set_application_name("RecentFilador");
  GtkRecentManager *grm = gtk_recent_manager_get_default();
  GtkRecentData *data = g_slice_new(GtkRecentData);

  static gchar* groups[] = {
    NULL
  };
  data->display_name=NULL;
  data->description = NULL;
  data->mime_type="image/jpeg";
  data->app_name = (gchar*) g_get_application_name();
  data->app_exec = "gimp %f";
  data->is_private = FALSE;
  data->groups = groups;
  gchar *uri = g_filename_to_uri("/home/gaspy/envio_netbook.jpg", NULL, NULL);
  gtk_recent_manager_add_full(grm, uri, data);

  gtk_main();
  return 0;
}

Versión independiente

Eso sí, el programa, ¡se queda colgado! Eso es mucho, tenemos varias soluciones, la primera es, en lugar de llamar a gtk_main(), llamar a gtk_main_iteration() varias veces. Pero es un poco chapuza, incluso metiéndolo en un bucle tipo:

1
2
while (gtk_events_pending())
  gtk_main_iteration();

Pero, es más, esto no nos garantiza que hagamos todas las iteraciones necesarias, ya que puede que algún mensaje no entre inmediatamente. Entonces, para el ejemplo, vamos a hacer que se llame a una función callback automáticamente cuando Gtk+ no tenga nada que hacer (usando g_idle_add(funcion, NULL)), y dicha función, creará el archivo reciente y se saldrá del programa (con gtk_main_quit(), finalizando correctamente el paso de mensajes Gtk+). Así nos dará una mejor sensación.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <gtk-3.0/gtk/gtk.h>

gboolean addrf(gpointer options)
{
  GtkRecentManager *grm = gtk_recent_manager_get_default();
  GtkRecentData *data = g_slice_new(GtkRecentData);
  static gchar* groups[] = {
    NULL
  };
  data->display_name=NULL;
  data->description = NULL;
  data->mime_type="image/jpeg";
  data->app_name = (gchar*) g_get_application_name();
  data->app_exec = "gimp %f";
  data->is_private = FALSE;
  data->groups = groups;
  gchar *uri = g_filename_to_uri("/home/gaspy/envio_netbook.jpg", NULL, NULL);
  gtk_recent_manager_add_full(grm, uri, data);

  gtk_main_quit();
}

int main(int argc, char*argv[])
{
  gtk_init(&argc, &argv);
  g_set_application_name("RecentFilador");
  g_idle_add(addrf, NULL);

  gtk_main();
  return 0;
}

Compilar

Para compilar, yo he hecho lo siguiente (en Linux):

$ gcc -o recents recents3.c $(pkg-config –libs –cflags gtk+-3.0)

He utilizado pkg-config para obtener todas las bibliotecas necesarias por Gtk+ y todas las rutas a los archivos de cabecera.

Compatibilidad

Aunque no lo he probado, no he utilizado nada 100% específico de Linux, por lo que debería funcionar sin problemas en Windows o en Mac.

Algo más completo

Pasáos por mi GitHub para ver un programa que sirve para hacer esto mismo. Listo para ser compilado. Sólo tenéis que mirar las instrucciones y compilar 🙂

Foto principal: Brady Bellini

También podría interesarte....

There are 6 comments left Ir a comentario

  1. Pingback: Cómo Insertar Un Elemento A La Lista De Documentos Recientes En C | PlanetaLibre /

  2. Babita reddy /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    This low grade of sources is not concerned about the satisfaction level, the client is receiving. For them making the contract and then, later on, just completing it is relevant. You are certainly not interested in getting Escort in Delhi your mind caught up in such type of tension. After all, this is the sole reason for you getting attracted towards the other sexy Independent Call Girls in Delhi city.

  3. seo /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    I’ve been searching for some decent stuff on the subject and haven’t had any luck up until this point, You just got a new biggest fan!..This is really nice to read..informative post is very good to read..thanks a lot! https://www.digitekprinting.com/poster-prints

  4. Vincent Cassel Damaged Coat /
    Usando Google Chrome Google Chrome 123.0.0.0 en Windows Windows NT

    This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information.

  5. shivani singh /
    Usando Google Chrome Google Chrome 123.0.0.0 en Windows Windows NT

    So how about we attempt to comprehend the secrets of our Delhi Call Girls and their sex craftsmanship?

  6. 토토사이트 /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    It’s a game. Five dollars is free. Try it It’s not an easy game
    ->-> 토토사이트.COM

Leave a Reply to Anónimo Cancle Reply