From 535e2005870ce6e0822418307bde22b09b8db3df Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Thu, 8 Sep 2011 00:11:48 +0000 Subject: [PATCH] Add a BufferManager singleton class, handling buffer lifetime it also provide access to buffers by name --- src/buffer.cc | 5 ++++ src/buffer_manager.cc | 60 +++++++++++++++++++++++++++++++++++++++++++ src/buffer_manager.hh | 32 +++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 src/buffer_manager.cc create mode 100644 src/buffer_manager.hh diff --git a/src/buffer.cc b/src/buffer.cc index 5e42a295..2a09cc5b 100644 --- a/src/buffer.cc +++ b/src/buffer.cc @@ -1,4 +1,7 @@ #include "buffer.hh" + +#include "buffer_manager.hh" + #include namespace Kakoune @@ -122,6 +125,8 @@ Buffer::Buffer(const std::string& name, const BufferString& initial_content) : m_name(name), m_history(1), m_history_cursor(m_history.begin()), m_content(initial_content) { + BufferManager::instance().register_buffer(this); + compute_lines(); } diff --git a/src/buffer_manager.cc b/src/buffer_manager.cc new file mode 100644 index 00000000..9d4cd506 --- /dev/null +++ b/src/buffer_manager.cc @@ -0,0 +1,60 @@ +#include "buffer_manager.hh" + +#include "buffer.hh" +#include "window.hh" +#include + +namespace Kakoune +{ + +struct name_not_unique {}; + + +BufferManager* BufferManager::ms_instance = nullptr; + +BufferManager& BufferManager::instance() +{ + if (not ms_instance) + ms_instance = new BufferManager(); + + return *ms_instance; +} + +void BufferManager::delete_instance() +{ + delete ms_instance; + ms_instance = nullptr; +} + +BufferManager::BufferManager() +{ +} + +void BufferManager::register_buffer(Buffer* buffer) +{ + assert(buffer); + const std::string& name = buffer->name(); + if (m_buffers.find(name) != m_buffers.end()) + throw name_not_unique(); + + m_buffers[name] = std::unique_ptr(buffer); +} + +void BufferManager::delete_buffer(Buffer* buffer) +{ + assert(buffer); + auto buffer_it = m_buffers.find(buffer->name()); + assert(buffer_it->second.get() == buffer); + m_buffers.erase(buffer_it); +} + +Buffer* BufferManager::get_buffer(const std::string& name) +{ + if (m_buffers.find(name) == m_buffers.end()) + return nullptr; + + return m_buffers[name].get(); +} + + +} diff --git a/src/buffer_manager.hh b/src/buffer_manager.hh new file mode 100644 index 00000000..06fb04f0 --- /dev/null +++ b/src/buffer_manager.hh @@ -0,0 +1,32 @@ +#ifndef buffer_manager_hh_INCLUDED +#define buffer_manager_hh_INCLUDED + +#include "buffer.hh" + +#include +#include + +namespace Kakoune +{ + +class BufferManager +{ +public: + void register_buffer(Buffer* buffer); + void delete_buffer(Buffer* buffer); + + Buffer* get_buffer(const std::string& name); + + static BufferManager& instance(); + static void delete_instance(); + +private: + BufferManager(); + static BufferManager* ms_instance; + + std::unordered_map> m_buffers; +}; + +} + +#endif // buffer_manager_hh_INCLUDED