locatorwidget.cpp 21.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3
4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8
9
10
11
** 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
Eike Ziller's avatar
Eike Ziller committed
12
13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18
19
20
21
22
23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25
26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27
28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
con's avatar
con committed
30

hjk's avatar
hjk committed
31
#include "locator.h"
32
#include "locatorwidget.h"
con's avatar
con committed
33
#include "locatorconstants.h"
34
#include "locatorsearchutils.h"
35
#include "ilocatorfilter.h"
con's avatar
con committed
36

37
#include <coreplugin/coreicons.h>
con's avatar
con committed
38
39
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
40
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
41
#include <coreplugin/fileiconprovider.h>
42
#include <coreplugin/icontext.h>
43
#include <utils/appmainwindow.h>
44
#include <utils/fancylineedit.h>
45
#include <utils/hostosinfo.h>
Eike Ziller's avatar
Eike Ziller committed
46
#include <utils/progressindicator.h>
hjk's avatar
hjk committed
47
#include <utils/qtcassert.h>
48
#include <utils/runextensions.h>
49
#include <utils/stylehelper.h>
con's avatar
con committed
50

Eike Ziller's avatar
Eike Ziller committed
51
#include <QColor>
52
53
54
55
56
57
58
59
60
61
62
63
#include <QFileInfo>
#include <QTimer>
#include <QEvent>
#include <QAction>
#include <QApplication>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>
#include <QTreeView>
#include <QToolTip>
con's avatar
con committed
64

65
66
Q_DECLARE_METATYPE(Core::ILocatorFilter*)
Q_DECLARE_METATYPE(Core::LocatorFilterEntry)
con's avatar
con committed
67

68
namespace Core {
con's avatar
con committed
69
70
namespace Internal {

con's avatar
con committed
71
/* A model to represent the Locator results. */
con's avatar
con committed
72
class LocatorModel : public QAbstractListModel
con's avatar
con committed
73
74
{
public:
con's avatar
con committed
75
    LocatorModel(QObject *parent = 0)
con's avatar
con committed
76
77
78
        : QAbstractListModel(parent)
    {}

79
    void clear();
con's avatar
con committed
80
81
82
83
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;

84
    void addEntries(const QList<LocatorFilterEntry> &entries);
con's avatar
con committed
85
86

private:
87
    mutable QList<LocatorFilterEntry> mEntries;
con's avatar
con committed
88
89
90
91
92
93
94
95
96
97
};

class CompletionList : public QTreeView
{
public:
    CompletionList(QWidget *parent = 0);

    void updatePreferredSize();
    QSize preferredSize() const { return m_preferredSize; }

Andre Hartmann's avatar
Andre Hartmann committed
98
    void focusOutEvent (QFocusEvent *event) {
99
100
101
        if (event->reason() == Qt::ActiveWindowFocusReason)
            hide();
        QTreeView::focusOutEvent(event);
Tobias Hunger's avatar
Tobias Hunger committed
102
103
    }

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    void next() {
        int index = currentIndex().row();
        ++index;
        if (index >= model()->rowCount(QModelIndex())) {
            // wrap
            index = 0;
        }
        setCurrentIndex(model()->index(index, 0));
    }

    void previous() {
        int index = currentIndex().row();
        --index;
        if (index < 0) {
            // wrap
            index = model()->rowCount(QModelIndex()) - 1;
        }
        setCurrentIndex(model()->index(index, 0));
    }

con's avatar
con committed
124
125
126
127
128
129
private:
    QSize m_preferredSize;
};

} // namespace Internal

130

131
using namespace Core::Internal;
con's avatar
con committed
132

con's avatar
con committed
133
// =========== LocatorModel ===========
con's avatar
con committed
134

135
void LocatorModel::clear()
con's avatar
con committed
136
{
137
138
139
140
141
142
143
144
145
    beginResetModel();
    mEntries.clear();
    endResetModel();
}

int LocatorModel::rowCount(const QModelIndex & parent) const
{
    if (parent.isValid())
        return 0;
con's avatar
con committed
146
147
148
    return mEntries.size();
}

con's avatar
con committed
149
int LocatorModel::columnCount(const QModelIndex &parent) const
con's avatar
con committed
150
151
152
153
{
    return parent.isValid() ? 0 : 2;
}

con's avatar
con committed
154
QVariant LocatorModel::data(const QModelIndex &index, int role) const
con's avatar
con committed
155
156
157
158
{
    if (!index.isValid() || index.row() >= mEntries.size())
        return QVariant();

159
    if (role == Qt::DisplayRole) {
160
        if (index.column() == 0)
con's avatar
con committed
161
            return mEntries.at(index.row()).displayName;
162
        else if (index.column() == 1)
con's avatar
con committed
163
            return mEntries.at(index.row()).extraInfo;
164
165
166
167
    } else if (role == Qt::ToolTipRole) {
        if (mEntries.at(index.row()).extraInfo.isEmpty())
            return QVariant(mEntries.at(index.row()).displayName);
        else
168
169
            return QVariant(mEntries.at(index.row()).displayName
                            + QLatin1String("\n\n") + mEntries.at(index.row()).extraInfo);
con's avatar
con committed
170
    } else if (role == Qt::DecorationRole && index.column() == 0) {
171
        LocatorFilterEntry &entry = mEntries[index.row()];
172
173
        if (!entry.fileIconResolved && !entry.fileName.isEmpty() && entry.displayIcon.isNull()) {
            entry.fileIconResolved = true;
174
            entry.displayIcon = FileIconProvider::icon(entry.fileName);
con's avatar
con committed
175
176
177
        }
        return entry.displayIcon;
    } else if (role == Qt::ForegroundRole && index.column() == 1) {
Eike Ziller's avatar
Eike Ziller committed
178
        return QColor(Qt::darkGray);
con's avatar
con committed
179
180
181
182
183
184
185
    } else if (role == Qt::UserRole) {
        return qVariantFromValue(mEntries.at(index.row()));
    }

    return QVariant();
}

186
void LocatorModel::addEntries(const QList<LocatorFilterEntry> &entries)
con's avatar
con committed
187
{
188
189
190
    beginInsertRows(QModelIndex(), mEntries.size(), mEntries.size() + entries.size() - 1);
    mEntries.append(entries);
    endInsertRows();
con's avatar
con committed
191
192
193
194
195
196
197
198
199
200
201
202
203
}

// =========== CompletionList ===========

CompletionList::CompletionList(QWidget *parent)
    : QTreeView(parent)
{
    setRootIsDecorated(false);
    setUniformRowHeights(true);
    setMaximumWidth(900);
    header()->hide();
    header()->setStretchLastSection(true);
    // This is too slow when done on all results
204
    //header()->setSectionResizeMode(QHeaderView::ResizeToContents);
con's avatar
con committed
205
    setWindowFlags(Qt::ToolTip);
206
207
208
209
210
211
    if (Utils::HostOsInfo::isMacHost()) {
        if (horizontalScrollBar())
            horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
        if (verticalScrollBar())
            verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
    }
con's avatar
con committed
212
213
214
215
216
217
218
}

void CompletionList::updatePreferredSize()
{
    const QStyleOptionViewItem &option = viewOptions();
    const QSize shint = itemDelegate()->sizeHint(option, model()->index(0, 0));

Eike Ziller's avatar
Eike Ziller committed
219
    m_preferredSize = QSize(730, shint.height() * 17 + frameWidth() * 2);
con's avatar
con committed
220
221
}

222
// =========== LocatorWidget ===========
con's avatar
con committed
223

hjk's avatar
hjk committed
224
LocatorWidget::LocatorWidget(Locator *qop) :
225
226
227
228
229
    m_locatorPlugin(qop),
    m_locatorModel(new LocatorModel(this)),
    m_completionList(new CompletionList(this)),
    m_filterMenu(new QMenu(this)),
    m_refreshAction(new QAction(tr("Refresh"), this)),
Orgad Shaneh's avatar
Orgad Shaneh committed
230
    m_configureAction(new QAction(ICore::msgShowOptionsDialog(), this)),
231
    m_fileLineEdit(new Utils::FancyLineEdit),
232
    m_needsClearResult(true),
233
    m_updateRequested(false),
234
235
    m_acceptRequested(false),
    m_possibleToolTipRequest(false)
con's avatar
con committed
236
{
237
    // Explicitly hide the completion list popup.
con's avatar
con committed
238
239
    m_completionList->hide();

240
    setFocusProxy(m_fileLineEdit);
241
    setWindowTitle(tr("Locate..."));
con's avatar
con committed
242
    resize(200, 90);
Eike Ziller's avatar
Eike Ziller committed
243
    QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
con's avatar
con committed
244
245
246
247
248
249
250
251
252
253
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    setSizePolicy(sizePolicy);
    setMinimumSize(QSize(200, 0));

    QHBoxLayout *layout = new QHBoxLayout(this);
    setLayout(layout);
    layout->setMargin(0);
    layout->addWidget(m_fileLineEdit);

254
    setWindowIcon(QIcon(QLatin1String(":/locator/images/locator.png")));
255
    const QPixmap pixmap = Icons::MAGNIFIER.pixmap();
256
    m_fileLineEdit->setFiltering(true);
257
    m_fileLineEdit->setButtonPixmap(Utils::FancyLineEdit::Left, pixmap);
258
    m_fileLineEdit->setButtonToolTip(Utils::FancyLineEdit::Left, tr("Options"));
con's avatar
con committed
259
    m_fileLineEdit->setFocusPolicy(Qt::ClickFocus);
260
    m_fileLineEdit->setButtonVisible(Utils::FancyLineEdit::Left, true);
261
    // We set click focus since otherwise you will always get two popups
262
    m_fileLineEdit->setButtonFocusPolicy(Utils::FancyLineEdit::Left, Qt::ClickFocus);
263
    m_fileLineEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
con's avatar
con committed
264
265
266
267

    m_fileLineEdit->installEventFilter(this);
    this->installEventFilter(this);

con's avatar
con committed
268
    m_completionList->setModel(m_locatorModel);
con's avatar
con committed
269
270
271
272
273
274
275
    m_completionList->header()->resizeSection(0, 300);
    m_completionList->updatePreferredSize();
    m_completionList->resize(m_completionList->preferredSize());

    m_filterMenu->addAction(m_refreshAction);
    m_filterMenu->addAction(m_configureAction);

276
    m_fileLineEdit->setButtonMenu(Utils::FancyLineEdit::Left, m_filterMenu);
con's avatar
con committed
277

con's avatar
con committed
278
    connect(m_refreshAction, SIGNAL(triggered()), m_locatorPlugin, SLOT(refresh()));
con's avatar
con committed
279
    connect(m_configureAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
Robert Loehning's avatar
Robert Loehning committed
280
    connect(m_fileLineEdit, SIGNAL(textChanged(QString)),
281
        this, SLOT(showPopup()));
con's avatar
con committed
282
    connect(m_completionList, SIGNAL(activated(QModelIndex)),
283
            this, SLOT(scheduleAcceptCurrentEntry()));
284

285
    m_entriesWatcher = new QFutureWatcher<LocatorFilterEntry>(this);
286
287
288
289
    connect(m_entriesWatcher, &QFutureWatcher<LocatorFilterEntry>::resultsReadyAt,
            this, &LocatorWidget::addSearchResults);
    connect(m_entriesWatcher, &QFutureWatcher<LocatorFilterEntry>::finished,
            this, &LocatorWidget::handleSearchFinished);
290

291
292
293
    m_showPopupTimer.setInterval(100);
    m_showPopupTimer.setSingleShot(true);
    connect(&m_showPopupTimer, SIGNAL(timeout()), SLOT(showPopupNow()));
Eike Ziller's avatar
Eike Ziller committed
294
295
296
297
298
299
300
301

    m_progressIndicator = new Utils::ProgressIndicator(Utils::ProgressIndicator::Small,
                                                       m_fileLineEdit);
    m_progressIndicator->raise();
    m_progressIndicator->hide();
    m_showProgressTimer.setSingleShot(true);
    m_showProgressTimer.setInterval(50); // don't show progress for < 50ms tasks
    connect(&m_showProgressTimer, &QTimer::timeout, [this]() { setProgressIndicatorVisible(true);});
con's avatar
con committed
302
303
}

Eike Ziller's avatar
Eike Ziller committed
304
305
306
307
308
void LocatorWidget::setPlaceholderText(const QString &text)
{
    m_fileLineEdit->setPlaceholderText(text);
}

309
void LocatorWidget::updateFilterList()
con's avatar
con committed
310
{
311
312
    typedef QMap<Id, QAction *> IdActionMap;

con's avatar
con committed
313
    m_filterMenu->clear();
314
315

    // update actions and menu
316
    IdActionMap actionCopy = m_filterActionMap;
317
318
    m_filterActionMap.clear();
    // register new actions, update existent
con's avatar
con committed
319
    foreach (ILocatorFilter *filter, m_locatorPlugin->filters()) {
320
321
        if (filter->shortcutString().isEmpty() || filter->isHidden())
            continue;
hjk's avatar
hjk committed
322
323
        Id filterId = filter->id();
        Id locatorId = filterId.withPrefix("Locator.");
324
        QAction *action = 0;
hjk's avatar
hjk committed
325
326
        Command *cmd = 0;
        if (!actionCopy.contains(filterId)) {
327
328
            // register new action
            action = new QAction(filter->displayName(), this);
329
            cmd = ActionManager::registerAction(action, locatorId);
hjk's avatar
hjk committed
330
            cmd->setAttribute(Command::CA_UpdateText);
331
            connect(action, SIGNAL(triggered()), this, SLOT(filterSelected()));
con's avatar
con committed
332
            action->setData(qVariantFromValue(filter));
333
        } else {
hjk's avatar
hjk committed
334
            action = actionCopy.take(filterId);
335
            action->setText(filter->displayName());
hjk's avatar
hjk committed
336
            cmd = ActionManager::command(locatorId);
con's avatar
con committed
337
        }
hjk's avatar
hjk committed
338
        m_filterActionMap.insert(filterId, action);
339
340
341
342
        m_filterMenu->addAction(cmd->action());
    }

    // unregister actions that are deleted now
343
344
345
346
347
    const IdActionMap::Iterator end = actionCopy.end();
    for (IdActionMap::Iterator it = actionCopy.begin(); it != end; ++it) {
        ActionManager::unregisterAction(it.value(), it.key().withPrefix("Locator."));
        delete it.value();
    }
348

con's avatar
con committed
349
350
351
352
353
    m_filterMenu->addSeparator();
    m_filterMenu->addAction(m_refreshAction);
    m_filterMenu->addAction(m_configureAction);
}

354
bool LocatorWidget::eventFilter(QObject *obj, QEvent *event)
con's avatar
con committed
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
    if (obj == m_fileLineEdit && event->type() == QEvent::KeyPress) {
        if (m_possibleToolTipRequest)
            m_possibleToolTipRequest = false;
        if (QToolTip::isVisible())
            QToolTip::hideText();

        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        switch (keyEvent->key()) {
        case Qt::Key_Up:
        case Qt::Key_Down:
        case Qt::Key_PageUp:
        case Qt::Key_PageDown:
            showCompletionList();
            QApplication::sendEvent(m_completionList, event);
            return true;
        case Qt::Key_Enter:
        case Qt::Key_Return:
            scheduleAcceptCurrentEntry();
            return true;
        case Qt::Key_Escape:
            m_completionList->hide();
            return true;
        case Qt::Key_Tab:
            m_completionList->next();
            return true;
        case Qt::Key_Backtab:
            m_completionList->previous();
            return true;
        case Qt::Key_Alt:
            if (keyEvent->modifiers() == Qt::AltModifier) {
                m_possibleToolTipRequest = true;
                return true;
            }
            break;
        default:
            break;
        }
    } else if (obj == m_fileLineEdit && event->type() == QEvent::KeyRelease) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (m_possibleToolTipRequest) {
            m_possibleToolTipRequest = false;
            if (m_completionList->isVisible()
                    && (keyEvent->key() == Qt::Key_Alt)
                    && (keyEvent->modifiers() == Qt::NoModifier)) {
                const QModelIndex index = m_completionList->currentIndex();
                if (index.isValid()) {
                    QToolTip::showText(m_completionList->pos() + m_completionList->visualRect(index).topRight(),
                                       m_locatorModel->data(index, Qt::ToolTipRole).toString());
                    return true;
                }
            }
        }
    } else if (obj == m_fileLineEdit && event->type() == QEvent::FocusOut) {
Andre Hartmann's avatar
Andre Hartmann committed
409
        QFocusEvent *fev = static_cast<QFocusEvent *>(event);
410
        if (fev->reason() != Qt::ActiveWindowFocusReason || !m_completionList->isActiveWindow())
Tobias Hunger's avatar
Tobias Hunger committed
411
            m_completionList->hide();
con's avatar
con committed
412
    } else if (obj == m_fileLineEdit && event->type() == QEvent::FocusIn) {
413
414
415
        QFocusEvent *fev = static_cast<QFocusEvent *>(event);
        if (fev->reason() != Qt::ActiveWindowFocusReason)
            showPopupNow();
con's avatar
con committed
416
417
    } else if (obj == this && event->type() == QEvent::ShortcutOverride) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
418
419
420
421
        switch (ke->key()) {
        case Qt::Key_Escape:
            if (!ke->modifiers()) {
                event->accept();
422
                QTimer::singleShot(0, this, SLOT(setFocusToCurrentMode()));
423
424
425
426
427
428
429
430
431
432
                return true;
            }
        case Qt::Key_Alt:
            if (ke->modifiers() == Qt::AltModifier) {
                event->accept();
                return true;
            }
            break;
        default:
            break;
con's avatar
con committed
433
434
435
436
437
        }
    }
    return QWidget::eventFilter(obj, event);
}

438
439
void LocatorWidget::setFocusToCurrentMode()
{
Orgad Shaneh's avatar
Orgad Shaneh committed
440
    ModeManager::setFocusToCurrentMode();
441
442
}

443
void LocatorWidget::showCompletionList()
con's avatar
con committed
444
445
446
447
448
449
450
451
{
    const int border = m_completionList->frameWidth();
    const QSize size = m_completionList->preferredSize();
    const QRect rect(mapToGlobal(QPoint(-border, -size.height() - border)), size);
    m_completionList->setGeometry(rect);
    m_completionList->show();
}

452
void LocatorWidget::showPopup()
con's avatar
con committed
453
{
454
    m_updateRequested = true;
455
    m_showPopupTimer.start();
456
457
458
459
}

void LocatorWidget::showPopupNow()
{
460
    m_showPopupTimer.stop();
461
    updateCompletionList(m_fileLineEdit->text());
con's avatar
con committed
462
463
464
    showCompletionList();
}

Andre Hartmann's avatar
Andre Hartmann committed
465
QList<ILocatorFilter *> LocatorWidget::filtersFor(const QString &text, QString &searchText)
con's avatar
con committed
466
{
467
    const QString trimmedText = text.trimmed();
Andre Hartmann's avatar
Andre Hartmann committed
468
    QList<ILocatorFilter *> filters = m_locatorPlugin->filters();
469
    const int whiteSpace = trimmedText.indexOf(QLatin1Char(' '));
con's avatar
con committed
470
471
    QString prefix;
    if (whiteSpace >= 0)
472
        prefix = trimmedText.left(whiteSpace);
con's avatar
con committed
473
474
    if (!prefix.isEmpty()) {
        prefix = prefix.toLower();
475
        QList<ILocatorFilter *> prefixFilters;
476
        foreach (ILocatorFilter *filter, filters) {
con's avatar
con committed
477
            if (prefix == filter->shortcutString()) {
478
                searchText = trimmedText.mid(whiteSpace).trimmed();
479
                prefixFilters << filter;
con's avatar
con committed
480
481
            }
        }
482
483
        if (!prefixFilters.isEmpty())
            return prefixFilters;
con's avatar
con committed
484
    }
485
    searchText = trimmedText;
Andre Hartmann's avatar
Andre Hartmann committed
486
    QList<ILocatorFilter *> activeFilters;
487
    foreach (ILocatorFilter *filter, filters)
488
        if (filter->isIncludedByDefault())
con's avatar
con committed
489
490
491
492
            activeFilters << filter;
    return activeFilters;
}

Eike Ziller's avatar
Eike Ziller committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
void LocatorWidget::setProgressIndicatorVisible(bool visible)
{
    if (!visible) {
        m_progressIndicator->hide();
        return;
    }
    const QSize iconSize = m_progressIndicator->sizeHint();
    m_progressIndicator->setGeometry(m_fileLineEdit->button(Utils::FancyLineEdit::Right)->geometry().x()
                                     - iconSize.width(),
                                     (m_fileLineEdit->height() - iconSize.height()) / 2 /*center*/,
                                     iconSize.width(),
                                     iconSize.height());
    m_progressIndicator->show();
}

508
509
void LocatorWidget::updateCompletionList(const QString &text)
{
510
    m_updateRequested = true;
511
512
513
514
515
516
517
518
519
520
    if (m_entriesWatcher->future().isRunning()) {
        // Cancel the old future. We may not just block the UI thread to wait for the search to
        // actually cancel, so try again when the finshed signal of the watcher ends up in
        // updateEntries() (which will call updateCompletionList again with the
        // requestedCompletionText)
        m_requestedCompletionText = text;
        m_entriesWatcher->future().cancel();
        return;
    }

Eike Ziller's avatar
Eike Ziller committed
521
    m_showProgressTimer.start();
522
    m_needsClearResult = true;
523
    QString searchText;
Andre Hartmann's avatar
Andre Hartmann committed
524
    const QList<ILocatorFilter *> filters = filtersFor(text, searchText);
525
526
527

    foreach (ILocatorFilter *filter, filters)
        filter->prepareSearch(searchText);
528
    QFuture<LocatorFilterEntry> future = QtConcurrent::run(runSearch, filters, searchText);
529
530
531
    m_entriesWatcher->setFuture(future);
}

532
void LocatorWidget::handleSearchFinished()
533
{
Eike Ziller's avatar
Eike Ziller committed
534
535
    m_showProgressTimer.stop();
    setProgressIndicatorVisible(false);
536
    m_updateRequested = false;
537
538
539
540
    if (m_acceptRequested) {
        acceptCurrentEntry();
        return;
    }
541
    if (m_entriesWatcher->future().isCanceled()) {
542
543
544
        const QString text = m_requestedCompletionText;
        m_requestedCompletionText.clear();
        updateCompletionList(text);
545
        return;
546
    }
547

548
549
550
551
    if (m_needsClearResult) {
        m_locatorModel->clear();
        m_needsClearResult = false;
    }
552
553
554
555
556
557
558
559
}

void LocatorWidget::scheduleAcceptCurrentEntry()
{
    if (m_updateRequested) {
        // don't just accept the selected entry, since the list is not up to date
        // accept will be called after the update finished
        m_acceptRequested = true;
560
561
        // do not wait for the rest of the search to finish
        m_entriesWatcher->future().cancel();
562
563
564
    } else {
        acceptCurrentEntry();
    }
con's avatar
con committed
565
566
}

567
void LocatorWidget::acceptCurrentEntry()
con's avatar
con committed
568
{
569
    m_acceptRequested = false;
con's avatar
con committed
570
571
572
573
574
    if (!m_completionList->isVisible())
        return;
    const QModelIndex index = m_completionList->currentIndex();
    if (!index.isValid())
        return;
575
    const LocatorFilterEntry entry = m_locatorModel->data(index, Qt::UserRole).value<LocatorFilterEntry>();
con's avatar
con committed
576
    m_completionList->hide();
577
    m_fileLineEdit->clearFocus();
con's avatar
con committed
578
579
580
    entry.filter->accept(entry);
}

581
void LocatorWidget::show(const QString &text, int selectionStart, int selectionLength)
con's avatar
con committed
582
{
583
584
    if (!text.isEmpty())
        m_fileLineEdit->setText(text);
585
586
    m_fileLineEdit->setFocus();
    showPopupNow();
587
    ICore::raiseWindow(ICore::mainWindow());
588

con's avatar
con committed
589
    if (selectionStart >= 0) {
con's avatar
con committed
590
        m_fileLineEdit->setSelection(selectionStart, selectionLength);
con's avatar
con committed
591
592
593
        if (selectionLength == 0) // make sure the cursor is at the right position (Mac-vs.-rest difference)
            m_fileLineEdit->setCursorPosition(selectionStart);
    } else {
594
        m_fileLineEdit->selectAll();
con's avatar
con committed
595
    }
con's avatar
con committed
596
597
}

598
void LocatorWidget::filterSelected()
con's avatar
con committed
599
{
600
    QString searchText = tr("<type here>");
Andre Hartmann's avatar
Andre Hartmann committed
601
    QAction *action = qobject_cast<QAction *>(sender());
hjk's avatar
hjk committed
602
    QTC_ASSERT(action, return);
Andre Hartmann's avatar
Andre Hartmann committed
603
    ILocatorFilter *filter = action->data().value<ILocatorFilter *>();
hjk's avatar
hjk committed
604
    QTC_ASSERT(filter, return);
605
606
607
608
    QString currentText = m_fileLineEdit->text().trimmed();
    // add shortcut string at front or replace existing shortcut string
    if (!currentText.isEmpty()) {
        searchText = currentText;
con's avatar
con committed
609
        foreach (ILocatorFilter *otherfilter, m_locatorPlugin->filters()) {
610
            if (currentText.startsWith(otherfilter->shortcutString() + QLatin1Char(' '))) {
Andre Hartmann's avatar
Andre Hartmann committed
611
                searchText = currentText.mid(otherfilter->shortcutString().length() + 1);
612
613
614
615
                break;
            }
        }
    }
616
    show(filter->shortcutString() + QLatin1Char(' ') + searchText,
con's avatar
con committed
617
         filter->shortcutString().length() + 1,
618
         searchText.length());
con's avatar
con committed
619
620
621
622
    updateCompletionList(m_fileLineEdit->text());
    m_fileLineEdit->setFocus();
}

623
void LocatorWidget::showConfigureDialog()
con's avatar
con committed
624
{
625
    ICore::showOptionsDialog(Constants::FILTER_OPTIONS_PAGE);
con's avatar
con committed
626
}
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
void LocatorWidget::addSearchResults(int firstIndex, int endIndex)
{
    if (m_needsClearResult) {
        m_locatorModel->clear();
        m_needsClearResult = false;
    }
    const bool selectFirst = m_locatorModel->rowCount() == 0;
    QList<LocatorFilterEntry> entries;
    for (int i = firstIndex; i < endIndex; ++i)
        entries.append(m_entriesWatcher->resultAt(i));
    m_locatorModel->addEntries(entries);
    if (selectFirst)
        m_completionList->setCurrentIndex(m_locatorModel->index(0, 0));
}

643
} // namespace Core