kis_color_filter_combo.cpp 12.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 *  Copyright (c) 2015 Dmitry Kazakov <dimula73@gmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "kis_color_filter_combo.h"

#include <klocalizedstring.h>
#include <QStylePainter>
#include <QtCore/qmath.h>
#include <QApplication>
25
#include <QProxyStyle>
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <QStyleOption>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QListView>
#include <QMouseEvent>




#include "kis_node_view_color_scheme.h"
#include "kis_debug.h"
#include "kis_icon_utils.h"
#include "krita_utils.h"
#include "kis_node.h"

enum AdditionalRoles {
    OriginalLabelIndex = Qt::UserRole + 1000
};


struct LabelFilteringModel : public QSortFilterProxyModel
{
    LabelFilteringModel(QObject *parent) : QSortFilterProxyModel(parent) {}

50
    bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override {
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        const QModelIndex index = sourceModel()->index(source_row, 0, source_parent);
        const int labelIndex = index.data(OriginalLabelIndex).toInt();


        return labelIndex < 0 || m_acceptedLabels.contains(labelIndex);
    }

    void setAcceptedLabels(const QSet<int> &value) {
        m_acceptedLabels = value;
        invalidateFilter();
    }

private:
    QSet<int> m_acceptedLabels;
};


68 69 70
class ComboEventFilter : public QObject
{
public:
71 72
    ComboEventFilter(KisColorFilterCombo *parent) : m_parent(parent), m_buttonPressed(false) {}

73
protected:
74
    bool eventFilter(QObject *obj, QEvent *event) override {
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        if (event->type() == QEvent::Leave) {
            m_buttonPressed = false;

        } else if (event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mevent = static_cast<QMouseEvent*>(event);
            m_buttonPressed = mevent->button() == Qt::LeftButton;

        } else if (event->type() == QEvent::MouseButtonRelease) {
            QMouseEvent *mevent = static_cast<QMouseEvent*>(event);
            QModelIndex index = m_parent->view()->indexAt(mevent->pos());
            if (!index.isValid()) return false;

            /**
             * We should eat the first event that arrives exactly when
             * the drop down appears on screen.
             */
            if (!m_buttonPressed) return true;

            const bool toUncheckedState = index.data(Qt::CheckStateRole) == Qt::Checked;

            if (toUncheckedState) {
                m_parent->model()->setData(index, Qt::Unchecked, Qt::CheckStateRole);
            } else {
                m_parent->model()->setData(index, Qt::Checked, Qt::CheckStateRole);
            }

            if (index.data(OriginalLabelIndex).toInt() == -1) {
                for (int i = 0; i < m_parent->model()->rowCount(); i++) {
                    const QModelIndex &other = m_parent->model()->index(i, 0);
                    if (other.data(OriginalLabelIndex) != -1) {
                        m_parent->model()->setData(other, toUncheckedState ? Qt::Unchecked : Qt::Checked, Qt::CheckStateRole);
                    }
                }
            } else {
                bool prevChecked = false;
                bool checkedVaries = false;
                QModelIndex allLabelsIndex;

                for (int i = 0; i < m_parent->model()->rowCount(); i++) {
                    const QModelIndex &other = m_parent->model()->index(i, 0);
                    if (other.data(OriginalLabelIndex) != -1) {
                        const bool currentChecked = other.data(Qt::CheckStateRole) == Qt::Checked;

                        if (i == 0) {
                            prevChecked = currentChecked;
                        } else {
                            if (prevChecked != currentChecked) {
                                checkedVaries = true;
                                break;
                            }
                        }
                    } else {
                        allLabelsIndex = other;
                    }
                }

                const bool allLabelsIndexShouldBeChecked =
                    prevChecked && !checkedVaries;

                if (allLabelsIndexShouldBeChecked !=
                    (allLabelsIndex.data(Qt::CheckStateRole) == Qt::Checked)) {

                    m_parent->model()->setData(allLabelsIndex, allLabelsIndexShouldBeChecked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
                }
            }

            emit m_parent->selectedColorsChanged();

            m_buttonPressed = false;
            return true;
        }

        return QObject::eventFilter(obj, event);
    }

150
private:
151 152 153 154 155 156 157
    KisColorFilterCombo *m_parent;
    bool m_buttonPressed;
};

class FullSizedListView : public QListView
{
public:
158
    QSize sizeHint() const override {
159 160 161 162
        return contentsSize();
    }
};

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
class PopupComboBoxStyle : public QProxyStyle
{
public:
    PopupComboBoxStyle(QStyle *baseStyle = nullptr) : QProxyStyle(baseStyle) {}

    int styleHint(QStyle::StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const override
    {
        // This flag makes ComboBox popup float ontop of its parent ComboBox, like in Fusion style.
        // Only when this hint is set will Qt respect combobox popup size hints, otherwise the popup
        // can never exceed the width of its parent ComboBox, like in Breeze style.
        if (hint == QStyle::SH_ComboBox_Popup) {
            return true;
        }

        return QProxyStyle::styleHint(hint, option, widget, returnData);
    }
};

181 182 183 184 185 186 187 188 189 190 191 192
struct KisColorFilterCombo::Private
{
    LabelFilteringModel *filteringModel;
};

KisColorFilterCombo::KisColorFilterCombo(QWidget *parent)
    : QComboBox(parent),
      m_d(new Private)
{
    QStandardItemModel *newModel = new QStandardItemModel(this);
    setModel(newModel);

193 194 195 196
    PopupComboBoxStyle *proxyStyle = new PopupComboBoxStyle(style());
    proxyStyle->setParent(this);
    setStyle(proxyStyle);

197
    setView(new FullSizedListView);
198 199 200 201 202
    m_eventFilters.append(new ComboEventFilter(this));
    m_eventFilters.append(new ComboEventFilter(this));

    view()->installEventFilter(m_eventFilters[0]);
    view()->viewport()->installEventFilter(m_eventFilters[1]);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

    KisNodeViewColorScheme scm;

    QStandardItem* item = new QStandardItem(i18nc("combo box: show all layers", "All"));
    item->setCheckable(true);
    item->setCheckState(Qt::Unchecked);
    item->setData(QColor(Qt::transparent), Qt::BackgroundColorRole);
    item->setData(int(-1), OriginalLabelIndex);
    item->setData(QSize(30, scm.rowHeight()), Qt::SizeHintRole);
    newModel->appendRow(item);

    int labelIndex = 0;
    foreach (const QColor &color, scm.allColorLabels()) {
        const QString title = color.alpha() > 0 ? "" : i18nc("combo box: select all layers without a label", "No Label");

        QStandardItem* item = new QStandardItem(title);
        item->setCheckable(true);
        item->setCheckState(Qt::Unchecked);
        item->setData(color, Qt::BackgroundColorRole);
        item->setData(labelIndex, OriginalLabelIndex);
        item->setData(QSize(30, scm.rowHeight()), Qt::SizeHintRole);
        newModel->appendRow(item);

        labelIndex++;
    }

    m_d->filteringModel = new LabelFilteringModel(this);
    QAbstractItemModel *originalModel = model();
    originalModel->setParent(m_d->filteringModel);

    m_d->filteringModel->setSourceModel(originalModel);
    setModel(m_d->filteringModel);
}

KisColorFilterCombo::~KisColorFilterCombo()
{
239
    qDeleteAll(m_eventFilters);
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
}

void collectAvailableLabels(KisNodeSP root, QSet<int> *labels)
{
    labels->insert(root->colorLabelIndex());

    KisNodeSP node = root->firstChild();
    while (node) {
        collectAvailableLabels(node, labels);
        node = node->nextSibling();
    }
}

void KisColorFilterCombo::updateAvailableLabels(KisNodeSP rootNode)
{
    QSet<int> labels;
    collectAvailableLabels(rootNode, &labels);

    updateAvailableLabels(labels);
}

void KisColorFilterCombo::updateAvailableLabels(const QSet<int> &labels)
{
    m_d->filteringModel->setAcceptedLabels(labels);
}

QList<int> KisColorFilterCombo::selectedColors() const
{
    QList<int> colors;
    for (int i = 0; i < model()->rowCount(); i++) {
        const QModelIndex &other = model()->index(i, 0);
        const int label = other.data(OriginalLabelIndex).toInt();

        if (label != -1 &&
            other.data(Qt::CheckStateRole) == Qt::Checked) {

            colors << label;
        }
    }
    return colors;
}

void KisColorFilterCombo::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QStylePainter painter(this);
    painter.setPen(palette().color(QPalette::Text));

    // draw the combobox frame, focusrect and selected etc.
    QStyleOptionComboBox opt;
    initStyleOption(&opt);
    painter.drawComplexControl(QStyle::CC_ComboBox, opt);

    {
        KisNodeViewColorScheme scm;
        const QRect editRect = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxEditField, this);
        const int size = qMin(editRect.width(), editRect.height());

        const QList<int> selectedColors = this->selectedColors();

        if (selectedColors.size() == 0 || selectedColors.size() == model()->rowCount() - 1) {
            QIcon icon = KisIconUtils::loadIcon("view-filter");
            QPixmap pixmap = icon.pixmap(QSize(size, size), !isEnabled() ? QIcon::Disabled : QIcon::Normal);
            painter.drawPixmap(editRect.right() - size, editRect.top(), pixmap);

        } else if (selectedColors.size() == 1) {
            const int currentLabel = selectedColors.first();
            QColor currentColor = scm.colorLabel(currentLabel);

            if (currentColor.alpha() > 0) {
                painter.fillRect(editRect, currentColor);
            } else if (currentLabel == 0) {
                QPen oldPen = painter.pen();

                const int border = 4;
                QRect crossRect(0, 0, size - 2 * border, size - 2 * border);
                crossRect.moveCenter(editRect.center());

                QColor shade = opt.palette.dark().color();
                painter.setPen(QPen(shade, 2));
                painter.drawLine(crossRect.topLeft(), crossRect.bottomRight());
                painter.drawLine(crossRect.bottomLeft(), crossRect.topRight());
            }
        } else {
            const int border = 0;
            QRect pieRect(0, 0, size - 2 * border, size - 2 * border);
            pieRect.moveCenter(editRect.center());

            const int numColors = selectedColors.size();
            const int step = 16 * 360 / numColors;

            int currentAngle = 0;

            //painter.save(); // optimize out!
            painter.setRenderHint(QPainter::Antialiasing);

            for (int i = 0; i < numColors; i++) {
                QColor color = scm.colorLabel(selectedColors[i]);
                QBrush brush = color.alpha() > 0 ? QBrush(color) : QBrush(Qt::black, Qt::Dense4Pattern);
                painter.setPen(color);
                painter.setBrush(brush);

                painter.drawPie(pieRect, currentAngle, step);
                currentAngle += step;
            }
            //painter.restore(); // optimize out!
        }
    }

    // draw the icon and text
    //painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}

QSize KisColorFilterCombo::minimumSizeHint() const
{
    return sizeHint();
}

QSize KisColorFilterCombo::sizeHint() const
{
    QStyleOptionComboBox opt;
    initStyleOption(&opt);

    const QStyleOption *baseOption = qstyleoption_cast<const QStyleOption *>(&opt);
    const int arrowSize = style()->pixelMetric(QStyle::PM_ScrollBarExtent, baseOption, this);

    const QSize originalHint = QComboBox::sizeHint();
    QSize sh(3 * arrowSize, originalHint.height());

370
    return sh;
371
}