Home | History | Annotate | Download | only in libgtk2ui
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef CHROME_BROWSER_UI_LIBGTK2UI_GTK2_SIGNAL_REGISTRAR_H_
      6 #define CHROME_BROWSER_UI_LIBGTK2UI_GTK2_SIGNAL_REGISTRAR_H_
      7 
      8 #include <glib.h>
      9 #include <map>
     10 #include <vector>
     11 
     12 #include "base/basictypes.h"
     13 
     14 typedef void (*GCallback) (void);
     15 typedef struct _GObject GObject;
     16 typedef struct _GtkWidget GtkWidget;
     17 
     18 namespace libgtk2ui {
     19 
     20 // A class that ensures that callbacks don't run on stale owner objects. Similar
     21 // in spirit to NotificationRegistrar. Use as follows:
     22 //
     23 //   class ChromeObject {
     24 //    public:
     25 //     ChromeObject() {
     26 //       ...
     27 //
     28 //       signals_.Connect(widget, "event", CallbackThunk, this);
     29 //     }
     30 //
     31 //     ...
     32 //
     33 //    private:
     34 //     Gtk2SignalRegistrar signals_;
     35 //   };
     36 //
     37 // When |signals_| goes down, it will disconnect the handlers connected via
     38 // Connect.
     39 class Gtk2SignalRegistrar {
     40  public:
     41   Gtk2SignalRegistrar();
     42   ~Gtk2SignalRegistrar();
     43 
     44   // Connect before the default handler. Returns the handler id.
     45   glong Connect(gpointer instance, const gchar* detailed_signal,
     46                 GCallback signal_handler, gpointer data);
     47   // Connect after the default handler. Returns the handler id.
     48   glong ConnectAfter(gpointer instance, const gchar* detailed_signal,
     49                      GCallback signal_handler, gpointer data);
     50 
     51   // Disconnects all signal handlers connected to |instance|.
     52   void DisconnectAll(gpointer instance);
     53 
     54  private:
     55   typedef std::vector<glong> HandlerList;
     56   typedef std::map<GObject*, HandlerList> HandlerMap;
     57 
     58   static void WeakNotifyThunk(gpointer data, GObject* where_the_object_was) {
     59     reinterpret_cast<Gtk2SignalRegistrar*>(data)->WeakNotify(
     60         where_the_object_was);
     61   }
     62   void WeakNotify(GObject* where_the_object_was);
     63 
     64   glong ConnectInternal(gpointer instance, const gchar* detailed_signal,
     65                         GCallback signal_handler, gpointer data, bool after);
     66 
     67   HandlerMap handler_lists_;
     68 
     69   DISALLOW_COPY_AND_ASSIGN(Gtk2SignalRegistrar);
     70 };
     71 
     72 }  // namespace libgtk2ui
     73 
     74 #endif  // CHROME_BROWSER_UI_LIBGTK2UI_GTK2_SIGNAL_REGISTRAR_H_
     75