gtkrecentmanager.c 66.7 KB
Newer Older
Cody Russell's avatar
Cody Russell committed
1
/* GTK - The GIMP Toolkit
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 * gtkrecentmanager.c: a manager for the recently used resources
 *
 * Copyright (C) 2006 Emmanuele Bassi
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
Javier Jardón's avatar
Javier Jardón committed
17
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
18 19
 */

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/**
 * SECTION:gtkrecentmanager
 * @Title: GtkRecentManager
 * @short_description: Managing recently used files
 * @See_Also: #GBookmarkFile, #GtkSettings, #GtkRecentChooser
 *
 * #GtkRecentManager provides a facility for adding, removing and
 * looking up recently used files. Each recently used file is
 * identified by its URI, and has meta-data associated to it, like
 * the names and command lines of the applications that have
 * registered it, the number of time each application has registered
 * the same file, the mime type of the file and whether the file
 * should be displayed only by the applications that have
 * registered it.
 *
35
 * The recently used files list is per user.
36 37 38 39 40 41 42
 *
 * The #GtkRecentManager acts like a database of all the recently
 * used files. You can create new #GtkRecentManager objects, but
 * it is more efficient to use the default manager created by GTK+.
 *
 * Adding a new recently used file is as simple as:
 *
43
 * |[<!-- language="C" -->
44 45 46 47 48 49 50 51 52 53 54 55
 * GtkRecentManager *manager;
 *
 * manager = gtk_recent_manager_get_default ();
 * gtk_recent_manager_add_item (manager, file_uri);
 * ]|
 *
 * The #GtkRecentManager will try to gather all the needed information
 * from the file itself through GIO.
 *
 * Looking up the meta-data associated with a recently used file
 * given its URI requires calling gtk_recent_manager_lookup_item():
 *
56
 * |[<!-- language="C" -->
57 58 59 60 61
 * GtkRecentManager *manager;
 * GtkRecentInfo *info;
 * GError *error = NULL;
 *
 * manager = gtk_recent_manager_get_default ();
62
 * info = gtk_recent_manager_lookup_item (manager, file_uri, &error);
63 64
 * if (error)
 *   {
65
 *     g_warning ("Could not find the file: %s", error->message);
66 67 68 69
 *     g_error_free (error);
 *   }
 * else
 *  {
70
 *    // Use the info object
71 72 73 74 75
 *    gtk_recent_info_unref (info);
 *  }
 * ]|
 *
 * In order to retrieve the list of recently used files, you can use
76
 * gtk_recent_manager_get_items(), which returns a list of #GtkRecentInfo-structs.
77 78 79 80
 *
 * A #GtkRecentManager is the model used to populate the contents of
 * one, or more #GtkRecentChooser implementations.
 *
81
 * Note that the maximum age of the recently used files list is
82
 * controllable through the #GtkSettings:gtk-recent-files-max-age
83
 * property.
84 85 86 87
 *
 * Recently used files are supported since GTK+ 2.10.
 */

88 89 90 91 92 93 94 95 96 97 98 99
#include "config.h"

#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <glib.h>
#include <glib/gstdio.h>
100
#include <gio/gio.h>
101 102 103

#include "gtkrecentmanager.h"
#include "gtkintl.h"
Emmanuele Bassi's avatar
Emmanuele Bassi committed
104
#include "gtksettings.h"
105 106 107 108 109 110
#include "gtkicontheme.h"
#include "gtktypebuiltins.h"
#include "gtkprivate.h"
#include "gtkmarshalers.h"

/* the file where we store the recently used items */
111
#define GTK_RECENTLY_USED_FILE  "recently-used.xbel"
112 113

/* return all items by default */
114
#define DEFAULT_LIMIT   -1
115

116 117 118
/* limit the size of the list */
#define MAX_LIST_SIZE 1000

119
/* keep in sync with xdgmime */
120
#define GTK_RECENT_DEFAULT_MIME "application/octet-stream"
121 122 123 124 125

typedef struct
{
  gchar *name;
  gchar *exec;
126

127
  guint count;
128

129 130 131
  time_t stamp;
} RecentAppInfo;

132 133 134
/**
 * GtkRecentInfo:
 *
135 136
 * #GtkRecentInfo-struct contains private data only, and should
 * be accessed using the provided API.
137
 *
138
 * #GtkRecentInfo constains all the meta-data
139 140 141 142
 * associated with an entry in the recently used files list.
 *
 * Since: 2.10
 */
143 144 145
struct _GtkRecentInfo
{
  gchar *uri;
146

147 148
  gchar *display_name;
  gchar *description;
149

150 151 152
  time_t added;
  time_t modified;
  time_t visited;
153

154
  gchar *mime_type;
155

156 157
  GSList *applications;
  GHashTable *apps_lookup;
158

159
  GSList *groups;
160

161
  gboolean is_private;
162

163
  GdkPixbuf *icon;
164

165 166 167 168 169 170 171 172
  gint ref_count;
};

struct _GtkRecentManagerPrivate
{
  gchar *filename;

  guint is_dirty : 1;
173

174 175 176
  gint size;

  GBookmarkFile *recent_items;
177 178

  GFileMonitor *monitor;
179 180 181

  guint changed_timeout;
  guint changed_age;
182 183 184 185 186 187
};

enum
{
  PROP_0,

188
  PROP_FILENAME,
189 190 191 192
  PROP_LIMIT,
  PROP_SIZE
};

193 194 195
static void     gtk_recent_manager_dispose             (GObject           *object);
static void     gtk_recent_manager_finalize            (GObject           *object);
static void     gtk_recent_manager_set_property        (GObject           *object,
196 197 198
                                                        guint              prop_id,
                                                        const GValue      *value,
                                                        GParamSpec        *pspec);
199
static void     gtk_recent_manager_get_property        (GObject           *object,
200 201 202
                                                        guint              prop_id,
                                                        GValue            *value,
                                                        GParamSpec        *pspec);
203 204 205 206 207 208 209 210 211 212 213 214
static void     gtk_recent_manager_add_item_query_info (GObject           *source_object,
                                                        GAsyncResult      *res,
                                                        gpointer           user_data);
static void     gtk_recent_manager_monitor_changed     (GFileMonitor      *monitor,
                                                        GFile             *file,
                                                        GFile             *other_file,
                                                        GFileMonitorEvent  event_type,
                                                        gpointer           user_data);
static void     gtk_recent_manager_changed             (GtkRecentManager  *manager);
static void     gtk_recent_manager_real_changed        (GtkRecentManager  *manager);
static void     gtk_recent_manager_set_filename        (GtkRecentManager  *manager,
                                                        const gchar       *filename);
215 216
static void     gtk_recent_manager_clamp_to_age        (GtkRecentManager  *manager,
                                                        gint               age);
217 218 219
static void     gtk_recent_manager_clamp_to_size       (GtkRecentManager  *manager,
                                                        const gint         size);

220
static void     gtk_recent_manager_enabled_changed     (GtkRecentManager  *manager);
221

222

223 224 225
static void     build_recent_items_list                (GtkRecentManager  *manager);
static void     purge_recent_items_list                (GtkRecentManager  *manager,
                                                        GError           **error);
226 227 228 229 230 231

static RecentAppInfo *recent_app_info_new  (const gchar   *app_name);
static void           recent_app_info_free (RecentAppInfo *app_info);

static GtkRecentInfo *gtk_recent_info_new  (const gchar   *uri);
static void           gtk_recent_info_free (GtkRecentInfo *recent_info);
232 233 234

static guint signal_changed = 0;

235 236
static GtkRecentManager *recent_manager_singleton = NULL;

237
G_DEFINE_TYPE_WITH_PRIVATE (GtkRecentManager, gtk_recent_manager, G_TYPE_OBJECT)
238

Matthias Clasen's avatar
Matthias Clasen committed
239 240
/* Test of haystack has the needle prefix, comparing case
 * insensitive. haystack may be UTF-8, but needle must
241 242
 * contain only lowercase ascii.
 */
Matthias Clasen's avatar
Matthias Clasen committed
243
static gboolean
244
has_case_prefix (const gchar *haystack,
Matthias Clasen's avatar
Matthias Clasen committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
                 const gchar *needle)
{
  const gchar *h, *n;

  /* Eat one character at a time. */
  h = haystack;
  n = needle;

  while (*n && *h && *n == g_ascii_tolower (*h))
    {
      n++;
      h++;
    }

  return *n == '\0';
}

262 263 264
GQuark
gtk_recent_manager_error_quark (void)
{
265
  return g_quark_from_static_string ("gtk-recent-manager-error-quark");
266 267 268 269 270 271
}

static void
gtk_recent_manager_class_init (GtkRecentManagerClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
272

273 274
  gobject_class->set_property = gtk_recent_manager_set_property;
  gobject_class->get_property = gtk_recent_manager_get_property;
275
  gobject_class->dispose = gtk_recent_manager_dispose;
276
  gobject_class->finalize = gtk_recent_manager_finalize;
277

278
  /**
279
   * GtkRecentManager:filename:
280
   *
281 282
   * The full path to the file to be used to store and read the
   * recently used resources list
283 284 285 286
   *
   * Since: 2.10
   */
  g_object_class_install_property (gobject_class,
287 288 289 290 291 292
                                   PROP_FILENAME,
                                   g_param_spec_string ("filename",
                                                        P_("Filename"),
                                                        P_("The full path to the file to be used to store and read the list"),
                                                        NULL,
                                                        (G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE)));
293

294
  /**
295
   * GtkRecentManager:size:
296
   *
297 298 299 300 301
   * The size of the recently used resources list.
   *
   * Since: 2.10
   */
  g_object_class_install_property (gobject_class,
302 303 304 305 306 307 308 309 310
                                   PROP_SIZE,
                                   g_param_spec_int ("size",
                                                     P_("Size"),
                                                     P_("The size of the recently used resources list"),
                                                     -1,
                                                     G_MAXINT,
                                                     0,
                                                     G_PARAM_READABLE));

311
  /**
312
   * GtkRecentManager::changed:
313 314
   * @recent_manager: the recent manager
   *
315 316 317
   * Emitted when the current recently used resources manager changes
   * its contents, either by calling gtk_recent_manager_add_item() or
   * by another application.
318 319 320 321 322
   *
   * Since: 2.10
   */
  signal_changed =
    g_signal_new (I_("changed"),
323 324 325 326 327 328 329
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_FIRST,
                  G_STRUCT_OFFSET (GtkRecentManagerClass, changed),
                  NULL, NULL,
                  g_cclosure_marshal_VOID__VOID,
                  G_TYPE_NONE, 0);

330 331 332 333 334 335 336
  klass->changed = gtk_recent_manager_real_changed;
}

static void
gtk_recent_manager_init (GtkRecentManager *manager)
{
  GtkRecentManagerPrivate *priv;
337
  GtkSettings *settings;
338

339
  manager->priv = gtk_recent_manager_get_instance_private (manager);
340 341
  priv = manager->priv;

342
  priv->size = 0;
343
  priv->filename = NULL;
344 345

  settings = gtk_settings_get_default ();
346 347 348
  if (settings)
    g_signal_connect_swapped (settings, "notify::gtk-recent-files-enabled",
                              G_CALLBACK (gtk_recent_manager_enabled_changed), manager);
349 350 351
}

static void
352 353 354 355
gtk_recent_manager_set_property (GObject      *object,
                                 guint         prop_id,
                                 const GValue *value,
                                 GParamSpec   *pspec)
356 357
{
  GtkRecentManager *recent_manager = GTK_RECENT_MANAGER (object);
358

359 360 361 362 363 364 365 366 367 368 369 370
  switch (prop_id)
    {
    case PROP_FILENAME:
      gtk_recent_manager_set_filename (recent_manager, g_value_get_string (value));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
371 372 373 374
gtk_recent_manager_get_property (GObject    *object,
                                 guint       prop_id,
                                 GValue     *value,
                                 GParamSpec *pspec)
375 376
{
  GtkRecentManager *recent_manager = GTK_RECENT_MANAGER (object);
377

378 379 380 381 382 383 384 385 386 387 388 389
  switch (prop_id)
    {
    case PROP_FILENAME:
      g_value_set_string (value, recent_manager->priv->filename);
      break;
    case PROP_SIZE:
      g_value_set_int (value, recent_manager->priv->size);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
390
}
391 392

static void
393
gtk_recent_manager_finalize (GObject *object)
394 395 396 397
{
  GtkRecentManager *manager = GTK_RECENT_MANAGER (object);
  GtkRecentManagerPrivate *priv = manager->priv;

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  g_free (priv->filename);

  if (priv->recent_items != NULL)
    g_bookmark_file_free (priv->recent_items);

  G_OBJECT_CLASS (gtk_recent_manager_parent_class)->finalize (object);
}

static void
gtk_recent_manager_dispose (GObject *gobject)
{
  GtkRecentManager *manager = GTK_RECENT_MANAGER (gobject);
  GtkRecentManagerPrivate *priv = manager->priv;

  if (priv->monitor != NULL)
413
    {
414 415 416 417 418
      g_signal_handlers_disconnect_by_func (priv->monitor,
                                            G_CALLBACK (gtk_recent_manager_monitor_changed),
                                            manager);
      g_object_unref (priv->monitor);
      priv->monitor = NULL;
419 420
    }

421 422 423 424 425 426
  if (priv->changed_timeout != 0)
    {
      g_source_remove (priv->changed_timeout);
      priv->changed_timeout = 0;
      priv->changed_age = 0;
    }
427

428 429 430 431 432 433
  if (priv->is_dirty)
    {
      g_object_ref (manager);
      g_signal_emit (manager, signal_changed, 0);
      g_object_unref (manager);
    }
434

435
  G_OBJECT_CLASS (gtk_recent_manager_parent_class)->dispose (gobject);
436 437
}

438 439 440 441 442 443 444
static void
gtk_recent_manager_enabled_changed (GtkRecentManager *manager)
{
  manager->priv->is_dirty = TRUE;
  gtk_recent_manager_changed (manager);
}

445 446 447 448 449 450 451 452 453 454
static void
gtk_recent_manager_real_changed (GtkRecentManager *manager)
{
  GtkRecentManagerPrivate *priv = manager->priv;

  g_object_freeze_notify (G_OBJECT (manager));

  if (priv->is_dirty)
    {
      GError *write_error;
455

456 457 458 459 460
      /* we are marked as dirty, so we dump the content of our
       * recently used items list
       */
      if (!priv->recent_items)
        {
461 462 463
          /* if no container object has been defined, we create a new
           * empty container, and dump it
           */
464
          priv->recent_items = g_bookmark_file_new ();
465 466
          priv->size = 0;
        }
467 468
      else
        {
469 470
          GtkSettings *settings;
          gint age;
471
          gint max_size = MAX_LIST_SIZE;
472
          gboolean enabled;
473

474 475 476 477 478 479 480 481 482 483 484
          settings = gtk_settings_get_default ();
          if (settings)
            g_object_get (G_OBJECT (settings),
                          "gtk-recent-files-max-age", &age,
                          "gtk-recent-files-enabled", &enabled,
                          NULL);
          else
            {
              age = 30;
              enabled = TRUE;
            }
485

486
          if (age == 0 || max_size == 0 || !enabled)
487 488 489
            {
              g_bookmark_file_free (priv->recent_items);
              priv->recent_items = g_bookmark_file_new ();
490
              priv->size = 0;
491
            }
492 493 494 495 496 497 498
          else
            {
              if (age > 0)
                gtk_recent_manager_clamp_to_age (manager, age);
              if (max_size > 0)
                gtk_recent_manager_clamp_to_size (manager, max_size);
            }
499
        }
500

501
      if (priv->filename != NULL)
502
        {
503 504 505 506
          write_error = NULL;
          g_bookmark_file_to_file (priv->recent_items, priv->filename, &write_error);
          if (write_error)
            {
507 508 509 510 511
              gchar *utf8 = g_filename_to_utf8 (priv->filename, -1, NULL, NULL, NULL);
              g_warning ("Attempting to store changes into '%s', but failed: %s",
                         utf8 ? utf8 : "(invalid filename)",
                         write_error->message);
              g_free (utf8);
512
              g_error_free (write_error);
513
            }
514

515 516
          if (g_chmod (priv->filename, 0600) < 0)
            {
517 518 519 520 521
              gchar *utf8 = g_filename_to_utf8 (priv->filename, -1, NULL, NULL, NULL);
              g_warning ("Attempting to set the permissions of '%s', but failed: %s",
                         utf8 ? utf8 : "(invalid filename)",
                         g_strerror (errno));
              g_free (utf8);
522
            }
523 524
        }

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
      /* mark us as clean */
      priv->is_dirty = FALSE;
    }
  else
    {
      /* we are not marked as dirty, so we have been called
       * because the recently used resources file has been
       * changed (and not from us).
       */
      build_recent_items_list (manager);
    }

  g_object_thaw_notify (G_OBJECT (manager));
}

540 541 542 543 544 545
static void
gtk_recent_manager_monitor_changed (GFileMonitor      *monitor,
                                    GFile             *file,
                                    GFile             *other_file,
                                    GFileMonitorEvent  event_type,
                                    gpointer           user_data)
546
{
547
  GtkRecentManager *manager = user_data;
548

549
  switch (event_type)
550
    {
551 552
    case G_FILE_MONITOR_EVENT_CHANGED:
    case G_FILE_MONITOR_EVENT_CREATED:
553
    case G_FILE_MONITOR_EVENT_DELETED:
554
      gdk_threads_enter ();
555
      gtk_recent_manager_changed (manager);
556
      gdk_threads_leave ();
557
      break;
558

559 560 561
    default:
      break;
    }
562 563
}

564 565 566
static gchar *
get_default_filename (void)
{
567 568 569 570 571 572 573 574 575 576 577 578
  if (g_mkdir_with_parents (g_get_user_data_dir (), 0755) == -1)
    {
      int saved_errno = errno;

      g_critical ("Unable to create user data directory '%s' for storing "
                  "the recently used files list: %s",
                  g_get_user_data_dir (),
                  g_strerror (saved_errno));

      return NULL;
    }

579 580 581 582 583
  return g_build_filename (g_get_user_data_dir (),
                           GTK_RECENTLY_USED_FILE,
                           NULL);
}

584 585
static void
gtk_recent_manager_set_filename (GtkRecentManager *manager,
586
                                 const gchar      *filename)
587 588
{
  GtkRecentManagerPrivate *priv;
589 590
  GFile *file;
  GError *error;
591

592
  g_assert (GTK_IS_RECENT_MANAGER (manager));
593

594
  priv = manager->priv;
595

596 597
  /* if a filename is already set and filename is not NULL, then copy
   * it and reset the monitor; otherwise, if it's NULL we're being
598 599
   * called from the finalization sequence, so we simply disconnect
   * the monitoring and return.
600 601 602 603
   *
   * if no filename is set and filename is NULL, use the default.
   */
  if (priv->filename)
604
    {
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
      g_free (priv->filename);

      if (priv->monitor)
        {
          g_signal_handlers_disconnect_by_func (priv->monitor,
                                                G_CALLBACK (gtk_recent_manager_monitor_changed),
                                                manager);
          g_object_unref (priv->monitor);
          priv->monitor = NULL;
        }

      if (!filename || *filename == '\0')
        return;
      else
        priv->filename = g_strdup (filename);
    }
  else
    {
      if (!filename || *filename == '\0')
624
        priv->filename = get_default_filename ();
625 626
      else
        priv->filename = g_strdup (filename);
627 628
    }

629
  if (priv->filename != NULL)
630
    {
631
      file = g_file_new_for_path (priv->filename);
632

633 634 635 636
      error = NULL;
      priv->monitor = g_file_monitor_file (file, G_FILE_MONITOR_NONE, NULL, &error);
      if (error)
        {
637 638 639 640 641 642 643
          gchar *utf8 = g_filename_to_utf8 (priv->filename, -1, NULL, NULL, NULL);
          g_warning ("Unable to monitor '%s': %s\n"
                     "The GtkRecentManager will not update its contents "
                     "if the file is changed from other instances",
                     utf8 ? utf8 : "(invalid filename)",
                     error->message);
          g_free (utf8);
644 645 646 647 648 649 650 651 652
          g_error_free (error);
        }
      else
        g_signal_connect (priv->monitor, "changed",
                          G_CALLBACK (gtk_recent_manager_monitor_changed),
                          manager);

      g_object_unref (file);
    }
653

654
  build_recent_items_list (manager);
655 656 657 658
}

/* reads the recently used resources file and builds the items list.
 * we keep the items list inside the parser object, and build the
659
 * RecentInfo object only on user’s demand to avoid useless replication.
660
 * this function resets the dirty bit of the manager.
661 662 663 664
 */
static void
build_recent_items_list (GtkRecentManager *manager)
{
665
  GtkRecentManagerPrivate *priv = manager->priv;
666 667 668 669 670 671 672 673 674
  GError *read_error;
  gint size;

  if (!priv->recent_items)
    {
      priv->recent_items = g_bookmark_file_new ();
      priv->size = 0;
    }

675
  if (priv->filename != NULL)
676
    {
677 678
      /* the file exists, and it's valid (we hope); if not, destroy the container
       * object and hope for a better result when the next "changed" signal is
679 680
       * fired.
       */
681 682 683 684 685 686 687 688 689 690 691
      read_error = NULL;
      g_bookmark_file_load_from_file (priv->recent_items, priv->filename, &read_error);
      if (read_error)
        {
          /* if the file does not exist we just wait for the first write
           * operation on this recent manager instance, to avoid creating
           * empty files and leading to spurious file system events (Sabayon
           * will not be happy about those)
           */
          if (read_error->domain == G_FILE_ERROR &&
            read_error->code != G_FILE_ERROR_NOENT)
692 693 694 695 696 697 698 699
            {
              gchar *utf8 = g_filename_to_utf8 (priv->filename, -1, NULL, NULL, NULL);
              g_warning ("Attempting to read the recently used resources "
                         "file at '%s', but the parser failed: %s.",
                         utf8 ? utf8 : "(invalid filename)",
                         read_error->message);
              g_free (utf8);
            }
700

701 702
          g_bookmark_file_free (priv->recent_items);
          priv->recent_items = NULL;
703

704 705 706
          g_error_free (read_error);
        }
      else
707
        {
708 709 710 711
          size = g_bookmark_file_get_size (priv->recent_items);
          if (priv->size != size)
            {
              priv->size = size;
712

713 714
              g_object_notify (G_OBJECT (manager), "size");
            }
715
        }
716 717
    }

718
  priv->is_dirty = FALSE;
719 720 721 722 723 724 725 726 727 728
}


/********************
 * GtkRecentManager *
 ********************/


/**
 * gtk_recent_manager_new:
729
 *
730 731
 * Creates a new recent manager object. Recent manager objects are used to
 * handle the list of recently used resources. A #GtkRecentManager object
732
 * monitors the recently used resources list, and emits the “changed” signal
733 734
 * each time something inside the list changes.
 *
735
 * #GtkRecentManager objects are expensive: be sure to create them only when
736
 * needed. You should use gtk_recent_manager_get_default() instead.
737
 *
738
 * Returns: A newly created #GtkRecentManager object
739 740 741 742 743 744
 *
 * Since: 2.10
 */
GtkRecentManager *
gtk_recent_manager_new (void)
{
745
  return g_object_new (GTK_TYPE_RECENT_MANAGER, NULL);
746 747 748 749 750
}

/**
 * gtk_recent_manager_get_default:
 *
751
 * Gets a unique instance of #GtkRecentManager, that you can share
752
 * in your application without caring about memory management.
753
 *
754 755
 * Returns: (transfer none): A unique #GtkRecentManager. Do not ref or
 *   unref it.
756 757 758 759 760 761
 *
 * Since: 2.10
 */
GtkRecentManager *
gtk_recent_manager_get_default (void)
{
762 763 764 765
  if (G_UNLIKELY (!recent_manager_singleton))
    recent_manager_singleton = gtk_recent_manager_new ();

  return recent_manager_singleton;
766 767 768
}


769
static void
770 771 772
gtk_recent_manager_add_item_query_info (GObject      *source_object,
                                        GAsyncResult *res,
                                        gpointer      user_data)
773 774 775 776 777
{
  GFile *file = G_FILE (source_object);
  GtkRecentManager *manager = user_data;
  GtkRecentData recent_data;
  GFileInfo *file_info;
778
  gchar *uri, *basename, *content_type;
779 780 781

  uri = g_file_get_uri (file);

782
  file_info = g_file_query_info_finish (file, res, NULL); /* NULL-GError */
783 784 785 786 787 788

  recent_data.display_name = NULL;
  recent_data.description = NULL;

  if (file_info)
    {
789 790 791 792 793 794 795 796
      content_type = g_file_info_get_attribute_as_string (file_info, G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE);

      if (G_LIKELY (content_type))
        recent_data.mime_type = g_content_type_get_mime_type (content_type);
      else
        recent_data.mime_type = g_strdup (GTK_RECENT_DEFAULT_MIME);

      g_free (content_type);
797 798 799
      g_object_unref (file_info);
    }
  else
800 801
    {
      basename = g_file_get_basename (file);
802 803
      content_type = g_content_type_guess (basename, NULL, 0, NULL);
      recent_data.mime_type = g_content_type_get_mime_type (content_type);
804
      g_free (basename);
805
      g_free (content_type);
806
    }
807 808 809 810 811 812

  recent_data.app_name = g_strdup (g_get_application_name ());
  recent_data.app_exec = g_strjoin (" ", g_get_prgname (), "%u", NULL);
  recent_data.groups = NULL;
  recent_data.is_private = FALSE;

813 814
  gdk_threads_enter ();

815
  /* Ignore return value, this can't fail anyway since all required
816 817
   * fields are set
   */
818 819
  gtk_recent_manager_add_full (manager, uri, &recent_data);

820 821 822
  manager->priv->is_dirty = TRUE;
  gtk_recent_manager_changed (manager);

823 824
  gdk_threads_leave ();

825 826 827 828 829 830 831 832
  g_free (recent_data.mime_type);
  g_free (recent_data.app_name);
  g_free (recent_data.app_exec);

  g_object_unref (manager);
  g_free (uri);
}

833 834
/**
 * gtk_recent_manager_add_item:
835
 * @manager: a #GtkRecentManager
836 837 838 839 840
 * @uri: a valid URI
 *
 * Adds a new resource, pointed by @uri, into the recently used
 * resources list.
 *
841
 * This function automatically retrieves some of the needed
842 843
 * metadata and setting other metadata to common default values;
 * it then feeds the data to gtk_recent_manager_add_full().
844
 *
845
 * See gtk_recent_manager_add_full() if you want to explicitly
846 847
 * define the metadata for the resource pointed by @uri.
 *
848
 * Returns: %TRUE if the new item was successfully added
849 850 851 852 853
 *   to the recently used resources list
 *
 * Since: 2.10
 */
gboolean
854 855
gtk_recent_manager_add_item (GtkRecentManager *manager,
                             const gchar      *uri)
856
{
857
  GFile* file;
858

859
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), FALSE);
860 861
  g_return_val_if_fail (uri != NULL, FALSE);

862
  file = g_file_new_for_uri (uri);
863

864 865 866 867 868
  g_file_query_info_async (file,
                           G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE,
                           G_PRIORITY_DEFAULT,
                           G_FILE_QUERY_INFO_NONE,
                           NULL,
869
                           gtk_recent_manager_add_item_query_info,
870
                           g_object_ref (manager));
871

872
  g_object_unref (file);
873

874
  return TRUE;
875 876 877 878
}

/**
 * gtk_recent_manager_add_full:
879
 * @manager: a #GtkRecentManager
880 881 882 883
 * @uri: a valid URI
 * @recent_data: metadata of the resource
 *
 * Adds a new resource, pointed by @uri, into the recently used
884 885
 * resources list, using the metadata specified inside the
 * #GtkRecentData-struct passed in @recent_data.
886 887 888 889 890 891
 *
 * The passed URI will be used to identify this resource inside the
 * list.
 *
 * In order to register the new recently used resource, metadata about
 * the resource must be passed as well as the URI; the metadata is
892
 * stored in a #GtkRecentData-struct, which must contain the MIME
893 894 895 896
 * type of the resource pointed by the URI; the name of the application
 * that is registering the item, and a command line to be used when
 * launching the item.
 *
897
 * Optionally, a #GtkRecentData-struct might contain a UTF-8 string
898 899 900
 * to be used when viewing the item instead of the last component of
 * the URI; a short description of the item; whether the item should
 * be considered private - that is, should be displayed only by the
901 902
 * applications that have registered it.
 *
903
 * Returns: %TRUE if the new item was successfully added to the
904
 *     recently used resources list, %FALSE otherwise
905 906 907 908
 *
 * Since: 2.10
 */
gboolean
909 910 911
gtk_recent_manager_add_full (GtkRecentManager    *manager,
                             const gchar         *uri,
                             const GtkRecentData *data)
912 913
{
  GtkRecentManagerPrivate *priv;
914 915
  GtkSettings *settings;
  gboolean enabled;
916

917
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), FALSE);
918 919 920 921 922 923 924
  g_return_val_if_fail (uri != NULL, FALSE);
  g_return_val_if_fail (data != NULL, FALSE);

  /* sanity checks */
  if ((data->display_name) &&
      (!g_utf8_validate (data->display_name, -1, NULL)))
    {
925
      g_warning ("Attempting to add '%s' to the list of recently used "
926 927 928
                 "resources, but the display name is not a valid UTF-8 "
                 "encoded string",
                 uri);
929 930
      return FALSE;
    }
931

932 933 934
  if ((data->description) &&
      (!g_utf8_validate (data->description, -1, NULL)))
    {
935
      g_warning ("Attempting to add '%s' to the list of recently used "
936 937 938
                 "resources, but the description is not a valid UTF-8 "
                 "encoded string",
                 uri);
939 940 941
      return FALSE;
    }

942

943 944
  if (!data->mime_type)
    {
945
      g_warning ("Attempting to add '%s' to the list of recently used "
946 947
                 "resources, but no MIME type was defined",
                 uri);
948 949
      return FALSE;
    }
950

951 952
  if (!data->app_name)
    {
953
      g_warning ("Attempting to add '%s' to the list of recently used "
954 955 956
                 "resources, but no name of the application that is "
                 "registering it was defined",
                 uri);
957 958
      return FALSE;
    }
959

960 961
  if (!data->app_exec)
    {
962
      g_warning ("Attempting to add '%s' to the list of recently used "
963 964 965
                 "resources, but no command line for the application "
                 "that is registering it was defined",
                 uri);
966 967
      return FALSE;
    }
968 969 970 971 972 973

  settings = gtk_settings_get_default ();
  g_object_get (G_OBJECT (settings), "gtk-recent-files-enabled", &enabled, NULL);
  if (!enabled)
    return TRUE;

974
  priv = manager->priv;
975 976 977 978 979 980 981

  if (!priv->recent_items)
    {
      priv->recent_items = g_bookmark_file_new ();
      priv->size = 0;
    }

982
  if (data->display_name)
983
    g_bookmark_file_set_title (priv->recent_items, uri, data->display_name);
984

985 986 987 988
  if (data->description)
    g_bookmark_file_set_description (priv->recent_items, uri, data->description);

  g_bookmark_file_set_mime_type (priv->recent_items, uri, data->mime_type);
989

990
  if (data->groups && ((char*)data->groups)[0] != '\0')
991 992
    {
      gint j;
993

994 995 996
      for (j = 0; (data->groups)[j] != NULL; j++)
        g_bookmark_file_add_group (priv->recent_items, uri, (data->groups)[j]);
    }
997

998 999 1000 1001 1002
  /* register the application; this will take care of updating the
   * registration count and time in case the application has
   * already registered the same document inside the list
   */
  g_bookmark_file_add_application (priv->recent_items, uri,
1003 1004 1005
                                   data->app_name,
                                   data->app_exec);

1006
  g_bookmark_file_set_is_private (priv->recent_items, uri,
1007 1008
                                  data->is_private);

1009 1010 1011 1012
  /* mark us as dirty, so that when emitting the "changed" signal we
   * will dump our changes
   */
  priv->is_dirty = TRUE;
1013
  gtk_recent_manager_changed (manager);
1014

1015 1016 1017 1018 1019
  return TRUE;
}

/**
 * gtk_recent_manager_remove_item:
1020
 * @manager: a #GtkRecentManager
1021
 * @uri: the URI of the item you wish to remove
1022
 * @error: (allow-none): return location for a #GError, or %NULL
1023 1024 1025 1026
 *
 * Removes a resource pointed by @uri from the recently used resources
 * list handled by a recent manager.
 *
1027
 * Returns: %TRUE if the item pointed by @uri has been successfully
1028
 *   removed by the recently used resources list, and %FALSE otherwise
1029 1030 1031 1032
 *
 * Since: 2.10
 */
gboolean
1033
gtk_recent_manager_remove_item (GtkRecentManager  *manager,
1034 1035
                                const gchar       *uri,
                                GError           **error)
1036 1037 1038 1039
{
  GtkRecentManagerPrivate *priv;
  GError *remove_error = NULL;

1040
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), FALSE);
1041 1042
  g_return_val_if_fail (uri != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1043

1044
  priv = manager->priv;
1045

1046 1047 1048 1049 1050
  if (!priv->recent_items)
    {
      priv->recent_items = g_bookmark_file_new ();
      priv->size = 0;

1051
      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1052 1053 1054
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);
1055 1056 1057 1058 1059 1060 1061

      return FALSE;
    }

  g_bookmark_file_remove_item (priv->recent_items, uri, &remove_error);
  if (remove_error)
    {
1062
      g_error_free (remove_error);
1063 1064

      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1065 1066 1067 1068
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);

1069 1070 1071 1072
      return FALSE;
    }

  priv->is_dirty = TRUE;
1073
  gtk_recent_manager_changed (manager);
1074

1075 1076 1077 1078 1079
  return TRUE;
}

/**
 * gtk_recent_manager_has_item:
1080
 * @manager: a #GtkRecentManager
1081 1082 1083 1084 1085
 * @uri: a URI
 *
 * Checks whether there is a recently used resource registered
 * with @uri inside the recent manager.
 *
1086
 * Returns: %TRUE if the resource was found, %FALSE otherwise
1087 1088 1089 1090
 *
 * Since: 2.10
 */
gboolean
1091
gtk_recent_manager_has_item (GtkRecentManager *manager,
1092
                             const gchar      *uri)
1093 1094 1095
{
  GtkRecentManagerPrivate *priv;

1096
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), FALSE);
1097 1098
  g_return_val_if_fail (uri != NULL, FALSE);

1099
  priv = manager->priv;
1100 1101 1102 1103 1104
  g_return_val_if_fail (priv->recent_items != NULL, FALSE);

  return g_bookmark_file_has_item (priv->recent_items, uri);
}

1105
static void
1106 1107
build_recent_info (GBookmarkFile *bookmarks,
                   GtkRecentInfo *info)
1108 1109 1110 1111 1112 1113
{
  gchar **apps, **groups;
  gsize apps_len, groups_len, i;

  g_assert (bookmarks != NULL);
  g_assert (info != NULL);
1114

1115 1116 1117
  info->display_name = g_bookmark_file_get_title (bookmarks, info->uri, NULL);
  info->description = g_bookmark_file_get_description (bookmarks, info->uri, NULL);
  info->mime_type = g_bookmark_file_get_mime_type (bookmarks, info->uri, NULL);
1118

1119
  info->is_private = g_bookmark_file_get_is_private (bookmarks, info->uri, NULL);
1120

1121 1122 1123
  info->added = g_bookmark_file_get_added (bookmarks, info->uri, NULL);
  info->modified = g_bookmark_file_get_modified (bookmarks, info->uri, NULL);
  info->visited = g_bookmark_file_get_visited (bookmarks, info->uri, NULL);
1124

1125 1126 1127 1128
  groups = g_bookmark_file_get_groups (bookmarks, info->uri, &groups_len, NULL);
  for (i = 0; i < groups_len; i++)
    {
      gchar *group_name = g_strdup (groups[i]);
1129

1130 1131 1132 1133
      info->groups = g_slist_append (info->groups, group_name);
    }

  g_strfreev (groups);
1134

1135 1136 1137 1138 1139 1140 1141 1142
  apps = g_bookmark_file_get_applications (bookmarks, info->uri, &apps_len, NULL);
  for (i = 0; i < apps_len; i++)
    {
      gchar *app_name, *app_exec;
      guint count;
      time_t stamp;
      RecentAppInfo *app_info;
      gboolean res;
1143

1144
      app_name = apps[i];
1145

1146
      res = g_bookmark_file_get_app_info (bookmarks, info->uri, app_name,
1147 1148 1149 1150
                                          &app_exec,
                                          &count,
                                          &stamp,
                                          NULL);
1151 1152
      if (!res)
        continue;
1153

1154 1155 1156 1157
      app_info = recent_app_info_new (app_name);
      app_info->exec = app_exec;
      app_info->count = count;
      app_info->stamp = stamp;
1158

1159
      info->applications = g_slist_prepend (info->applications, app_info);
1160 1161
      g_hash_table_replace (info->apps_lookup, app_info->name, app_info);
    }
1162

1163 1164 1165 1166 1167
  g_strfreev (apps);
}

/**
 * gtk_recent_manager_lookup_item:
1168
 * @manager: a #GtkRecentManager
1169
 * @uri: a URI
1170
 * @error: (allow-none): a return location for a #GError, or %NULL
1171 1172
 *
 * Searches for a URI inside the recently used resources list, and
1173
 * returns a #GtkRecentInfo-struct containing informations about the resource
1174 1175
 * like its MIME type, or its display name.
 *
1176
 * Returns: (nullable): a #GtkRecentInfo-struct containing information
1177
 *   about the resource pointed by @uri, or %NULL if the URI was
1178
 *   not registered in the recently used resources list. Free with
1179
 *   gtk_recent_info_unref().
Matthias Clasen's avatar
Matthias Clasen committed
1180 1181 1182
 *
 * Since: 2.10
 */
1183
GtkRecentInfo *
1184
gtk_recent_manager_lookup_item (GtkRecentManager  *manager,
1185 1186
                                const gchar       *uri,
                                GError           **error)
1187 1188 1189
{
  GtkRecentManagerPrivate *priv;
  GtkRecentInfo *info = NULL;
1190

1191
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), NULL);
1192 1193
  g_return_val_if_fail (uri != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1194

1195
  priv = manager->priv;
1196 1197 1198 1199 1200 1201
  if (!priv->recent_items)
    {
      priv->recent_items = g_bookmark_file_new ();
      priv->size = 0;

      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1202 1203 1204
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);
1205 1206 1207

      return NULL;
    }
1208

1209 1210 1211
  if (!g_bookmark_file_has_item (priv->recent_items, uri))
    {
      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1212 1213 1214
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);
1215 1216
      return NULL;
    }
1217

1218 1219
  info = gtk_recent_info_new (uri);
  g_return_val_if_fail (info != NULL, NULL);
1220

1221
  /* fill the RecentInfo structure with the data retrieved by our
1222
   * parser object from the storage file
1223
   */
1224 1225
  build_recent_info (priv->recent_items, info);

1226
  return info;
1227 1228 1229 1230 1231 1232
}

/**
 * gtk_recent_manager_move_item:
 * @manager: a #GtkRecentManager
 * @uri: the URI of a recently used resource
1233 1234
 * @new_uri: (allow-none): the new URI of the recently used resource, or
 *    %NULL to remove the item pointed by @uri in the list
1235
 * @error: (allow-none): a return location for a #GError, or %NULL
1236 1237
 *
 * Changes the location of a recently used resource from @uri to @new_uri.
1238
 *
1239 1240 1241
 * Please note that this function will not affect the resource pointed
 * by the URIs, but only the URI used in the recently used resources list.
 *
1242
 * Returns: %TRUE on success
1243 1244
 *
 * Since: 2.10
1245
 */
1246 1247
gboolean
gtk_recent_manager_move_item (GtkRecentManager  *recent_manager,
1248 1249 1250
                              const gchar       *uri,
                              const gchar       *new_uri,
                              GError           **error)
1251 1252 1253
{
  GtkRecentManagerPrivate *priv;
  GError *move_error;
1254

1255 1256 1257
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (recent_manager), FALSE);
  g_return_val_if_fail (uri != NULL, FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1258

1259 1260
  priv = recent_manager->priv;

1261 1262 1263
  if (!priv->recent_items)
    {
      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1264 1265 1266
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);
1267 1268 1269
      return FALSE;
    }

1270 1271 1272
  if (!g_bookmark_file_has_item (priv->recent_items, uri))
    {
      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1273 1274 1275
                   GTK_RECENT_MANAGER_ERROR_NOT_FOUND,
                   _("Unable to find an item with URI '%s'"),
                   uri);
1276 1277
      return FALSE;
    }
1278

1279
  move_error = NULL;
1280 1281 1282 1283
  if (!g_bookmark_file_move_item (priv->recent_items,
                                  uri,
                                  new_uri,
                                  &move_error))
1284
    {
1285 1286 1287
      g_error_free (move_error);

      g_set_error (error, GTK_RECENT_MANAGER_ERROR,
1288 1289 1290
                   GTK_RECENT_MANAGER_ERROR_UNKNOWN,
                   _("Unable to move the item with URI '%s' to '%s'"),
                   uri, new_uri);
1291 1292
      return FALSE;
    }
1293

1294 1295
  priv->is_dirty = TRUE;
  gtk_recent_manager_changed (recent_manager);
1296

1297 1298 1299 1300 1301
  return TRUE;
}

/**
 * gtk_recent_manager_get_items:
1302
 * @manager: a #GtkRecentManager
1303 1304 1305
 *
 * Gets the list of recently used resources.
 *
1306
 * Returns: (element-type GtkRecentInfo) (transfer full): a list of
1307
 *   newly allocated #GtkRecentInfo objects. Use
1308 1309 1310 1311 1312 1313
 *   gtk_recent_info_unref() on each item inside the list, and then
 *   free the list itself using g_list_free().
 *
 * Since: 2.10
 */
GList *
1314
gtk_recent_manager_get_items (GtkRecentManager *manager)
1315 1316 1317 1318 1319
{
  GtkRecentManagerPrivate *priv;
  GList *retval = NULL;
  gchar **uris;
  gsize uris_len, i;
1320

1321
  g_return_val_if_fail (GTK_IS_RECENT_MANAGER (manager), NULL);
1322

1323
  priv = manager->priv;
1324 1325
  if (!priv->recent_items)
    return NULL;
1326

1327 1328 1329 1330
  uris = g_bookmark_file_get_uris (priv->recent_items, &uris_len);
  for (i = 0; i < uris_len; i++)
    {
      GtkRecentInfo *info;
1331

1332
      info = gtk_recent_info_new (uris[i]);
1333
      build_recent_info (priv->recent_items, info);
1334

1335 1336
      retval = g_list_prepend (retval, info);
    }
1337

1338
  g_strfreev (uris);
1339

1340 1341 1342 1343 1344
  return retval;
}

static void
purge_recent_items_list (GtkRecentManager  *manager,
1345
                         GError           **error)
1346 1347 1348
{
  GtkRecentManagerPrivate *priv = manager->priv;

1349
  if (priv->recent_items == NULL)
1350
    return;
1351

1352 1353 1354
  g_bookmark_file_free (priv->recent_items);
  priv->recent_items = g_bookmark_file_new ();
  priv->size = 0;
1355

1356
  /* emit the changed signal, to ensure that the purge is written */
1357
  priv->is_dirty = TRUE;
1358 1359 1360 1361 1362
  gtk_recent_manager_changed (manager);
}

/**
 * gtk_recent_manager_purge_items:
1363
 * @manager: a #GtkRecentManager
1364
 * @error: (allow-none): a return location for a #GError, or %NULL
1365 1366 1367
 *
 * Purges every item from the recently used resources list.
 *
1368
 * Returns: the number of items that have been removed from the
1369
 *   recently used resources list
1370 1371 1372 1373
 *
 * Since: 2.10
 */
gint
1374
gtk_recent_manager_purge_items (GtkRecentManager  *manager,
1375
                                GError           **error)
1376 1377 1378
{
  GtkRecentManagerPrivate *priv;
  gint count, purged;
Matthias Clasen's avatar