From 06950aab233de6a2f47293d59575bb42f6131660 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Wed, 27 Jan 2021 22:06:49 +0100 Subject: Complete rewrite using C++ and with shared state support --- src/xcb_colors.cc | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/xcb_colors.cc (limited to 'src/xcb_colors.cc') diff --git a/src/xcb_colors.cc b/src/xcb_colors.cc new file mode 100644 index 0000000..f4caca4 --- /dev/null +++ b/src/xcb_colors.cc @@ -0,0 +1,93 @@ +#include "common.hh" + +#include "xcb_colors.hh" +#include "xcb_connection.hh" +#include "xcb_event.hh" + +#include +#include +#include + +namespace xcb { + +namespace { + +class ColorsImpl : public Colors { +public: + ColorsImpl(shared_conn conn, xcb_colormap_t colormap) + : conn_(conn), colormap_(colormap), + storage_(std::make_shared()) {} + + Color get_with_fallback(uint8_t r, uint8_t g, uint8_t b, + uint32_t fallback) override { + auto key = make_key(r, g, b); + auto it = index_.find(key); + size_t index; + if (it == index_.end()) { + index = cookie_.size(); + cookie_.push_back(xcb_alloc_color(conn_.get(), colormap_, + static_cast(r) << 8, + static_cast(g) << 8, + static_cast(b) << 8)); + fallback_.push_back(fallback); + index_.emplace(key, index); + } else { + index = it->second; + } + return Color(storage_, index); + } + + bool sync() override { + std::vector colors; + colors.reserve(cookie_.size()); + for (size_t i = 0; i < cookie_.size(); ++i) { + xcb::reply reply( + xcb_alloc_color_reply(conn_.get(), cookie_[i], nullptr)); + if (reply) { + colors.push_back(reply->pixel); + } else { + colors.push_back(fallback_[i]); + } + } + storage_->set(std::move(colors)); + return true; + } + +private: + class StorageImpl : public Storage { + public: + uint32_t get(size_t id) const override { + assert(id < resolved_.size()); + return resolved_[id]; + } + + void set(std::vector resolved) { + resolved_ = std::move(resolved); + } + + private: + std::vector resolved_; + }; + + static uint32_t make_key(uint8_t r, uint8_t g, uint8_t b) { + return static_cast(r) << 16 | + static_cast(g) << 8 | b; + } + + shared_conn conn_; + xcb_colormap_t colormap_; + std::map index_; + std::vector cookie_; + std::vector fallback_; + std::shared_ptr storage_; +}; + +} // namespace + +std::unique_ptr Colors::create(shared_conn conn, + xcb_colormap_t colormap) { + return std::make_unique(conn, colormap); +} + +} // namespace xcb + -- cgit v1.2.3-70-g09d2