summaryrefslogtreecommitdiffstats
path: root/app/gtk_signal_registrar.h
blob: 3f14dbe3a6c14483b851924d7da232cca5ecb1fa (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef APP_GTK_SIGNAL_REGISTRAR_H_
#define APP_GTK_SIGNAL_REGISTRAR_H_

#include <glib.h>
#include <map>
#include <vector>

#include "base/basictypes.h"

typedef void (*GCallback) (void);
typedef struct _GObject GObject;
typedef struct _GtkWidget GtkWidget;

// A class that ensures that callbacks don't run on stale owner objects. Similar
// in spirit to NotificationRegistrar. Use as follows:
//
//   class ChromeObject {
//    public:
//     ChromeObject() {
//       ...
//
//       signals_.Connect(widget, "event", CallbackThunk, this);
//     }
//
//     ...
//
//    private:
//     GtkSignalRegistrar signals_;
//   };
//
// When |signals_| goes down, it will disconnect the handlers connected via
// Connect.
class GtkSignalRegistrar {
 public:
  GtkSignalRegistrar();
  ~GtkSignalRegistrar();

  // Connect before the default handler. Returns the handler id.
  glong Connect(gpointer instance, const gchar* detailed_signal,
                GCallback signal_handler, gpointer data);
  // Connect after the default handler. Returns the handler id.
  glong ConnectAfter(gpointer instance, const gchar* detailed_signal,
                     GCallback signal_handler, gpointer data);

 private:
  static void WeakNotifyThunk(gpointer data, GObject* where_the_object_was) {
    reinterpret_cast<GtkSignalRegistrar*>(data)->WeakNotify(
        where_the_object_was);
  }
  void WeakNotify(GObject* where_the_object_was);

  glong ConnectInternal(gpointer instance, const gchar* detailed_signal,
                        GCallback signal_handler, gpointer data, bool after);

  typedef std::vector<glong> HandlerList;
  typedef std::map<GObject*, HandlerList> HandlerMap;
  HandlerMap handler_lists_;

  DISALLOW_COPY_AND_ASSIGN(GtkSignalRegistrar);
};

#endif  // APP_GTK_SIGNAL_REGISTRAR_H_