File: ktreeviewsearchline.cpp

package info (click to toggle)
plasma-sdk 6.5.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,264 kB
  • sloc: cpp: 4,446; xml: 452; sh: 27; makefile: 12
file content (611 lines) | stat: -rw-r--r-- 17,832 bytes parent folder | download | duplicates (3)
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
/*
   SPDX-FileCopyrightText: 2003 Scott Wheeler <wheeler@kde.org>
   SPDX-FileCopyrightText: 2005 Rafal Rzepecki <divide@users.sourceforge.net>
   SPDX-FileCopyrightText: 2006 Hamish Rodda <rodda@kde.org>
   SPDX-FileCopyrightText: 2007 Pino Toscano <pino@kde.org>

   SPDX-License-Identifier: LGPL-2.0-only
*/

#include "ktreeviewsearchline.h"

#include <QActionGroup>
#include <QApplication>
#include <QContextMenuEvent>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QList>
#include <QMenu>
#include <QTimer>
#include <QToolButton>
#include <QTreeView>

#include <QDebug>
#include <klocalizedstring.h>

class KTreeViewSearchLinePrivate
{
public:
    KTreeViewSearchLinePrivate(KTreeViewSearchLine *_parent)
        : parent(_parent)
        , caseSensitive(Qt::CaseInsensitive)
        , activeSearch(false)
        , keepParentsVisible(true)
        , canChooseColumns(true)
        , queuedSearches(0)
    {
    }

    KTreeViewSearchLine *parent;
    QList<QTreeView *> treeViews;
    Qt::CaseSensitivity caseSensitive;
    bool activeSearch;
    bool keepParentsVisible;
    bool canChooseColumns;
    QString search;
    int queuedSearches;
    QList<int> searchColumns;

    void rowsInserted(QAbstractItemModel *model, const QModelIndex &parent, int start, int end) const;
    void treeViewDeleted(QObject *treeView);
    void slotColumnActivated(QAction *action);
    void slotAllVisibleColumns();

    void checkColumns();
    void checkItemParentsNotVisible(QTreeView *treeView);
    bool checkItemParentsVisible(QTreeView *treeView, const QModelIndex &index);
};

////////////////////////////////////////////////////////////////////////////////
// private slots
////////////////////////////////////////////////////////////////////////////////
void KTreeViewSearchLine::rowsInserted(const QModelIndex &parentIndex, int start, int end) const
{
    QAbstractItemModel *model = qobject_cast<QAbstractItemModel *>(sender());
    d->rowsInserted(model, parentIndex, start, end);
}

void KTreeViewSearchLinePrivate::rowsInserted(QAbstractItemModel *model, const QModelIndex &parentIndex, int start, int end) const
{
    // QAbstractItemModel* model = qobject_cast<QAbstractItemModel*>( parent->sender() );
    if (!model) {
        return;
    }

    const auto it = std::find_if(treeViews.cbegin(), treeViews.cend(), [=](QTreeView *tree) {
        return tree->model() == model;
    });
    if (it == treeViews.cend()) {
        return;
    }

    QTreeView *widget = *it;
    for (int i = start; i <= end; ++i) {
        widget->setRowHidden(i, parentIndex, !parent->itemMatches(parentIndex, i, parent->text()));
    }
}

void KTreeViewSearchLinePrivate::treeViewDeleted(QObject *object)
{
    treeViews.removeAll(static_cast<QTreeView *>(object));
    parent->setEnabled(treeViews.isEmpty());
}

void KTreeViewSearchLinePrivate::slotColumnActivated(QAction *action)
{
    if (!action) {
        return;
    }

    bool ok;
    int column = action->data().toInt(&ok);

    if (!ok) {
        return;
    }

    if (action->isChecked()) {
        if (!searchColumns.isEmpty()) {
            if (!searchColumns.contains(column)) {
                searchColumns.append(column);
            }

            if (searchColumns.count() == treeViews.first()->header()->count() - treeViews.first()->header()->hiddenSectionCount()) {
                searchColumns.clear();
            }

        } else {
            searchColumns.append(column);
        }
    } else {
        if (searchColumns.isEmpty()) {
            QHeaderView *const header = treeViews.first()->header();

            for (int i = 0; i < header->count(); i++) {
                if (i != column && !header->isSectionHidden(i)) {
                    searchColumns.append(i);
                }
            }

        } else if (searchColumns.contains(column)) {
            searchColumns.removeAll(column);
        }
    }

    parent->updateSearch();
}

void KTreeViewSearchLinePrivate::slotAllVisibleColumns()
{
    if (searchColumns.isEmpty()) {
        searchColumns.append(0);
    } else {
        searchColumns.clear();
    }

    parent->updateSearch();
}

////////////////////////////////////////////////////////////////////////////////
// private methods
////////////////////////////////////////////////////////////////////////////////

void KTreeViewSearchLinePrivate::checkColumns()
{
    canChooseColumns = parent->canChooseColumnsCheck();
}

void KTreeViewSearchLinePrivate::checkItemParentsNotVisible(QTreeView *treeView)
{
    Q_UNUSED(treeView)

// TODO: PORT ME
#if 0
  QTreeWidgetItemIterator it( treeWidget );

  for ( ; *it; ++it ) {
    QTreeWidgetItem *item = *it;
    item->treeWidget()->setItemHidden( item, !parent->itemMatches( item, search ) );
  }
#endif
}

/** Check whether \p item, its siblings and their descendents should be shown. Show or hide the items as necessary.
 *
 *  \p item  The list view item to start showing / hiding items at. Typically, this is the first child of another item, or the
 *              the first child of the list view.
 *  \return \c true if an item which should be visible is found, \c false if all items found should be hidden. If this function
 *             returns true and \p highestHiddenParent was not 0, highestHiddenParent will have been shown.
 */
bool KTreeViewSearchLinePrivate::checkItemParentsVisible(QTreeView *treeView, const QModelIndex &index)
{
    bool childMatch = false;
    const int rowcount = treeView->model()->rowCount(index);
    for (int i = 0; i < rowcount; ++i) {
        childMatch |= checkItemParentsVisible(treeView, treeView->model()->index(i, 0, index));
    }

    // Should this item be shown? It should if any children should be, or if it matches.
    const QModelIndex parentindex = index.parent();
    if (childMatch || parent->itemMatches(parentindex, index.row(), search)) {
        treeView->setRowHidden(index.row(), parentindex, false);
        return true;
    }

    treeView->setRowHidden(index.row(), parentindex, true);

    return false;
}

////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////

KTreeViewSearchLine::KTreeViewSearchLine(QWidget *parent, QTreeView *treeView)
    : KLineEdit(parent)
    , d(new KTreeViewSearchLinePrivate(this))
{
    connect(this, &QLineEdit::textChanged, this, &KTreeViewSearchLine::queueSearch);

    setClearButtonEnabled(true);
    setTreeView(treeView);

    if (!treeView) {
        setEnabled(false);
    }
}

KTreeViewSearchLine::KTreeViewSearchLine(QWidget *parent, const QList<QTreeView *> &treeViews)
    : KLineEdit(parent)
    , d(new KTreeViewSearchLinePrivate(this))
{
    connect(this, &QLineEdit::textChanged, this, &KTreeViewSearchLine::queueSearch);

    setClearButtonEnabled(true);
    setTreeViews(treeViews);
}

KTreeViewSearchLine::~KTreeViewSearchLine()
{
    delete d;
}

Qt::CaseSensitivity KTreeViewSearchLine::caseSensitivity() const
{
    return d->caseSensitive;
}

QList<int> KTreeViewSearchLine::searchColumns() const
{
    if (d->canChooseColumns) {
        return d->searchColumns;
    } else {
        return QList<int>();
    }
}

bool KTreeViewSearchLine::keepParentsVisible() const
{
    return d->keepParentsVisible;
}

QTreeView *KTreeViewSearchLine::treeView() const
{
    if (d->treeViews.count() == 1) {
        return d->treeViews.first();
    } else {
        return nullptr;
    }
}

QList<QTreeView *> KTreeViewSearchLine::treeViews() const
{
    return d->treeViews;
}

////////////////////////////////////////////////////////////////////////////////
// public slots
////////////////////////////////////////////////////////////////////////////////

void KTreeViewSearchLine::addTreeView(QTreeView *treeView)
{
    if (treeView) {
        connectTreeView(treeView);

        d->treeViews.append(treeView);
        setEnabled(!d->treeViews.isEmpty());

        d->checkColumns();
    }
}

void KTreeViewSearchLine::removeTreeView(QTreeView *treeView)
{
    if (treeView) {
        int index = d->treeViews.indexOf(treeView);

        if (index != -1) {
            d->treeViews.removeAt(index);
            d->checkColumns();

            disconnectTreeView(treeView);

            setEnabled(!d->treeViews.isEmpty());
        }
    }
}

void KTreeViewSearchLine::updateSearch(const QString &pattern)
{
    d->search = pattern.isNull() ? text() : pattern;

    for (QTreeView *treeView : std::as_const(d->treeViews)) {
        updateSearch(treeView);
    }
}

void KTreeViewSearchLine::updateSearch(QTreeView *treeView)
{
    if (!treeView || !treeView->model()->rowCount()) {
        return;
    }

    // If there's a selected item that is visible, make sure that it's visible
    // when the search changes too (assuming that it still matches).

    QModelIndex currentIndex = treeView->currentIndex();

    bool wasUpdateEnabled = treeView->updatesEnabled();
    treeView->setUpdatesEnabled(false);
    if (d->keepParentsVisible) {
        for (int i = 0; i < treeView->model()->rowCount(); ++i) {
            d->checkItemParentsVisible(treeView, treeView->rootIndex());
        }
    } else {
        d->checkItemParentsNotVisible(treeView);
    }
    treeView->setUpdatesEnabled(wasUpdateEnabled);

    if (currentIndex.isValid()) {
        treeView->scrollTo(currentIndex);
    }
}

void KTreeViewSearchLine::setCaseSensitivity(Qt::CaseSensitivity caseSensitive)
{
    if (d->caseSensitive != caseSensitive) {
        d->caseSensitive = caseSensitive;
        updateSearch();
    }
}

void KTreeViewSearchLine::setKeepParentsVisible(bool visible)
{
    if (d->keepParentsVisible != visible) {
        d->keepParentsVisible = visible;
        updateSearch();
    }
}

void KTreeViewSearchLine::setSearchColumns(const QList<int> &columns)
{
    if (d->canChooseColumns) {
        d->searchColumns = columns;
    }
}

void KTreeViewSearchLine::setTreeView(QTreeView *treeView)
{
    setTreeViews(QList<QTreeView *>());
    addTreeView(treeView);
}

void KTreeViewSearchLine::setTreeViews(const QList<QTreeView *> &treeViews)
{
    for (QTreeView *treeView : std::as_const(d->treeViews)) {
        disconnectTreeView(treeView);
    }

    d->treeViews = treeViews;

    for (QTreeView *treeView : std::as_const(d->treeViews)) {
        connectTreeView(treeView);
    }

    d->checkColumns();

    setEnabled(!d->treeViews.isEmpty());
}

////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////

bool KTreeViewSearchLine::itemMatches(const QModelIndex &index, int row, const QString &pattern) const
{
    if (pattern.isEmpty()) {
        return true;
    }

    if (!index.isValid()) {
        return false;
    }

    // If the search column list is populated, search just the columns
    // specifified.  If it is empty default to searching all of the columns.

    const int columncount = index.model()->columnCount(index);
    if (!d->searchColumns.isEmpty()) {
        QList<int>::ConstIterator it = d->searchColumns.constBegin();
        for (; it != d->searchColumns.constEnd(); ++it) {
            if (*it < columncount && index.model()->index(row, *it, index).data(Qt::DisplayRole).toString().indexOf(pattern, 0, d->caseSensitive) >= 0) {
                return true;
            }
        }
    } else {
        for (int i = 0; i < columncount; ++i) {
            if (index.model()->index(row, i, index).data(Qt::DisplayRole).toString().indexOf(pattern, 0, d->caseSensitive) >= 0) {
                return true;
            }
        }
    }

    return false;
}

void KTreeViewSearchLine::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *popup = KLineEdit::createStandardContextMenu();

    if (d->canChooseColumns) {
        popup->addSeparator();
        QMenu *subMenu = popup->addMenu(i18n("Search Columns"));

        QAction *allVisibleColumnsAction = subMenu->addAction(i18n("All Visible Columns"), this, SLOT(slotAllVisibleColumns()));
        allVisibleColumnsAction->setCheckable(true);
        allVisibleColumnsAction->setChecked(!d->searchColumns.count());
        subMenu->addSeparator();

        bool allColumnsAreSearchColumns = true;

        QActionGroup *group = new QActionGroup(popup);
        group->setExclusive(false);
        connect(group, SIGNAL(triggered(QAction *)), SLOT(slotColumnActivated(QAction *)));

        QHeaderView *const header = d->treeViews.first()->header();
        for (int j = 0; j < header->count(); j++) {
            int i = header->logicalIndex(j);

            if (header->isSectionHidden(i)) {
                continue;
            }

            QString columnText = header->model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
            QAction *columnAction = subMenu->addAction(qvariant_cast<QIcon>(header->model()->headerData(i, Qt::Horizontal, Qt::DecorationRole)), columnText);
            columnAction->setCheckable(true);
            columnAction->setChecked(d->searchColumns.isEmpty() || d->searchColumns.contains(i));
            columnAction->setData(i);
            columnAction->setActionGroup(group);

            if (d->searchColumns.isEmpty() || d->searchColumns.indexOf(i) != -1) {
                columnAction->setChecked(true);
            } else {
                allColumnsAreSearchColumns = false;
            }
        }

        allVisibleColumnsAction->setChecked(allColumnsAreSearchColumns);

        // searchColumnsMenuActivated() relies on one possible "all" representation
        if (allColumnsAreSearchColumns && !d->searchColumns.isEmpty()) {
            d->searchColumns.clear();
        }
    }

    popup->exec(event->globalPos());
    delete popup;
}

void KTreeViewSearchLine::connectTreeView(QTreeView *treeView)
{
    connect(treeView, SIGNAL(destroyed(QObject *)), this, SLOT(treeViewDeleted(QObject *)));

    connect(treeView->model(), &QAbstractItemModel::rowsInserted, this, &KTreeViewSearchLine::rowsInserted);
}

void KTreeViewSearchLine::disconnectTreeView(QTreeView *treeView)
{
    disconnect(treeView, SIGNAL(destroyed(QObject *)), this, SLOT(treeViewDeleted(QObject *)));

    disconnect(treeView->model(), &QAbstractItemModel::rowsInserted, this, &KTreeViewSearchLine::rowsInserted);
}

bool KTreeViewSearchLine::canChooseColumnsCheck()
{
    // This is true if either of the following is true:

    // there are no listviews connected
    if (d->treeViews.isEmpty()) {
        return false;
    }

    const QTreeView *first = d->treeViews.first();

    const int numcols = first->model()->columnCount();
    // the listviews have only one column,
    if (numcols < 2) {
        return false;
    }

    QStringList headers;
    for (int i = 0; i < numcols; ++i) {
        headers.append(first->header()->model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString());
    }

    QList<QTreeView *>::ConstIterator it = d->treeViews.constBegin();
    for (++it /* skip the first one */; it != d->treeViews.constEnd(); ++it) {
        // the listviews have different numbers of columns,
        if ((*it)->model()->columnCount() != numcols) {
            return false;
        }

        // the listviews differ in column labels.
        QStringList::ConstIterator jt;
        int i;
        for (i = 0, jt = headers.constBegin(); i < numcols; ++i, ++jt) {
            Q_ASSERT(jt != headers.constEnd());

            if ((*it)->header()->model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString() != *jt) {
                return false;
            }
        }
    }

    return true;
}

////////////////////////////////////////////////////////////////////////////////
// protected slots
////////////////////////////////////////////////////////////////////////////////

void KTreeViewSearchLine::queueSearch(const QString &search)
{
    d->queuedSearches++;
    d->search = search;

    QTimer::singleShot(200, this, &KTreeViewSearchLine::activateSearch);
}

void KTreeViewSearchLine::activateSearch()
{
    --(d->queuedSearches);

    if (d->queuedSearches == 0) {
        updateSearch(d->search);
    }
}

////////////////////////////////////////////////////////////////////////////////
// KTreeViewSearchLineWidget
////////////////////////////////////////////////////////////////////////////////

class KTreeViewSearchLineWidgetPrivate
{
public:
    KTreeViewSearchLineWidgetPrivate()
        : treeView(nullptr)
        , searchLine(nullptr)
    {
    }

    QTreeView *treeView;
    KTreeViewSearchLine *searchLine;
};

KTreeViewSearchLineWidget::KTreeViewSearchLineWidget(QWidget *parent, QTreeView *treeView)
    : QWidget(parent)
    , d(new KTreeViewSearchLineWidgetPrivate)
{
    d->treeView = treeView;

    QTimer::singleShot(0, this, &KTreeViewSearchLineWidget::createWidgets);
}

KTreeViewSearchLineWidget::~KTreeViewSearchLineWidget()
{
    delete d;
}

KTreeViewSearchLine *KTreeViewSearchLineWidget::createSearchLine(QTreeView *treeView) const
{
    return new KTreeViewSearchLine(const_cast<KTreeViewSearchLineWidget *>(this), treeView);
}

void KTreeViewSearchLineWidget::createWidgets()
{
    QLabel *label = new QLabel(i18n("S&earch:"), this);
    label->setObjectName(QLatin1String("kde toolbar widget"));

    searchLine()->show();

    label->setBuddy(d->searchLine);
    label->show();

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setSpacing(5);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(label);
    layout->addWidget(d->searchLine);
}

KTreeViewSearchLine *KTreeViewSearchLineWidget::searchLine() const
{
    if (!d->searchLine) {
        d->searchLine = createSearchLine(d->treeView);
    }

    return d->searchLine;
}

#include "moc_ktreeviewsearchline.cpp"