2014-03-13 06:25:09 +08:00
|
|
|
// Aseprite Document Library
|
2015-01-19 09:05:33 +08:00
|
|
|
// Copyright (c) 2001-2015 David Capello
|
2014-03-13 06:25:09 +08:00
|
|
|
//
|
2014-03-30 07:08:05 +08:00
|
|
|
// This file is released under the terms of the MIT license.
|
|
|
|
// Read LICENSE.txt for more information.
|
2014-03-13 06:25:09 +08:00
|
|
|
|
|
|
|
#ifdef HAVE_CONFIG_H
|
|
|
|
#include "config.h"
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#include "doc/object.h"
|
|
|
|
|
2015-01-19 09:05:33 +08:00
|
|
|
#include "base/mutex.h"
|
|
|
|
#include "base/scoped_lock.h"
|
|
|
|
|
|
|
|
#include <unordered_map>
|
|
|
|
|
2014-03-13 06:25:09 +08:00
|
|
|
namespace doc {
|
|
|
|
|
2015-01-19 09:05:33 +08:00
|
|
|
static base::mutex mutex;
|
2014-07-29 11:53:24 +08:00
|
|
|
static ObjectId newId = 0;
|
2015-01-19 09:05:33 +08:00
|
|
|
static std::unordered_map<ObjectId, Object*> objects;
|
2014-07-29 11:53:24 +08:00
|
|
|
|
2014-10-21 09:21:31 +08:00
|
|
|
Object::Object(ObjectType type)
|
|
|
|
: m_type(type)
|
2015-01-19 09:05:33 +08:00
|
|
|
, m_id(0)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
Object::Object(const Object& other)
|
|
|
|
: m_type(other.m_type)
|
|
|
|
, m_id(0) // We don't copy the ID
|
2014-07-29 11:53:24 +08:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
Object::~Object()
|
2014-03-13 06:25:09 +08:00
|
|
|
{
|
2015-01-19 09:05:33 +08:00
|
|
|
if (m_id)
|
|
|
|
setId(0);
|
2014-03-13 06:25:09 +08:00
|
|
|
}
|
|
|
|
|
2014-10-21 09:21:31 +08:00
|
|
|
int Object::getMemSize() const
|
|
|
|
{
|
|
|
|
return sizeof(Object);
|
|
|
|
}
|
|
|
|
|
2015-01-19 09:05:33 +08:00
|
|
|
const ObjectId Object::id() const
|
|
|
|
{
|
|
|
|
// The first time the ID is request, we store the object in the
|
|
|
|
// "objects" hash table.
|
|
|
|
if (!m_id) {
|
|
|
|
base::scoped_unlock hold(mutex);
|
|
|
|
m_id = ++newId;
|
|
|
|
objects.insert(std::make_pair(m_id, const_cast<Object*>(this)));
|
|
|
|
}
|
|
|
|
return m_id;
|
|
|
|
}
|
|
|
|
|
|
|
|
void Object::setId(ObjectId id)
|
|
|
|
{
|
|
|
|
base::scoped_unlock hold(mutex);
|
|
|
|
|
|
|
|
if (m_id) {
|
|
|
|
auto it = objects.find(m_id);
|
|
|
|
ASSERT(it != objects.end());
|
|
|
|
ASSERT(it->second == this);
|
|
|
|
if (it != objects.end())
|
|
|
|
objects.erase(it);
|
|
|
|
}
|
|
|
|
|
|
|
|
m_id = id;
|
|
|
|
|
|
|
|
if (m_id) {
|
|
|
|
ASSERT(objects.find(m_id) == objects.end());
|
|
|
|
objects.insert(std::make_pair(m_id, this));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Object* get_object(ObjectId id)
|
|
|
|
{
|
|
|
|
base::scoped_unlock hold(mutex);
|
|
|
|
auto it = objects.find(id);
|
|
|
|
if (it != objects.end())
|
|
|
|
return it->second;
|
|
|
|
else
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2014-03-13 06:25:09 +08:00
|
|
|
} // namespace doc
|