Enable storing TrackableObject in other C++ class

This commit is contained in:
Cheng Zhao 2015-06-24 14:49:08 +08:00
parent 7f0658efa7
commit 552a12d2ee
2 changed files with 45 additions and 1 deletions

View file

@ -4,8 +4,28 @@
#include "atom/browser/api/trackable_object.h"
#include "base/supports_user_data.h"
namespace mate {
namespace {
const char* kTrackedObjectKey = "TrackedObjectKey";
class IDUserData : public base::SupportsUserData::Data {
public:
explicit IDUserData(int32_t id) : id_(id) {}
operator int32_t() const { return id_; }
private:
int32_t id_;
DISALLOW_COPY_AND_ASSIGN(IDUserData);
};
} // namespace
atom::IDWeakMap TrackableObject::weak_map_;
// static
@ -20,6 +40,15 @@ TrackableObject* TrackableObject::FromWeakMapID(v8::Isolate* isolate,
return self;
}
// static
TrackableObject* TrackableObject::FromWrappedClass(
v8::Isolate* isolate, base::SupportsUserData* wrapped) {
auto id = static_cast<IDUserData*>(wrapped->GetUserData(kTrackedObjectKey));
if (!id)
return nullptr;
return FromWeakMapID(isolate, *id);
}
// static
void TrackableObject::ReleaseAllWeakReferences() {
weak_map_.Clear();
@ -36,4 +65,8 @@ void TrackableObject::AfterInit(v8::Isolate* isolate) {
weak_map_id_ = weak_map_.Add(isolate, GetWrapper(isolate));
}
void TrackableObject::Attach(base::SupportsUserData* wrapped) {
wrapped->SetUserData(kTrackedObjectKey, new IDUserData(weak_map_id_));
}
} // namespace mate

View file

@ -8,15 +8,23 @@
#include "atom/browser/api/event_emitter.h"
#include "atom/common/id_weak_map.h"
namespace base {
class SupportsUserData;
}
namespace mate {
// All instances of TrackableObject will be kept in a weak map and can be got
// from its ID.
class TrackableObject : public mate::EventEmitter {
public:
// Find out the TrackableObject from its ID in weak map:
// Find out the TrackableObject from its ID in weak map.
static TrackableObject* FromWeakMapID(v8::Isolate* isolate, int32_t id);
// Find out the TrackableObject from the class it wraps.
static TrackableObject* FromWrappedClass(
v8::Isolate* isolate, base::SupportsUserData* wrapped);
// Releases all weak references in weak map, called when app is terminating.
static void ReleaseAllWeakReferences();
@ -30,6 +38,9 @@ class TrackableObject : public mate::EventEmitter {
TrackableObject();
~TrackableObject() override;
// Wrap TrackableObject into a class that SupportsUserData.
void Attach(base::SupportsUserData* wrapped);
private:
static atom::IDWeakMap weak_map_;