/* * Copyright 2026 Joel Klinghed * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "xcb_colors.hh" #include "xcb_connection.hh" #include "xcb_event.hh" #include #include #include #include #include #include #include #include namespace xcb { namespace { class ColorsImpl : public Colors { public: ColorsImpl(shared_conn conn, xcb_colormap_t colormap) : conn_(std::move(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 {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: [[nodiscard]] 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(std::move(conn), colormap); } } // namespace xcb