// SPDX-License-Identifier: GPL-3.0-or-later #include "app/editor/colourpicker.h" #include "app/state.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace xpl::editor { void sendLookPreview(const Adjustments &adjustments) { QDBusMessage signal = QDBusMessage::createSignal(QStringLiteral("/fyi/hotsocket/xplasma/Look"), QStringLiteral("fyi.hotsocket.xplasma.Look"), QStringLiteral("Preview")); signal << adjustments.toMap(); QDBusConnection::sessionBus().send(signal); } // --- the slider ---------------------------------------------------------------------------- ColourSlider::ColourSlider(QWidget *parent) : QSlider(Qt::Horizontal, parent) { // (Ticks below: the style's thumb points down, into the strip.) setTickPosition(QSlider::TicksBelow); } void ColourSlider::setColours(std::function colourAt) { m_colourAt = std::move(colourAt); update(); } QSize ColourSlider::sizeHint() const { // (Room under the thumb for the strip's lower half.) return QSize(256, QSlider::sizeHint().height() + 6); } QSize ColourSlider::minimumSizeHint() const { return QSize(120, sizeHint().height()); } // The strip's housing: from the thumb's middle to just past its point, along // the channel the thumb's centre travels, a little wider either side. QRect ColourSlider::housing() const { QStyleOptionSlider opt; initStyleOption(&opt); const QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); const QRect channel = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); const int top = handle.top() + handle.height() / 2 - 1; return QRect(QPoint(channel.left() - 2, top), QPoint(channel.right() + 2, qMin(height() - 1, handle.bottom() + 5))); } int ColourSlider::valueAt(int x) const { QStyleOptionSlider opt; initStyleOption(&opt); const QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); const QRect channel = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); const int span = qMax(1, channel.width() - handle.width()); const int pos = qBound(0, x - channel.left() - handle.width() / 2, span); return QStyle::sliderValueFromPosition(minimum(), maximum(), pos, span); } void ColourSlider::paintEvent(QPaintEvent *) { QPainter p(this); // The housing: the style's progress-bar groove, the colours inside it. QStyleOptionProgressBar bar; bar.initFrom(this); bar.rect = housing(); bar.minimum = 0; bar.maximum = 1; bar.progress = 0; style()->drawControl(QStyle::CE_ProgressBarGroove, &bar, &p, this); const QRect inside = bar.rect.adjusted(2, 2, -2, -2); if (m_colourAt) for (int x = inside.left(); x <= inside.right(); ++x) p.fillRect(QRect(x, inside.top(), 1, inside.height()), m_colourAt(valueAt(x))); // The thumb, over it. QStyleOptionSlider opt; initStyleOption(&opt); opt.subControls = QStyle::SC_SliderHandle; style()->drawComplexControl(QStyle::CC_Slider, &opt, &p, this); } void ColourSlider::mousePressEvent(QMouseEvent *event) { // A click on the strip puts the thumb there (and the drag goes on from it). QStyleOptionSlider opt; initStyleOption(&opt); const QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); if (event->button() == Qt::LeftButton && !handle.contains(event->pos())) setValue(valueAt(event->pos().x())); QSlider::mousePressEvent(event); } // --- the custom colours ---------------------------------------------------------------- namespace { constexpr QSize kWell(22, 18); constexpr int kGap = 4; constexpr int kColumns = 8; } // namespace CustomColours::CustomColours(QWidget *parent) : QWidget(parent) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } void CustomColours::setColours(const QList &colours) { m_colours = colours; m_chosen = -1; resized(); } void CustomColours::append(const QColor &colour) { m_colours.append(colour); resized(); Q_EMIT changed(); } int CustomColours::rows() const { return qMax(1, int((m_colours.size() + kColumns - 1) / kColumns)); } QSize CustomColours::sizeHint() const { return QSize(kColumns * kWell.width() + (kColumns - 1) * kGap, rows() * kWell.height() + (rows() - 1) * kGap); } QRect CustomColours::cell(int index) const { return QRect(QPoint((index % kColumns) * (kWell.width() + kGap), (index / kColumns) * (kWell.height() + kGap)), kWell); } int CustomColours::indexAt(QPoint pos) const { for (int i = 0; i < rows() * kColumns; ++i) if (cell(i).contains(pos)) return i; return -1; } void CustomColours::resized() { updateGeometry(); update(); // (A row more, or one less: the dialog fits round it.) if (QWidget *w = window(); w && w != this) QMetaObject::invokeMethod(w, [w] { w->adjustSize(); }, Qt::QueuedConnection); } void CustomColours::paintEvent(QPaintEvent *) { QPainter p(this); QStyleOptionFrame frame; frame.initFrom(this); frame.state |= QStyle::State_Sunken; frame.lineWidth = 2; frame.midLineWidth = 0; for (int i = 0; i < rows() * kColumns; ++i) { frame.rect = cell(i); style()->drawPrimitive(QStyle::PE_Frame, &frame, &p, this); // (The one being dragged leaves its place empty: it's at the pointer.) if (i < m_colours.size() && i != m_dragging) p.fillRect(cell(i).adjusted(2, 2, -2, -2), m_colours.at(i)); if (i == m_chosen && m_dragging < 0) { p.setPen(palette().color(QPalette::WindowText)); p.drawRect(cell(i).adjusted(0, 0, -1, -1)); } } if (m_dragging >= 0) { const QRect at(m_dragPos - QPoint(kWell.width() / 2, kWell.height() / 2), kWell); frame.rect = at; frame.state &= ~QStyle::State_Sunken; frame.state |= QStyle::State_Raised; style()->drawPrimitive(QStyle::PE_Frame, &frame, &p, this); p.fillRect(at.adjusted(2, 2, -2, -2), m_colours.at(m_dragging)); } } void CustomColours::mousePressEvent(QMouseEvent *event) { const int i = indexAt(event->pos()); if (event->button() != Qt::LeftButton || i < 0 || i >= m_colours.size()) return; m_pressed = i; m_pressPos = event->pos(); } void CustomColours::mouseMoveEvent(QMouseEvent *event) { if (m_pressed < 0) return; if (m_dragging < 0) { if ((event->pos() - m_pressPos).manhattanLength() < QApplication::startDragDistance()) return; m_dragging = m_pressed; } m_dragPos = event->pos(); // Where it'd go: the cell under the pointer -- past the last colour, the // last place (they stay packed, no gaps). const int cols = qBound(0, event->pos().x() / (kWell.width() + kGap), kColumns - 1); const int row = qBound(0, event->pos().y() / (kWell.height() + kGap), rows() - 1); const int target = qMin(int(m_colours.size()) - 1, row * kColumns + cols); if (target != m_dragging) { m_colours.move(m_dragging, target); if (m_chosen == m_dragging) m_chosen = target; m_dragging = target; } update(); } void CustomColours::mouseReleaseEvent(QMouseEvent *event) { if (event->button() != Qt::LeftButton || m_pressed < 0) return; if (m_dragging >= 0) { m_chosen = m_dragging; m_dragging = -1; Q_EMIT changed(); } else { m_chosen = m_pressed; Q_EMIT picked(m_colours.at(m_pressed)); } m_pressed = -1; update(); } void CustomColours::contextMenuEvent(QContextMenuEvent *event) { const int i = indexAt(event->pos()); if (i < 0 || i >= m_colours.size()) return; QMenu menu(this); QAction *remove = menu.addAction(QStringLiteral("&Remove")); if (menu.exec(event->globalPos()) != remove) return; m_colours.removeAt(i); if (m_chosen == i) m_chosen = -1; else if (m_chosen > i) --m_chosen; resized(); Q_EMIT changed(); } // --- the dialog ------------------------------------------------------------------------ namespace { constexpr const char *kCustomKey = "customColours"; constexpr int kMaxChroma = 150; // (beyond any sRGB colour's C*) } // namespace ColourPicker::ColourPicker(const QColor &initial, QWidget *parent) : QDialog(parent) { setWindowTitle(QStringLiteral("Color")); auto *layout = new QVBoxLayout(this); // The colour, and its numbers: as XP's dialog shows Color|Solid beside them. auto *top = new QHBoxLayout; m_swatch = new QLabel; m_swatch->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); m_swatch->setFixedSize(64, 48); top->addWidget(m_swatch); auto *hexRow = new QGridLayout; auto *hexLabel = new QLabel(QStringLiteral("He&x:")); m_hex = new QLineEdit; m_hex->setValidator(new QRegularExpressionValidator(QRegularExpression(QStringLiteral("#?[0-9a-fA-F]{0,6}")), m_hex)); m_hex->setMaximumWidth(m_hex->fontMetrics().horizontalAdvance(QStringLiteral("#000000")) + 16); hexLabel->setBuddy(m_hex); hexRow->addWidget(hexLabel, 0, 0); hexRow->addWidget(m_hex, 0, 1); top->addLayout(hexRow); top->addStretch(1); layout->addLayout(top); auto *grid = new QGridLayout; m_hue = new ColourSlider; m_hue->setRange(0, 359); m_chroma = new ColourSlider; m_chroma->setRange(0, kMaxChroma); m_lightness = new ColourSlider; m_lightness->setRange(0, 100); m_hueValue = new QLabel; m_chromaValue = new QLabel; m_lightnessValue = new QLabel; const struct { const char *label; ColourSlider *slider; QLabel *value; } rows[] = { {"&Hue:", m_hue, m_hueValue}, {"&Color:", m_chroma, m_chromaValue}, {"&Lightness:", m_lightness, m_lightnessValue}}; int row = 0; for (const auto &r : rows) { auto *label = new QLabel(QLatin1String(r.label)); label->setBuddy(r.slider); r.value->setMinimumWidth(r.value->fontMetrics().horizontalAdvance(QStringLiteral("360°"))); r.value->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(label, row, 0); grid->addWidget(r.slider, row, 1); grid->addWidget(r.value, row, 2); connect(r.slider, &QSlider::valueChanged, this, &ColourPicker::slidersMoved); ++row; } layout->addLayout(grid); // Custom colors: rows of eight, as many as they fill; Add puts the colour // last (a new row when the last is full). layout->addWidget(new QLabel(QStringLiteral("Custom colors:"))); m_custom = new CustomColours; QList saved; for (const QJsonValue &v : State::load().settings.value(QLatin1String(kCustomKey)).toArray()) if (const QColor c(v.toString()); c.isValid()) // (empty slots, as first kept, dropped) saved << c; m_custom->setColours(saved); connect(m_custom, &CustomColours::picked, this, [this](const QColor &c) { setLch(toLch(c.rgb())); }); connect(m_custom, &CustomColours::changed, this, &ColourPicker::saveCustom); layout->addWidget(m_custom); auto *add = new QPushButton(QStringLiteral("&Add to Custom Colors")); connect(add, &QPushButton::clicked, this, [this] { m_custom->append(m_colour); }); layout->addWidget(add); auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); layout->addWidget(buttons); connect(m_hex, &QLineEdit::textEdited, this, &ColourPicker::hexEdited); setLch(toLch((initial.isValid() ? initial : QColor(Qt::black)).rgb())); } std::optional ColourPicker::pick(const QColor &initial, QWidget *parent, const std::function &live) { ColourPicker dialog(initial, parent); if (live) connect(&dialog, &ColourPicker::colourChanged, &dialog, live); if (dialog.exec() != QDialog::Accepted) { if (live) live(initial); return std::nullopt; } return dialog.colour(); } void ColourPicker::setLch(const Lch &lch) { m_lch = lch; for (QSlider *s : {static_cast(m_hue), static_cast(m_chroma), static_cast(m_lightness)}) s->blockSignals(true); m_hue->setValue(int(std::lround(lch.h)) % 360); m_chroma->setValue(int(std::lround(std::min(lch.c, double(kMaxChroma))))); m_lightness->setValue(int(std::lround(lch.l))); for (QSlider *s : {static_cast(m_hue), static_cast(m_chroma), static_cast(m_lightness)}) s->blockSignals(false); showColour(); } void ColourPicker::slidersMoved() { m_lch = {double(m_lightness->value()), double(m_chroma->value()), double(m_hue->value())}; showColour(); } void ColourPicker::hexEdited() { QString text = m_hex->text(); if (!text.startsWith(QLatin1Char('#'))) text.prepend(QLatin1Char('#')); if (text.size() != 7) return; const QColor c(text); if (!c.isValid()) return; const int cursor = m_hex->cursorPosition(); m_fromHex = true; setLch(toLch(c.rgb())); m_fromHex = false; m_hex->setCursorPosition(cursor); } void ColourPicker::showColour() { m_colour = QColor(fromLch(m_lch)); QPixmap swatch(m_swatch->size() - QSize(4, 4)); swatch.fill(m_colour); m_swatch->setPixmap(swatch); m_hueValue->setText(QStringLiteral("%1°").arg(m_hue->value())); m_chromaValue->setText(QString::number(m_chroma->value())); m_lightnessValue->setText(QString::number(m_lightness->value())); // (Not from its own typing, which is what moved the sliders. It has the // focus from the start, so focus alone left it showing the first colour.) if (!m_fromHex) m_hex->setText(m_colour.name()); // Each strip: the colours along it, the other two held. const Lch at = m_lch; m_hue->setColours([at](int v) { return QColor(fromLch({at.l, at.c, double(v)})); }); m_chroma->setColours([at](int v) { return QColor(fromLch({at.l, double(v), at.h})); }); m_lightness->setColours([at](int v) { return QColor(fromLch({double(v), at.c, at.h})); }); Q_EMIT colourChanged(m_colour); } void ColourPicker::saveCustom() { State state = State::load(); QJsonArray saved; for (const QColor &c : m_custom->colours()) saved.append(c.name()); state.settings.insert(QLatin1String(kCustomKey), saved); state.save(); } } // namespace xpl::editor