summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/gtk/g_object_weak_ref.cc
blob: e3c7e90e6aef08659e1762006035f30cbf2d76a0 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (c) 2011 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.

#include "chrome/browser/ui/gtk/g_object_weak_ref.h"

#include "base/logging.h"

class GObjectWeakRef::GObjectWeakRefDelegate
    : public base::RefCounted<GObjectWeakRefDelegate> {
 public:
  explicit GObjectWeakRefDelegate(GObject* object);

  GObject* get() const { return object_; }

 private:
  friend class base::RefCounted<GObjectWeakRefDelegate>;

  ~GObjectWeakRefDelegate();

  static void OnFinalizedThunk(gpointer data, GObject* object);
  void OnFinalized(GObject* object);

  GObject* object_;

  DISALLOW_COPY_AND_ASSIGN(GObjectWeakRefDelegate);
};

GObjectWeakRef::GObjectWeakRefDelegate::GObjectWeakRefDelegate(GObject* object)
    : object_(object) {
  if (object)
    g_object_weak_ref(object, OnFinalizedThunk, this);
}

GObjectWeakRef::GObjectWeakRefDelegate::~GObjectWeakRefDelegate() {
  if (object_)
    g_object_weak_unref(object_, OnFinalizedThunk, this);
}

// static
void GObjectWeakRef::GObjectWeakRefDelegate::OnFinalizedThunk(gpointer data,
                                                              GObject* object) {
  static_cast<GObjectWeakRefDelegate*>(data)->OnFinalized(object);
}

void GObjectWeakRef::GObjectWeakRefDelegate::OnFinalized(GObject* object) {
  DCHECK_EQ(object_, object);
  object_ = NULL;
}

GObjectWeakRef::GObjectWeakRef(GObject* object) {
  reset(object);
}

GObjectWeakRef::GObjectWeakRef(GtkWidget* widget) {
  reset(G_OBJECT(widget));
}

GObjectWeakRef::GObjectWeakRef(const GObjectWeakRef& ref) : ref_(ref.ref_) {}

GObjectWeakRef::~GObjectWeakRef() {}

GObjectWeakRef& GObjectWeakRef::operator=(GObject* object) {
  reset(object);
  return *this;
}

GObjectWeakRef& GObjectWeakRef::operator=(GtkWidget* widget) {
  reset(G_OBJECT(widget));
  return *this;
}

GObjectWeakRef& GObjectWeakRef::operator=(const GObjectWeakRef& ref) {
  ref_ = ref.ref_;
  return *this;
}

GObject* GObjectWeakRef::get() const {
  return ref_->get();
}

void GObjectWeakRef::reset(GObject* object) {
  ref_ = new GObjectWeakRefDelegate(object);
}