diff --git a/atom/browser/api/trackable_object.cc b/atom/browser/api/trackable_object.cc index fb0762af5bc0..61f36fd904c4 100644 --- a/atom/browser/api/trackable_object.cc +++ b/atom/browser/api/trackable_object.cc @@ -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(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 diff --git a/atom/browser/api/trackable_object.h b/atom/browser/api/trackable_object.h index e3030d32d239..b09fc35be8da 100644 --- a/atom/browser/api/trackable_object.h +++ b/atom/browser/api/trackable_object.h @@ -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_;