summaryrefslogtreecommitdiff
blob: 1ebd8e3dd55136b9ff11f2047e455202b870e92e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
239
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
From 34d5352c1f30d92b10667574cb7fcc1cf7e9af66 Mon Sep 17 00:00:00 2001
From: Eugene Popov <popov895@ukr.net>
Date: Sat, 6 Nov 2021 18:49:37 +0000
Subject: [PATCH] [KCommandBar] Dynamic column widths + shortcuts alignment

---
 src/kcommandbar.cpp        | 278 +++++++++++++++++++++----------------
 src/kcommandbarmodel_p.cpp |  17 +--
 src/kcommandbarmodel_p.h   |   9 +-
 tests/kcommandbartest.cpp  |   9 ++
 4 files changed, 176 insertions(+), 137 deletions(-)

diff --git a/src/kcommandbar.cpp b/src/kcommandbar.cpp
index 0d17ffa0..4d0987d7 100644
--- a/src/kcommandbar.cpp
+++ b/src/kcommandbar.cpp
@@ -16,6 +16,7 @@
 #include <QTextLayout>
 #include <QTreeView>
 #include <QVBoxLayout>
+#include <QHeaderView>
 
 #include <KConfigGroup>
 #include <KFuzzyMatcher>
@@ -147,32 +148,24 @@ public:
 
     void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
     {
-        QStyleOptionViewItem options = option;
-        initStyleOption(&options, index);
-
         painter->save();
 
-        // paint background
-        if (option.state & QStyle::State_Selected) {
-            painter->fillRect(option.rect, option.palette.highlight());
-        } else {
-            painter->fillRect(option.rect, option.palette.base());
-        }
-
         /**
          * Draw everything, (widget, icon etc) except the text
          */
-        options.text = QString(); // clear old text
-        QStyle *style = options.widget->style();
-        style->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget);
+        QStyleOptionViewItem optionCopy = option;
+        initStyleOption(&optionCopy, index);
+        optionCopy.text.clear(); // clear old text
+        QStyle *style = option.widget->style();
+        style->drawControl(QStyle::CE_ItemViewItem, &optionCopy, painter, option.widget);
 
-        const int hMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &options, options.widget);
+        const int hMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, option.widget);
 
         QRect outputRect = option.rect;
 
         const CommandBarFilterModel *model = static_cast<const CommandBarFilterModel*>(index.model());
         if (model->hasActionsWithIcons()) {
-            const int iconWidth = options.decorationSize.width() + hMargin;
+            const int iconWidth = option.decorationSize.width() + hMargin;
             if (option.direction == Qt::RightToLeft) {
                 outputRect.adjust(0, 0, -iconWidth, 0);
             } else {
@@ -198,7 +191,7 @@ public:
         }
 
         QTextCharFormat fmt;
-        fmt.setForeground(options.palette.link().color());
+        fmt.setForeground(option.palette.link().color());
         fmt.setFontWeight(QFont::Bold);
 
         /**
@@ -206,13 +199,13 @@ public:
          */
         const auto fmtRanges = KFuzzyMatcher::matchedRanges(m_filterString, str);
         QTextCharFormat f;
-        f.setForeground(options.palette.link());
+        f.setForeground(option.palette.link());
         std::transform(fmtRanges.begin(), fmtRanges.end(), std::back_inserter(formats), [f, actionNameStart](const KFuzzyMatcher::Range &fr) {
             return QTextLayout::FormatRange{fr.start + actionNameStart, fr.length, f};
         });
 
         outputRect.adjust(hMargin, 0, -hMargin, 0);
-        paintItemText(painter, original, outputRect, options, std::move(formats));
+        paintItemText(painter, original, outputRect, option, std::move(formats));
 
         painter->restore();
     }
@@ -240,122 +233,159 @@ public:
         return shortcutString.split(QLatin1String(", "), Qt::SkipEmptyParts);
     }
 
+    // returns the width needed to draw the shortcut
+    static int shortcutDrawingWidth(const QStyleOptionViewItem &option, const QString &shortcut, int hMargin)
+    {
+        int width = 0;
+        if (!shortcut.isEmpty()) {
+            // adapt the shortcut as it will be drawn
+            // "Ctrl+A, Alt+B" => "Ctrl+A+Alt+B"
+            QString adaptedShortcut = shortcut;
+            adaptedShortcut.replace(QStringLiteral(", "), QStringLiteral("+"));
+
+            width = option.fontMetrics.horizontalAdvance(adaptedShortcut);
+
+            // count the number of segments
+            // "Ctrl+A+Alt+B" => ["Ctrl", "+", "A", "+", "Alt", "+", "B"]
+            static const QRegularExpression regExp(QStringLiteral("(\\+(?!\\+)|\\+(?=\\+{2}))"));
+            const int segmentsCount = 2 * adaptedShortcut.count(regExp) + 1;
+
+            // add left and right margins for each segment
+            width += segmentsCount * 2 * hMargin;
+        }
+
+        return width;
+    }
+
     void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
     {
-        QStyleOptionViewItem options = option;
-        initStyleOption(&options, index);
-        painter->save();
+        // draw background
+        option.widget->style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);
 
         const QString shortcutString = index.data().toString();
-
-        // paint background
-        if (option.state & QStyle::State_Selected) {
-            painter->fillRect(option.rect, option.palette.highlight());
-        } else {
-            painter->fillRect(option.rect, option.palette.base());
+        if (shortcutString.isEmpty()) {
+            return;
         }
 
-        options.text = QString(); // clear old text
-        options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter, options.widget);
-
-        if (!shortcutString.isEmpty()) {
-            /**
-             * Shortcut string splitting
-             *
-             * We do it in two steps
-             * 1. Split on ", " so that if we have multi modifier shortcuts they are nicely
-             *    split into strings.
-             * 2. Split each shortcut from step 1 into individual string.
-             *
-             * Example:
-             *
-             * "Ctrl+,, Alt+:"
-             * Step 1: [ "Ctrl+," , "Alt+:"]
-             * Step 2: [ "Ctrl", ",", "Alt", ":"]
-             */
-            const QStringList spaceSplitted = splitShortcutString(shortcutString);
-            QStringList list;
-            list.reserve(spaceSplitted.size() * 2);
-            for (const QString &shortcut : spaceSplitted) {
-                list += shortcut.split(QLatin1Char('+'), Qt::SkipEmptyParts);
-                if (shortcut.endsWith(QLatin1Char('+'))) {
-                    list.append(QStringLiteral("+"));
-                }
+        /**
+            * Shortcut string splitting
+            *
+            * We do it in two steps
+            * 1. Split on ", " so that if we have multi modifier shortcuts they are nicely
+            *    split into strings.
+            * 2. Split each shortcut from step 1 into individual string.
+            *
+            * Example:
+            *
+            * "Ctrl+,, Alt+:"
+            * Step 1: [ "Ctrl+," , "Alt+:"]
+            * Step 2: [ "Ctrl", ",", "Alt", ":"]
+            */
+        const QStringList spaceSplitted = splitShortcutString(shortcutString);
+        QStringList list;
+        list.reserve(spaceSplitted.size() * 2);
+        for (const QString &shortcut : spaceSplitted) {
+            list += shortcut.split(QLatin1Char('+'), Qt::SkipEmptyParts);
+            if (shortcut.endsWith(QLatin1Char('+'))) {
+                list.append(QStringLiteral("+"));
             }
+        }
 
-            /**
-             * Create rects for each string from the previous step
-             *
-             * @todo boundingRect may give issues here, use horizontalAdvance
-             * @todo We probably dont need the full rect, just the width so the
-             * "btns" vector can just be vector<pair<int, string>>
-             */
-            QVector<QPair<QRect, QString>> btns;
-            btns.reserve(list.size());
-            const int height = options.rect.height();
-            for (const QString &text : std::as_const(list)) {
-                if (text.isEmpty()) {
-                    continue;
-                }
-                QRect r = option.fontMetrics.boundingRect(text);
-                // this happens on gnome so we manually decrease the
-                // height a bit
-                if (r.height() == height) {
-                    r.setHeight(r.height() - 4);
-                }
-                r.setWidth(r.width() + 8);
-                btns.append({r, text});
+        /**
+            * Create rects for each string from the previous step
+            *
+            * @todo We probably dont need the full rect, just the width so the
+            * "btns" vector can just be vector<pair<int, string>>
+            */
+        QVector<QPair<QRect, QString>> btns;
+        btns.reserve(list.size());
+        const int height = option.rect.height();
+        const int hMargin = horizontalMargin(option);
+        for (const QString &text : std::as_const(list)) {
+            if (text.isEmpty()) {
+                continue;
             }
-
-            // we have nothing, just return
-            if (btns.isEmpty()) {
-                return;
+            QRect r(0, 0, option.fontMetrics.horizontalAdvance(text), option.fontMetrics.lineSpacing());
+            // this happens on gnome so we manually decrease the
+            // height a bit
+            if (r.height() == height) {
+                r.setHeight(r.height() - 4);
             }
+            r.setWidth(r.width() + 2 * hMargin);
+            btns.append({r, text});
+        }
+
+        // we have nothing, just return
+        if (btns.isEmpty()) {
+            return;
+        }
+
+        const QRect plusRect = option.fontMetrics.boundingRect(QLatin1Char('+'));
 
-            const QRect plusRect = option.fontMetrics.boundingRect(QLatin1Char('+'));
-
-            // draw them
-            int x = option.rect.x();
-            const int y = option.rect.y();
-            const int plusY = option.rect.y() + plusRect.height() / 2;
-            const int total = btns.size();
-
-            // make sure our rects are nicely V-center aligned in the row
-            painter->translate(QPoint(0, (option.rect.height() - btns.at(0).first.height()) / 2));
-
-            int i = 0;
-            painter->setRenderHint(QPainter::Antialiasing);
-            for (const auto &btn : std::as_const(btns)) {
-                painter->setPen(Qt::NoPen);
-                const QRect &rect = btn.first;
-
-                QRect buttonRect(x, y, rect.width(), rect.height());
-
-                // draw rounded rect shadow
-                auto shadowRect = buttonRect.translated(0, 1);
-                painter->setBrush(option.palette.shadow());
-                painter->drawRoundedRect(shadowRect, 3.0, 3.0);
-
-                // draw rounded rect itself
-                painter->setBrush(option.palette.button());
-                painter->drawRoundedRect(buttonRect, 3.0, 3.0);
-
-                // draw text inside rounded rect
-                painter->setPen(option.palette.buttonText().color());
-                painter->drawText(buttonRect, Qt::AlignCenter, btn.second);
-
-                // draw '+'
-                if (i + 1 < total) {
-                    x += rect.width() + 5;
-                    painter->drawText(QPoint(x, plusY + (rect.height() / 2)), QStringLiteral("+"));
-                    x += plusRect.width() + 5;
-                }
-                i++;
+        // draw them
+        int x;
+        if (option.direction == Qt::RightToLeft) {
+            x = option.rect.x() + hMargin;
+        } else {
+            x = option.rect.right() - shortcutDrawingWidth(option, shortcutString, hMargin) - hMargin;
+        }
+        const int y = option.rect.y() + (option.rect.height() - btns.at(0).first.height()) / 2;
+        const int plusY = option.rect.y() + (option.rect.height() - plusRect.height()) / 2;
+        const int total = btns.size();
+
+        int i = 0;
+        painter->save();
+        painter->setRenderHint(QPainter::Antialiasing);
+        for (const auto &btn : std::as_const(btns)) {
+            painter->setPen(Qt::NoPen);
+            const QRect &rect = btn.first;
+
+            QRect buttonRect(x, y, rect.width(), rect.height());
+
+            // draw rounded rect shadow
+            auto shadowRect = buttonRect.translated(0, 1);
+            painter->setBrush(option.palette.shadow());
+            painter->drawRoundedRect(shadowRect, 3.0, 3.0);
+
+            // draw rounded rect itself
+            painter->setBrush(option.palette.button());
+            painter->drawRoundedRect(buttonRect, 3.0, 3.0);
+
+            // draw text inside rounded rect
+            painter->setPen(option.palette.buttonText().color());
+            painter->drawText(buttonRect, Qt::AlignCenter, btn.second);
+
+            // draw '+'
+            if (i + 1 < total) {
+                x += rect.width() + hMargin;
+                painter->drawText(QPoint(x, plusY + (rect.height() / 2)), QStringLiteral("+"));
+                x += plusRect.width() + hMargin;
             }
+            i++;
         }
 
         painter->restore();
     }
+
+    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
+    {
+        if (index.isValid() && index.column() == KCommandBarModel::Column_Shortcut) {
+            QString shortcut = index.data().toString();
+            if (!shortcut.isEmpty()) {
+                const int hMargin = horizontalMargin(option);
+                const int width = shortcutDrawingWidth(option, shortcut, hMargin) + 2 * hMargin;
+
+                return QSize(width, 0);
+            }
+        }
+
+        return QStyledItemDelegate::sizeHint(option, index);
+    }
+
+    int horizontalMargin(const QStyleOptionViewItem &option) const
+    {
+        return option.widget->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, &option) + 2;
+    }
 };
 
 // BEGIN KCommandBarPrivate
@@ -410,9 +440,6 @@ void KCommandBarPrivate::updateViewGeometry(KCommandBar *q)
 
     const QSize viewMaxSize(centralSize.width() / 2.4, centralSize.height() / 2);
 
-    // First column occupies 60% of the width
-    m_treeView.setColumnWidth(0, viewMaxSize.width() * 0.6);
-
     // Position should be central over window
     const int xPos = std::max(0, (centralSize.width() - viewMaxSize.width()) / 2);
     const int yPos = std::max(0, (centralSize.height() - viewMaxSize.height()) * 1 / 4);
@@ -505,8 +532,8 @@ KCommandBar::KCommandBar(QWidget *parent)
 
     CommandBarStyleDelegate *delegate = new CommandBarStyleDelegate(this);
     ShortcutStyleDelegate *del = new ShortcutStyleDelegate(this);
-    d->m_treeView.setItemDelegateForColumn(0, delegate);
-    d->m_treeView.setItemDelegateForColumn(1, del);
+    d->m_treeView.setItemDelegateForColumn(KCommandBarModel::Column_Command, delegate);
+    d->m_treeView.setItemDelegateForColumn(KCommandBarModel::Column_Shortcut, del);
 
     connect(&d->m_lineEdit, &QLineEdit::returnPressed, this, [this]() {
         d->slotReturnPressed(this);
@@ -525,6 +552,11 @@ KCommandBar::KCommandBar(QWidget *parent)
     d->m_treeView.setSortingEnabled(true);
     d->m_treeView.setModel(&d->m_proxyModel);
 
+    d->m_treeView.header()->setMinimumSectionSize(0);
+    d->m_treeView.header()->setStretchLastSection(false);
+    d->m_treeView.header()->setSectionResizeMode(KCommandBarModel::Column_Command, QHeaderView::Stretch);
+    d->m_treeView.header()->setSectionResizeMode(KCommandBarModel::Column_Shortcut, QHeaderView::ResizeToContents);
+
     d->m_treeView.installEventFilter(this);
     d->m_lineEdit.installEventFilter(this);
 
diff --git a/src/kcommandbarmodel_p.cpp b/src/kcommandbarmodel_p.cpp
index fee271c5..6a172c9c 100644
--- a/src/kcommandbarmodel_p.cpp
+++ b/src/kcommandbarmodel_p.cpp
@@ -69,12 +69,9 @@ void KCommandBarModel::refresh(const QVector<KCommandBar::ActionGroup> &actionGr
     QVector<Item> temp_rows;
     std::unordered_set<QAction *> uniqueActions;
     temp_rows.reserve(totalActions);
-    int actionGroupIdx = 0;
     for (const auto &ag : actionGroups) {
         const auto &agActions = ag.actions;
         fillRows(temp_rows, ag.name, agActions, uniqueActions);
-
-        actionGroupIdx++;
     }
 
     /**
@@ -117,22 +114,16 @@ QVariant KCommandBarModel::data(const QModelIndex &index, int role) const
 
     switch (role) {
     case Qt::DisplayRole:
-        if (col == 0) {
+        if (col == Column_Command) {
             return entry.displayName();
-        } else {
-            return entry.action->shortcut().toString();
         }
+        Q_ASSERT(col == Column_Shortcut);
+        return entry.action->shortcut().toString();
     case Qt::DecorationRole:
-        if (col == 0) {
+        if (col == Column_Command) {
             return entry.action->icon();
         }
         break;
-    case Qt::TextAlignmentRole:
-        if (col == 0) {
-            return Qt::AlignLeft;
-        } else {
-            return Qt::AlignRight;
-        }
     case Qt::ToolTipRole: {
         QString toolTip = entry.displayName();
         if (!entry.action->shortcut().isEmpty()) {
diff --git a/src/kcommandbarmodel_p.h b/src/kcommandbarmodel_p.h
index 29a0249c..af547104 100644
--- a/src/kcommandbarmodel_p.h
+++ b/src/kcommandbarmodel_p.h
@@ -29,6 +29,13 @@ public:
 
     enum Role { Score = Qt::UserRole + 1 };
 
+    enum Column
+    {
+        Column_Command,
+        Column_Shortcut,
+        Column_Count
+    };
+
     /**
      * Resets the model
      *
@@ -48,7 +55,7 @@ public:
     int columnCount(const QModelIndex &parent = QModelIndex()) const override
     {
         Q_UNUSED(parent);
-        return 2;
+        return Column_Count;
     }
 
     /**
diff --git a/tests/kcommandbartest.cpp b/tests/kcommandbartest.cpp
index 46e1bc86..1c631bbb 100644
--- a/tests/kcommandbartest.cpp
+++ b/tests/kcommandbartest.cpp
@@ -103,6 +103,9 @@ public:
         for (; i < 2; ++i) {
             acts[1].actions.append(genAction(this, QStringLiteral("folder"), i));
         }
+        acts[1].actions[0]->setShortcut(QStringLiteral("G"));
+        acts[1].actions[1]->setCheckable(true);
+        acts[1].actions[1]->setShortcut(QStringLiteral("Ctrl++"));
 
         acts[2].name = QStringLiteral("Second Menu Group - Disabled acts");
         for (; i < 4; ++i) {
@@ -116,6 +119,8 @@ public:
         for (; i < 6; ++i) {
             acts[3].actions.append(genAction(this, QStringLiteral("security-low"), i, Qt::CTRL | Qt::ALT));
         }
+        acts[3].actions[0]->setCheckable(true);
+        acts[3].actions[0]->setShortcut(QStringLiteral("Ctrl+,, Ctrl++, Ctrl+K"));
 
         return acts;
     }
@@ -128,10 +133,14 @@ public:
         acts[0].name = QStringLiteral("مینو گروپ");
         acts[0].actions = {new QAction(QIcon::fromTheme("folder"), QStringLiteral("یہ فولڈر ایکشن ہے"), this),
                            new QAction(QIcon::fromTheme("folder"), QStringLiteral("یہ ایک اور فولڈر ایکشن ہے"), this)};
+        acts[0].actions[1]->setCheckable(true);
+        acts[0].actions[1]->setShortcut(QStringLiteral("Ctrl+Shift++"));
 
         acts[1].name = QStringLiteral("گروپ");
         acts[1].actions = {new QAction(QIcon::fromTheme("zoom-out"), QStringLiteral("یہ فولڈر ایکشن ہے"), this),
                            new QAction(QIcon::fromTheme("security-low"), QStringLiteral("یہ ایک اور فولڈر ایکشن ہے"), this)};
+        acts[1].actions[1]->setCheckable(true);
+        acts[1].actions[1]->setShortcut(QStringLiteral("Ctrl+-"));
 
         return acts;
     }
-- 
GitLab