aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
blob: c80cbf44c6a2ac6ede5df6463f6f5106d21ccc66 (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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "gettingstartedwelcomepage.h"

#include "exampleslistmodel.h"
#include "screenshotcropper.h"

#include <utils/fileutils.h>
#include <utils/pathchooser.h>
#include <utils/winutils.h>

#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/modemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>

#include <QApplication>
#include <QBuffer>
#include <QCloseEvent>
#include <QComboBox>
#include <QDesktopServices>
#include <QDialogButtonBox>
#include <QDir>
#include <QGridLayout>
#include <QHeaderView>
#include <QIdentityProxyModel>
#include <QImage>
#include <QImageReader>
#include <QLabel>
#include <QMessageBox>
#include <QPainter>
#include <QPointer>
#include <QPushButton>
#include <QStyledItemDelegate>
#include <QTableView>
#include <QTime>
#include <QTimer>

using namespace Core;
using namespace Utils;

namespace QtSupport {
namespace Internal {

const char C_FALLBACK_ROOT[] = "ProjectsFallbackRoot";

const int itemWidth = 230;
const int itemHeight = 230;
const int itemGap = 10;
const int tagsSeparatorY = itemHeight - 60;

ExamplesWelcomePage::ExamplesWelcomePage(bool showExamples)
    : m_showExamples(showExamples)
{
}

QString ExamplesWelcomePage::title() const
{
    return m_showExamples ? tr("Examples") : tr("Tutorials");
}

int ExamplesWelcomePage::priority() const
{
    return m_showExamples ? 30 : 40;
}

Id ExamplesWelcomePage::id() const
{
    return m_showExamples ? "Examples" : "Tutorials";
}

QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileInfo, QStringList &filesToOpen, const QStringList& dependencies)
{
    const QString projectDir = proFileInfo.canonicalPath();
    QDialog d(ICore::mainWindow());
    auto lay = new QGridLayout(&d);
    auto descrLbl = new QLabel;
    d.setWindowTitle(tr("Copy Project to writable Location?"));
    descrLbl->setTextFormat(Qt::RichText);
    descrLbl->setWordWrap(false);
    const QString nativeProjectDir = QDir::toNativeSeparators(projectDir);
    descrLbl->setText(QString::fromLatin1("<blockquote>%1</blockquote>").arg(nativeProjectDir));
    descrLbl->setMinimumWidth(descrLbl->sizeHint().width());
    descrLbl->setWordWrap(true);
    descrLbl->setText(tr("<p>The project you are about to open is located in the "
                         "write-protected location:</p><blockquote>%1</blockquote>"
                         "<p>Please select a writable location below and click \"Copy Project and Open\" "
                         "to open a modifiable copy of the project or click \"Keep Project and Open\" "
                         "to open the project in location.</p><p><b>Note:</b> You will not "
                         "be able to alter or compile your project in the current location.</p>")
                      .arg(nativeProjectDir));
    lay->addWidget(descrLbl, 0, 0, 1, 2);
    auto txt = new QLabel(tr("&Location:"));
    auto chooser = new PathChooser;
    txt->setBuddy(chooser);
    chooser->setExpectedKind(PathChooser::ExistingDirectory);
    chooser->setHistoryCompleter(QLatin1String("Qt.WritableExamplesDir.History"));
    QSettings *settings = ICore::settings();
    chooser->setPath(settings->value(QString::fromLatin1(C_FALLBACK_ROOT),
                                     DocumentManager::projectsDirectory().toString()).toString());
    lay->addWidget(txt, 1, 0);
    lay->addWidget(chooser, 1, 1);
    enum { Copy = QDialog::Accepted + 1, Keep = QDialog::Accepted + 2 };
    auto bb = new QDialogButtonBox;
    QPushButton *copyBtn = bb->addButton(tr("&Copy Project and Open"), QDialogButtonBox::AcceptRole);
    connect(copyBtn, &QAbstractButton::released, &d, [&d] { d.done(Copy); });
    copyBtn->setDefault(true);
    QPushButton *keepBtn = bb->addButton(tr("&Keep Project and Open"), QDialogButtonBox::RejectRole);
    connect(keepBtn, &QAbstractButton::released, &d, [&d] { d.done(Keep); });
    lay->addWidget(bb, 2, 0, 1, 2);
    connect(chooser, &PathChooser::validChanged, copyBtn, &QWidget::setEnabled);
    int code = d.exec();
    if (code == Copy) {
        QString exampleDirName = proFileInfo.dir().dirName();
        QString destBaseDir = chooser->path();
        settings->setValue(QString::fromLatin1(C_FALLBACK_ROOT), destBaseDir);
        QDir toDirWithExamplesDir(destBaseDir);
        if (toDirWithExamplesDir.cd(exampleDirName)) {
            toDirWithExamplesDir.cdUp(); // step out, just to not be in the way
            QMessageBox::warning(ICore::mainWindow(), tr("Cannot Use Location"),
                                 tr("The specified location already exists. "
                                    "Please specify a valid location."),
                                 QMessageBox::Ok, QMessageBox::NoButton);
            return QString();
        } else {
            QString error;
            QString targetDir = destBaseDir + QLatin1Char('/') + exampleDirName;
            if (FileUtils::copyRecursively(FilePath::fromString(projectDir),
                    FilePath::fromString(targetDir), &error)) {
                // set vars to new location
                const QStringList::Iterator end = filesToOpen.end();
                for (QStringList::Iterator it = filesToOpen.begin(); it != end; ++it)
                    it->replace(projectDir, targetDir);

                foreach (const QString &dependency, dependencies) {
                    const FilePath targetFile = FilePath::fromString(targetDir)
                            .pathAppended(QDir(dependency).dirName());
                    if (!FileUtils::copyRecursively(FilePath::fromString(dependency), targetFile,
                            &error)) {
                        QMessageBox::warning(ICore::mainWindow(), tr("Cannot Copy Project"), error);
                        // do not fail, just warn;
                    }
                }


                return targetDir + QLatin1Char('/') + proFileInfo.fileName();
            } else {
                QMessageBox::warning(ICore::mainWindow(), tr("Cannot Copy Project"), error);
            }

        }
    }
    if (code == Keep)
        return proFileInfo.absoluteFilePath();
    return QString();
}

void ExamplesWelcomePage::openProject(const ExampleItem &item)
{
    using namespace ProjectExplorer;
    QString proFile = item.projectPath;
    if (proFile.isEmpty())
        return;

    QStringList filesToOpen = item.filesToOpen;
    if (!item.mainFile.isEmpty()) {
        // ensure that the main file is opened on top (i.e. opened last)
        filesToOpen.removeAll(item.mainFile);
        filesToOpen.append(item.mainFile);
    }

    QFileInfo proFileInfo(proFile);
    if (!proFileInfo.exists())
        return;

    // If the Qt is a distro Qt on Linux, it will not be writable, hence compilation will fail
    // Same if it is installed in non-writable location for other reasons
    const bool needsCopy = withNtfsPermissions<bool>([proFileInfo] {
        QFileInfo pathInfo(proFileInfo.path());
        return !proFileInfo.isWritable()
                || !pathInfo.isWritable() /* path of .pro file */
                || !QFileInfo(pathInfo.path()).isWritable() /* shadow build directory */;
    });
    if (needsCopy)
        proFile = copyToAlternativeLocation(proFileInfo, filesToOpen, item.dependencies);

    // don't try to load help and files if loading the help request is being cancelled
    if (proFile.isEmpty())
        return;
    ProjectExplorerPlugin::OpenProjectResult result = ProjectExplorerPlugin::openProject(proFile);
    if (result) {
        ICore::openFiles(filesToOpen);
        ModeManager::activateMode(Core::Constants::MODE_EDIT);
        QUrl docUrl = QUrl::fromUserInput(item.docUrl);
        if (docUrl.isValid())
            HelpManager::showHelpUrl(docUrl, HelpManager::ExternalHelpAlways);
        ModeManager::activateMode(ProjectExplorer::Constants::MODE_SESSION);
    } else {
        ProjectExplorerPlugin::showOpenProjectError(result);
    }
}

//////////////////////////////

static QColor themeColor(Theme::Color role)
{
    return Utils::creatorTheme()->color(role);
}

static QFont sizedFont(int size, const QWidget *widget, bool underline = false)
{
    QFont f = widget->font();
    f.setPixelSize(size);
    f.setUnderline(underline);
    return f;
}

class SearchBox : public WelcomePageFrame
{
public:
    SearchBox(QWidget *parent)
        : WelcomePageFrame(parent)
    {
        QPalette pal;
        pal.setColor(QPalette::Base, themeColor(Theme::Welcome_BackgroundColor));

        m_lineEdit = new FancyLineEdit;
        m_lineEdit->setFiltering(true);
        m_lineEdit->setFrame(false);
        m_lineEdit->setFont(sizedFont(14, this));
        m_lineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
        m_lineEdit->setPalette(pal);

        auto box = new QHBoxLayout(this);
        box->setContentsMargins(10, 3, 3, 3);
        box->addWidget(m_lineEdit);
    }

    FancyLineEdit *m_lineEdit;
};

class GridView : public QTableView
{
public:
    GridView(QWidget *parent)
        : QTableView(parent)
    {
        setVerticalScrollMode(ScrollPerPixel);
        horizontalHeader()->hide();
        horizontalHeader()->setDefaultSectionSize(itemWidth);
        verticalHeader()->hide();
        verticalHeader()->setDefaultSectionSize(itemHeight);
        setMouseTracking(true); // To enable hover.
        setSelectionMode(QAbstractItemView::NoSelection);
        setFrameShape(QFrame::NoFrame);
        setGridStyle(Qt::NoPen);

        QPalette pal;
        pal.setColor(QPalette::Base, themeColor(Theme::Welcome_BackgroundColor));
        setPalette(pal); // Makes a difference on Mac.
    }

    void leaveEvent(QEvent *) final
    {
        QHoverEvent hev(QEvent::HoverLeave, QPointF(), QPointF());
        viewportEvent(&hev); // Seemingly needed to kill the hover paint.
    }
};

class GridProxyModel : public QAbstractItemModel
{
public:
    using OptModelIndex = Utils::optional<QModelIndex>;

    void setSourceModel(QAbstractItemModel *newModel)
    {
        if (m_sourceModel == newModel)
            return;
        if (m_sourceModel)
            disconnect(m_sourceModel, nullptr, this, nullptr);
        m_sourceModel = newModel;
        if (newModel) {
            connect(newModel, &QAbstractItemModel::layoutAboutToBeChanged, this, [this] {
                emit layoutAboutToBeChanged();
            });
            connect(newModel, &QAbstractItemModel::layoutChanged, this, [this] {
                emit layoutChanged();
            });
            connect(newModel, &QAbstractItemModel::modelAboutToBeReset, this, [this] {
                beginResetModel();
            });
            connect(newModel, &QAbstractItemModel::modelReset, this, [this] { endResetModel(); });
            connect(newModel, &QAbstractItemModel::rowsAboutToBeInserted, this, [this] {
                beginResetModel();
            });
            connect(newModel, &QAbstractItemModel::rowsInserted, this, [this] { endResetModel(); });
            connect(newModel, &QAbstractItemModel::rowsAboutToBeRemoved, this, [this] {
                beginResetModel();
            });
            connect(newModel, &QAbstractItemModel::rowsRemoved, this, [this] { endResetModel(); });
        }
    }

    QAbstractItemModel *sourceModel() const
    {
        return m_sourceModel;
    }

    QVariant data(const QModelIndex &index, int role) const final
    {
        const OptModelIndex sourceIndex = mapToSource(index);
        if (sourceIndex)
            return sourceModel()->data(*sourceIndex, role);
        return QVariant();
    }

    Qt::ItemFlags flags(const QModelIndex &index) const final
    {
        const OptModelIndex sourceIndex = mapToSource(index);
        if (sourceIndex)
            return sourceModel()->flags(*sourceIndex);
        return Qt::ItemFlags();
    }

    bool hasChildren(const QModelIndex &parent) const final
    {
        const OptModelIndex sourceParent = mapToSource(parent);
        if (sourceParent)
            return sourceModel()->hasChildren(*sourceParent);
        return false;
    }

    void setColumnCount(int columnCount)
    {
        if (columnCount == m_columnCount)
            return;
        QTC_ASSERT(columnCount >= 1, columnCount = 1);
        m_columnCount = columnCount;
        emit layoutChanged();
    }

    int rowCount(const QModelIndex &parent) const final
    {
        if (parent.isValid())
            return 0;
        int rows = sourceModel()->rowCount(QModelIndex());
        return (rows + m_columnCount - 1) / m_columnCount;
    }

    int columnCount(const QModelIndex &parent) const final
    {
        if (parent.isValid())
            return 0;
        return m_columnCount;
    }

    QModelIndex index(int row, int column, const QModelIndex &) const final
    {
        return createIndex(row, column, nullptr);
    }

    QModelIndex parent(const QModelIndex &) const final
    {
        return QModelIndex();
    }

    // The items at the lower right of the grid might not correspond to source items, if
    // source's row count is not N*columnCount
    OptModelIndex mapToSource(const QModelIndex &proxyIndex) const
    {
        if (!proxyIndex.isValid())
            return QModelIndex();
        int sourceRow = proxyIndex.row() * m_columnCount + proxyIndex.column();
        if (sourceRow < sourceModel()->rowCount())
            return sourceModel()->index(sourceRow, 0);
        return OptModelIndex();
    }

    QModelIndex mapFromSource(const QModelIndex &sourceIndex) const
    {
        if (!sourceIndex.isValid())
            return QModelIndex();
        QTC_CHECK(sourceIndex.column() == 0);
        int proxyRow = sourceIndex.row() / m_columnCount;
        int proxyColumn = sourceIndex.row() % m_columnCount;
        return index(proxyRow, proxyColumn, QModelIndex());
    }

private:
    QAbstractItemModel *m_sourceModel = nullptr;
    int m_columnCount = 1;
};

class ExampleDelegate : public QStyledItemDelegate
{
    Q_OBJECT

public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const final
    {
        const ExampleItem item = index.data(ExamplesListModel::ExampleItemRole).value<ExampleItem>();
        const QRect rc = option.rect;

        // Quick hack for empty items in the last row.
        if (item.name.isEmpty())
            return;

        const int d = 10;
        const int x = rc.x() + d;
        const int y = rc.y() + d;
        const int w = rc.width() - 2 * d - itemGap;
        const int h = rc.height() - 2 * d;
        const bool hovered = option.state & QStyle::State_MouseOver;

        const int tagsBase = tagsSeparatorY + 10;
        const int shiftY = tagsSeparatorY - 20;
        const int nameY = tagsSeparatorY - 20;

        const QRect textRect = QRect(x, y + nameY, w, h);

        QTextOption wrapped;
        wrapped.setWrapMode(QTextOption::WordWrap);
        int offset = 0;
        if (hovered) {
            if (index != m_previousIndex) {
                m_previousIndex = index;
                m_startTime.start();
                m_currentArea = rc;
                m_currentWidget = qobject_cast<QAbstractItemView *>(
                    const_cast<QWidget *>(option.widget));
            }
            offset = m_startTime.elapsed() * itemHeight / 200; // Duration 200 ms.
            if (offset < shiftY)
                QTimer::singleShot(5, this, &ExampleDelegate::goon);
            else if (offset > shiftY)
                offset = shiftY;
        } else {
            m_previousIndex = QModelIndex();
        }

        const QFontMetrics fm(option.widget->font());
        const QRect shiftedTextRect = textRect.adjusted(0, -offset, 0, -offset);

        // The pixmap.
        if (offset == 0) {
            QPixmap pm = index.data(ExamplesListModel::ExampleImageRole).value<QPixmap>();
            QRect inner(x + 11, y - offset, ExamplesListModel::exampleImageSize.width(),
                        ExamplesListModel::exampleImageSize.height());
            QRect pixmapRect = inner;
            if (!pm.isNull()) {
                painter->setPen(foregroundColor2);
                if (!m_showExamples)
                    pixmapRect = inner.adjusted(6, 20, -6, -15);
                QPoint pixmapPos = pixmapRect.center();
                pixmapPos.rx() -= pm.width() / pm.devicePixelRatio() / 2;
                pixmapPos.ry() -= pm.height() / pm.devicePixelRatio() / 2;
                painter->drawPixmap(pixmapPos, pm);
                if (item.isVideo) {
                    painter->setFont(sizedFont(13, option.widget));
                    QString videoLen = item.videoLength;
                    painter->drawText(pixmapRect.adjusted(0, 0, 0, painter->font().pixelSize() + 3),
                                      videoLen, Qt::AlignBottom | Qt::AlignHCenter);
                }
            } else {
                // The description text as fallback.
                painter->setPen(foregroundColor2);
                painter->setFont(sizedFont(11, option.widget));
                painter->drawText(pixmapRect.adjusted(6, 10, -6, -10), item.description, wrapped);
            }
            painter->setPen(foregroundColor1);
            painter->drawRect(pixmapRect.adjusted(-1, -1, -1, -1));
        }

        // The title of the example.
        painter->setPen(foregroundColor1);
        painter->setFont(sizedFont(13, option.widget));
        QRectF nameRect;
        if (offset) {
            nameRect = painter->boundingRect(shiftedTextRect, item.name, wrapped);
            painter->drawText(nameRect, item.name, wrapped);
        } else {
            nameRect = QRect(x, y + nameY, x + w, y + nameY + 20);
            QString elidedName = fm.elidedText(item.name, Qt::ElideRight, w - 20);
            painter->drawText(nameRect, elidedName);
        }

        // The separator line below the example title.
        if (offset) {
            int ll = nameRect.bottom() + 5;
            painter->setPen(lightColor);
            painter->drawLine(x, ll, x + w, ll);
        }

        // The description text.
        if (offset) {
            int dd = nameRect.height() + 10;
            QRect descRect = shiftedTextRect.adjusted(0, dd, 0, dd);
            painter->setPen(foregroundColor2);
            painter->setFont(sizedFont(11, option.widget));
            painter->drawText(descRect, item.description, wrapped);
        }

        // Separator line between text and 'Tags:' section
        painter->setPen(lightColor);
        painter->drawLine(x, y + tagsSeparatorY, x + w, y + tagsSeparatorY);

        // The 'Tags:' section
        const int tagsHeight = h - tagsBase;
        const QFont tagsFont = sizedFont(10, option.widget);
        const QFontMetrics tagsFontMetrics(tagsFont);
        QRect tagsLabelRect = QRect(x, y + tagsBase, 30, tagsHeight - 2);
        painter->setPen(foregroundColor2);
        painter->setFont(tagsFont);
        painter->drawText(tagsLabelRect, ExamplesWelcomePage::tr("Tags:"));

        painter->setPen(themeColor(Theme::Welcome_LinkColor));
        m_currentTagRects.clear();
        int xx = 0;
        int yy = y + tagsBase;
        for (const QString &tag : item.tags) {
            const int ww = tagsFontMetrics.horizontalAdvance(tag) + 5;
            if (xx + ww > w - 30) {
                yy += 15;
                xx = 0;
            }
            const QRect tagRect(xx + x + 30, yy, ww, 15);
            painter->drawText(tagRect, tag);
            m_currentTagRects.append({ tag, tagRect });
            xx += ww;
        }

        // Box it when hovered.
        if (hovered) {
            painter->setPen(lightColor);
            painter->drawRect(rc.adjusted(0, 0, -1, -1));
        }
    }

    void goon()
    {
        if (m_currentWidget)
            m_currentWidget->viewport()->update(m_currentArea);
    }

    bool editorEvent(QEvent *ev, QAbstractItemModel *model,
        const QStyleOptionViewItem &option, const QModelIndex &idx) final
    {
        if (ev->type() == QEvent::MouseButtonRelease) {
            const ExampleItem item = idx.data(Qt::UserRole).value<ExampleItem>();
            auto mev = static_cast<QMouseEvent *>(ev);
            if (idx.isValid()) {
                const QPoint pos = mev->pos();
                if (pos.y() > option.rect.y() + tagsSeparatorY) {
                    //const QStringList tags = idx.data(Tags).toStringList();
                    for (const auto &it : m_currentTagRects) {
                        if (it.second.contains(pos))
                            emit tagClicked(it.first);
                    }
                } else {
                    if (item.isVideo)
                        QDesktopServices::openUrl(QUrl::fromUserInput(item.videoUrl));
                    else if (item.hasSourceCode)
                        ExamplesWelcomePage::openProject(item);
                    else
                        HelpManager::showHelpUrl(QUrl::fromUserInput(item.docUrl),
                                                       HelpManager::ExternalHelpAlways);
                }
            }
        }
        return QStyledItemDelegate::editorEvent(ev, model, option, idx);
    }

    void setShowExamples(bool showExamples) { m_showExamples = showExamples; goon(); }

signals:
    void tagClicked(const QString &tag);

private:
    const QColor lightColor = QColor(221, 220, 220); // color: "#dddcdc"
    const QColor backgroundColor = themeColor(Theme::Welcome_BackgroundColor);
    const QColor foregroundColor1 = themeColor(Theme::Welcome_ForegroundPrimaryColor); // light-ish.
    const QColor foregroundColor2 = themeColor(Theme::Welcome_ForegroundSecondaryColor); // blacker.

    mutable QPersistentModelIndex m_previousIndex;
    mutable QTime m_startTime;
    mutable QRect m_currentArea;
    mutable QPointer<QAbstractItemView> m_currentWidget;
    mutable QVector<QPair<QString, QRect>> m_currentTagRects;
    bool m_showExamples = true;
};

class ExamplesPageWidget : public QWidget
{
public:
    ExamplesPageWidget(bool isExamples)
        : m_isExamples(isExamples)
    {
        m_exampleDelegate.setShowExamples(isExamples);
        const int sideMargin = 27;
        static auto s_examplesModel = new ExamplesListModel(this);
        m_examplesModel = s_examplesModel;

        auto filteredModel = new ExamplesListModelFilter(m_examplesModel, !m_isExamples, this);

        auto searchBox = new SearchBox(this);
        m_searcher = searchBox->m_lineEdit;

        auto vbox = new QVBoxLayout(this);
        vbox->setContentsMargins(30, sideMargin, 0, 0);

        auto hbox = new QHBoxLayout;
        if (m_isExamples) {
            m_searcher->setPlaceholderText(ExamplesWelcomePage::tr("Search in Examples..."));

            auto exampleSetSelector = new QComboBox(this);
            exampleSetSelector->setMinimumWidth(itemWidth);
            exampleSetSelector->setMaximumWidth(itemWidth);
            ExampleSetModel *exampleSetModel = m_examplesModel->exampleSetModel();
            exampleSetSelector->setModel(exampleSetModel);
            exampleSetSelector->setCurrentIndex(exampleSetModel->selectedExampleSet());
            connect(exampleSetSelector, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated),
                    exampleSetModel, &ExampleSetModel::selectExampleSet);
            connect(exampleSetModel, &ExampleSetModel::selectedExampleSetChanged,
                    exampleSetSelector, &QComboBox::setCurrentIndex);

            hbox->setSpacing(17);
            hbox->addWidget(exampleSetSelector);
        } else {
            m_searcher->setPlaceholderText(ExamplesWelcomePage::tr("Search in Tutorials..."));
        }
        hbox->addWidget(searchBox);
        hbox->addSpacing(sideMargin);
        vbox->addItem(hbox);

        m_gridModel.setSourceModel(filteredModel);

        auto gridView = new GridView(this);
        gridView->setModel(&m_gridModel);
        gridView->setItemDelegate(&m_exampleDelegate);
        vbox->addWidget(gridView);

        connect(&m_exampleDelegate, &ExampleDelegate::tagClicked,
                this, &ExamplesPageWidget::onTagClicked);
        connect(m_searcher, &QLineEdit::textChanged,
                filteredModel, &ExamplesListModelFilter::setSearchString);
    }

    int bestColumnCount() const
    {
        return qMax(1, width() / (itemWidth + itemGap));
    }

    void resizeEvent(QResizeEvent *ev) final
    {
        QWidget::resizeEvent(ev);
        m_gridModel.setColumnCount(bestColumnCount());
    }

    void onTagClicked(const QString &tag)
    {
        QString text = m_searcher->text();
        m_searcher->setText(text + QString("tag:\"%1\" ").arg(tag));
    }

    const bool m_isExamples;
    ExampleDelegate m_exampleDelegate;
    QPointer<ExamplesListModel> m_examplesModel;
    QLineEdit *m_searcher;
    GridProxyModel m_gridModel;
};

QWidget *ExamplesWelcomePage::createWidget() const
{
    return new ExamplesPageWidget(m_showExamples);
}

} // namespace Internal
} // namespace QtSupport

#include "gettingstartedwelcomepage.moc"