File: grepdialog.cpp

package info (click to toggle)
kdevelop 4%3A25.04.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 73,508 kB
  • sloc: cpp: 291,803; python: 4,322; javascript: 3,518; sh: 1,316; ansic: 703; xml: 414; php: 95; lisp: 66; makefile: 31; sed: 12
file content (687 lines) | stat: -rw-r--r-- 23,942 bytes parent folder | download | duplicates (2)
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
/*
    SPDX-FileCopyrightText: 1999-2001 Bernd Gehrmann <bernd@kdevelop.org>
    SPDX-FileCopyrightText: 1999-2001 the KDevelop Team
    SPDX-FileCopyrightText: 2007 Dukju Ahn <dukjuahn@gmail.com>
    SPDX-FileCopyrightText: 2010 Julien Desgats <julien.desgats@gmail.com>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "grepdialog.h"

#include <algorithm>

#include <QCloseEvent>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileDialog>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QShowEvent>
#include <QStringList>
#include <QTimer>

#include <KComboBox>
#include <KCompletion>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KUrlCompletion>

#include <interfaces/icore.h>
#include <interfaces/idocument.h>
#include <interfaces/idocumentcontroller.h>
#include <interfaces/iruncontroller.h>
#include <interfaces/iproject.h>
#include <interfaces/iprojectcontroller.h>
#include <interfaces/isession.h>

#include <util/algorithm.h>
#include <util/path.h>
#include <util/wildcardhelpers.h>

#include "debug.h"
#include "grepviewplugin.h"
#include "grepoutputview.h"
#include "grepfindthread.h"
#include "greputil.h"

#include <utility>

using namespace KDevelop;

namespace {

inline QString allOpenFilesString() { return i18nc("@item:inlistbox", "All Open Files"); }
inline QString allOpenProjectsString() { return i18nc("@item:inlistbox", "All Open Projects"); }

inline QStringList template_desc()
{
    return QStringList{
        QStringLiteral("verbatim"),
        QStringLiteral("word"),
        QStringLiteral("assignment"),
        QStringLiteral("->MEMBER("),
        QStringLiteral("class::MEMBER("),
        QStringLiteral("OBJECT->member("),
    };
}

inline QStringList template_str()
{
    return QStringList{
        QStringLiteral("%s"),
        QStringLiteral("\\b%s\\b"),
        QStringLiteral("\\b%s\\b\\s*=[^=]"),
        QStringLiteral("\\->\\s*\\b%s\\b\\s*\\("),
        QStringLiteral("([a-z0-9_$]+)\\s*::\\s*\\b%s\\b\\s*\\("),
        QStringLiteral("\\b%s\\b\\s*\\->\\s*([a-z0-9_$]+)\\s*\\("),
    };
}

inline QStringList repl_template()
{
    return QStringList{
        QStringLiteral("%s"),
        QStringLiteral("%s"),
        QStringLiteral("%s = "),
        QStringLiteral("->%s("),
        QStringLiteral("\\1::%s("),
        QStringLiteral("%s->\\1("),
    };
}

inline QStringList filepatterns()
{
    return QStringList{
        QStringLiteral("*.h,*.hxx,*.hpp,*.hh,*.h++,*.H,*.tlh,*.cuh,*.cpp,*.cc,*.C,*.c++,*.cxx,*.ocl,*.inl,*.idl,*.c,*.cu,*.m,*.mm,*.M,*.y,*.ypp,*.yxx,*.y++,*.l,*.txt,*.xml,*.rc"),
        QStringLiteral("*.cpp,*.cc,*.C,*.c++,*.cxx,*.ocl,*.inl,*.c,*.cu,*.m,*.mm,*.M"),
        QStringLiteral("*.h,*.hxx,*.hpp,*.hh,*.h++,*.H,*.tlh,*.cuh,*.idl"),
        QStringLiteral("*.adb"),
        QStringLiteral("*.cs"),
        QStringLiteral("*.f"),
        QStringLiteral("*.html,*.htm"),
        QStringLiteral("*.hs"),
        QStringLiteral("*.java"),
        QStringLiteral("*.js"),
        QStringLiteral("*.php,*.php3,*.php4"),
        QStringLiteral("*.pl"),
        QStringLiteral("*.pp,*.pas"),
        QStringLiteral("*.py"),
        QStringLiteral("*.js,*.css,*.yml,*.rb,*.rhtml,*.html.erb,*.rjs,*.js.rjs,*.rxml,*.xml.builder"),
        QStringLiteral("CMakeLists.txt,*.cmake"),
        QStringLiteral("*"),
    };
}

inline QStringList excludepatterns()
{
    return QStringList{
        QStringLiteral("/CVS/,/SCCS/,/.svn/,/_darcs/,/build/,/.git/"),
        QString(),
    };
}

KConfigGroup dialogConfigGroup()
{
    return ICore::self()->activeSession()->config()->group(QStringLiteral("GrepDialog"));
}

class DialogConfigReader
{
public:
    DialogConfigReader()
        : m_config{dialogConfigGroup()}
    {
    }

    QStringList patternList() const
    {
        return m_config.readEntry("LastSearchItems", QStringList{});
    }
    int templateIndex() const
    {
        return m_config.readEntry("LastUsedTemplateIndex", 0);
    }
    QStringList templateStringList() const
    {
        return m_config.readEntry("LastUsedTemplateString", template_str());
    }
    QStringList replacementTemplateStringList() const
    {
        return m_config.readEntry("LastUsedReplacementTemplateString", repl_template());
    }
    bool isRegex() const
    {
        return m_config.readEntry("regexp", false);
    }
    bool isCaseSensitive() const
    {
        return m_config.readEntry("case_sens", true);
    }
    QStringList searchPathsList(const GrepViewPlugin& plugin) const
    {
        const bool isAnyProjectOpen = plugin.core()->projectController()->projectCount() != 0;
        return m_config.readEntry("SearchPaths",
                                  QStringList{isAnyProjectOpen ? allOpenProjectsString() : QDir::homePath()});
    }
    int depth() const
    {
        return m_config.readEntry("depth", -1);
    }
    bool limitToProjectFiles() const
    {
        return m_config.readEntry("search_project_files", true);
    }
    QStringList filePatternsList() const
    {
        return m_config.readEntry("file_patterns", filepatterns());
    }
    QStringList excludePatternsList() const
    {
        return m_config.readEntry("exclude_patterns", excludepatterns());
    }

private:
    KConfigGroup m_config;
};

QString searchTemplateFromTemplateString(const QString& templateString)
{
    return templateString.isEmpty() ? QStringLiteral("%s") : templateString;
}

///Separator used to separate search paths.
inline QString pathsSeparator() { return (QStringLiteral(";")); }

///Returns the chosen directories or files (only the top directories, not subfiles)
QList<QUrl> getDirectoryChoice(const QString& text)
{
    QList<QUrl> ret;
    if (text == allOpenFilesString()) {
        const auto openDocuments = ICore::self()->documentController()->openDocuments();
        ret.reserve(openDocuments.size());
        for (auto* doc : openDocuments) {
            ret << doc->url();
        }
    } else if (text == allOpenProjectsString()) {
        const auto projects = ICore::self()->projectController()->projects();
        ret.reserve(projects.size());
        for (auto* project : projects) {
            ret << project->path().toUrl();
        }
    } else {
        const QStringList semicolonSeparatedFileList = text.split(pathsSeparator(), Qt::SkipEmptyParts);
        if (!semicolonSeparatedFileList.isEmpty() && QFileInfo::exists(semicolonSeparatedFileList[0])) {
            // We use QFileInfo to make sure this is really a semicolon-separated file list, not a file containing
            // a semicolon in the name.
            ret.reserve(semicolonSeparatedFileList.size());
            for (const QString& file : semicolonSeparatedFileList) {
                ret << QUrl::fromLocalFile(file).adjusted(QUrl::StripTrailingSlash | QUrl::NormalizePathSegments);
            }
        } else {
            auto url = QUrl::fromUserInput(text).adjusted(QUrl::StripTrailingSlash | QUrl::NormalizePathSegments);
            if (!url.isEmpty()) {
                ret.push_back(std::move(url));
            }
        }
    }
    return ret;
}

///Check if all directories are part of a project
bool directoriesInProject(const QString& dir)
{
    const auto urls = getDirectoryChoice(dir);
    return std::all_of(urls.begin(), urls.end(), [&](const QUrl& url) {
        IProject *proj = ICore::self()->projectController()->findProjectForUrl(url);
        return (proj && proj->path().toUrl().isLocalFile());
    });
}

///Max number of items in paths combo box.
const int pathsMaxCount = 25;
}

GrepDialog::GrepDialog(GrepViewPlugin* plugin, GrepOutputView* toolView, QWidget* parent, bool show)
    : QDialog(parent)
    , Ui::GrepWidget()
    , m_plugin(plugin)
    , m_toolView(toolView)
    , m_show(show)
{
    setAttribute(Qt::WA_DeleteOnClose);

    // if we don't intend on showing the dialog, we can skip all UI setup
    if (!m_show) {
        return;
    }

    setWindowTitle(i18nc("@title:window", "Find/Replace in Files"));

    setupUi(this);
    patternCombo->lineEdit()->setClearButtonEnabled(true);
    adjustSize();

    auto searchButton = buttonBox->button(QDialogButtonBox::Ok);
    Q_ASSERT(searchButton);
    searchButton->setText(i18nc("@action:button", "Search..."));
    searchButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-find")));
    connect(searchButton, &QPushButton::clicked, this, &GrepDialog::startSearch);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &GrepDialog::reject);

    const DialogConfigReader configReader;

    patternCombo->addItems(configReader.patternList());
    patternCombo->setInsertPolicy(QComboBox::InsertAtTop);
    patternCombo->setCompleter(nullptr);

    templateTypeCombo->addItems(template_desc());
    templateTypeCombo->setCurrentIndex(configReader.templateIndex());
    templateEdit->addItems(configReader.templateStringList());
    templateEdit->setEditable(true);
    templateEdit->setCompletionMode(KCompletion::CompletionPopup);
    KCompletion* comp = templateEdit->completionObject();
    connect(templateEdit, QOverload<const QString&>::of(&KComboBox::returnPressed),
            comp, QOverload<const QString&>::of(&KCompletion::addItem));
    for(int i=0; i<templateEdit->count(); i++)
        comp->addItem(templateEdit->itemText(i));
    replacementTemplateEdit->addItems(configReader.replacementTemplateStringList());
    replacementTemplateEdit->setEditable(true);
    replacementTemplateEdit->setCompletionMode(KCompletion::CompletionPopup);
    comp = replacementTemplateEdit->completionObject();
    connect(replacementTemplateEdit, QOverload<const QString&>::of(&KComboBox::returnPressed),
            comp, QOverload<const QString&>::of(&KCompletion::addItem));
    for(int i=0; i<replacementTemplateEdit->count(); i++)
        comp->addItem(replacementTemplateEdit->itemText(i));

    regexCheck->setChecked(configReader.isRegex());

    caseSensitiveCheck->setChecked(configReader.isCaseSensitive());

    searchPaths->setCompletionObject(new KUrlCompletion());
    searchPaths->setAutoDeleteCompletionObject(true);
    searchPaths->addItems(configReader.searchPathsList(*m_plugin));
    searchPaths->setInsertPolicy(QComboBox::InsertAtTop);

    syncButton->setIcon(QIcon::fromTheme(QStringLiteral("dirsync")));
    syncButton->setMenu(createSyncButtonMenu());

    depthSpin->setValue(configReader.depth());
    limitToProjectCheck->setChecked(configReader.limitToProjectFiles());

    filesCombo->addItems(configReader.filePatternsList());
    excludeCombo->addItems(configReader.excludePatternsList());

    connect(templateTypeCombo, QOverload<int>::of(&KComboBox::activated),
            this, &GrepDialog::templateTypeComboActivated);
    connect(patternCombo, &QComboBox::editTextChanged,
            this, &GrepDialog::patternComboEditTextChanged);
    patternComboEditTextChanged( patternCombo->currentText() );
    patternCombo->setFocus();

    connect(searchPaths, &KComboBox::textActivated, this, &GrepDialog::setSearchLocations);

    directorySelector->setIcon(QIcon::fromTheme(QStringLiteral("document-open")));
    connect(directorySelector, &QPushButton::clicked, this, &GrepDialog::selectDirectoryDialog );

    Q_ASSERT(searchPaths->lineEdit());
    connect(searchPaths->lineEdit(), &QLineEdit::editingFinished, this, &GrepDialog::updateLimitToProjectEnabled);
    updateLimitToProjectEnabled();
}

void GrepDialog::selectDirectoryDialog()
{
    const QString dirName = QFileDialog::getExistingDirectory(
        this, i18nc("@title:window", "Select Directory to Search in"),
        searchPaths->lineEdit()->text());
    if (!dirName.isEmpty()) {
        setSearchLocations(dirName);
    }
}

void GrepDialog::addUrlToMenu(QMenu* menu, const QUrl& url)
{
    QAction* action = menu->addAction(m_plugin->core()->projectController()->prettyFileName(url, KDevelop::IProjectController::FormatPlain));
    action->setData(QVariant(url.toString(QUrl::PreferLocalFile)));
    connect(action, &QAction::triggered, this, &GrepDialog::synchronizeDirActionTriggered);
}

void GrepDialog::addStringToMenu(QMenu* menu, const QString& string)
{
    QAction* action = menu->addAction(string);
    action->setData(QVariant(string));
    connect(action, &QAction::triggered, this, &GrepDialog::synchronizeDirActionTriggered);
}

void GrepDialog::synchronizeDirActionTriggered(bool)
{
    auto* action = qobject_cast<QAction*>(sender());
    Q_ASSERT(action);
    setSearchLocations(action->data().toString());
}

QMenu* GrepDialog::createSyncButtonMenu()
{
    auto* ret = new QMenu(this);

    QSet<Path> hadUrls;

    IDocument *doc = m_plugin->core()->documentController()->activeDocument();
    if ( doc )
    {
        Path url = Path(doc->url()).parent();

        // always add the current file's parent directory
        hadUrls.insert(url);
        addUrlToMenu(ret, url.toUrl());

        url = url.parent();

        while(m_plugin->core()->projectController()->findProjectForUrl(url.toUrl()))
        {
            if (!Algorithm::insert(hadUrls, url).inserted) {
                break;
            }
            addUrlToMenu(ret, url.toUrl());
            url = url.parent();
        }
    }

    QVector<QUrl> otherProjectUrls;
    const auto projects = m_plugin->core()->projectController()->projects();
    for (IProject* project : projects) {
        if (!hadUrls.contains(project->path())) {
            otherProjectUrls.append(project->path().toUrl());
        }
    }

    // sort the remaining project URLs alphabetically
    std::sort(otherProjectUrls.begin(), otherProjectUrls.end());
    for (const QUrl& url : std::as_const(otherProjectUrls)) {
        addUrlToMenu(ret, url);
    }

    ret->addSeparator();
    addStringToMenu(ret, allOpenFilesString());
    addStringToMenu(ret, allOpenProjectsString());
    return ret;
}

GrepDialog::~GrepDialog()
{
}

void GrepDialog::setLastUsedSettings()
{
    Q_ASSERT_X(!m_show, Q_FUNC_INFO, "Precondition");

    const auto currentItem = [](const QStringList& itemList) {
        return itemList.value(0); // the first item (if any) in the list stored in config is current
    };

    const DialogConfigReader configReader;

    m_settings.pattern = currentItem(configReader.patternList());
    m_settings.searchTemplate = searchTemplateFromTemplateString(currentItem(configReader.templateStringList()));
    m_settings.replacementTemplate = currentItem(configReader.replacementTemplateStringList());
    m_settings.regexp = configReader.isRegex();
    m_settings.caseSensitive = configReader.isCaseSensitive();
    m_settings.searchPaths = currentItem(configReader.searchPathsList(*m_plugin));
    m_settings.depth = configReader.depth();
    m_settings.projectFilesOnly = configReader.limitToProjectFiles() && directoriesInProject(m_settings.searchPaths);
    m_settings.files = currentItem(configReader.filePatternsList());
    m_settings.exclude = currentItem(configReader.excludePatternsList());
}

void GrepDialog::setVisible(bool visible)
{
    QDialog::setVisible(visible && m_show);
}

void GrepDialog::closeEvent(QCloseEvent* closeEvent)
{
    Q_UNUSED(closeEvent);

    if (!m_show) {
        return;
    }

    auto cg = dialogConfigGroup();
    // memorize the last patterns and paths
    cg.writeEntry("LastSearchItems", qCombo2StringList(patternCombo));
    cg.writeEntry("regexp", regexCheck->isChecked());
    cg.writeEntry("depth", depthSpin->value());
    cg.writeEntry("search_project_files", limitToProjectCheck->isChecked());
    cg.writeEntry("case_sens", caseSensitiveCheck->isChecked());
    cg.writeEntry("exclude_patterns", qCombo2StringList(excludeCombo));
    cg.writeEntry("file_patterns", qCombo2StringList(filesCombo));
    cg.writeEntry("LastUsedTemplateIndex", templateTypeCombo->currentIndex());
    cg.writeEntry("LastUsedTemplateString", qCombo2StringList(templateEdit));
    cg.writeEntry("LastUsedReplacementTemplateString", qCombo2StringList(replacementTemplateEdit));
    cg.writeEntry("SearchPaths", qCombo2StringList(searchPaths));
    cg.sync();
}

void GrepDialog::templateTypeComboActivated(int index)
{
    templateEdit->setCurrentItem( template_str().at(index), true );
    replacementTemplateEdit->setCurrentItem( repl_template().at(index), true );
}

void GrepDialog::setPattern(const QString& pattern)
{
    if (m_show) {
        patternCombo->setEditText(pattern);
        patternComboEditTextChanged(pattern);
    }
    m_settings.pattern = pattern;
}

void GrepDialog::historySearch(QVector<GrepJobSettings> &settingsHistory)
{
    // clear the current settings history and pass it to a job list
    m_historyJobSettings.clear();
    m_historyJobSettings.swap(settingsHistory);

    // check if anything is do be done and if all projects are loaded
    if (!m_historyJobSettings.empty() && !checkProjectsOpened()) {
        connect(KDevelop::ICore::self()->projectController(),
                &KDevelop::IProjectController::projectOpened,
                this, &GrepDialog::checkProjectsOpened);
    }
}

void GrepDialog::setSearchLocations(const QString& dir)
{
    if (dir.isEmpty()) {
        return; // ignore an attempt to set invalid empty search location
    }

    if (!m_show) {
        m_settings.searchPaths = dir;
        return;
    }

    if (QDir::isAbsolutePath(dir)) {
        static_cast<KUrlCompletion*>(searchPaths->completionObject())->setDir(QUrl::fromLocalFile(dir));
    }

    if (searchPaths->contains(dir)) {
        searchPaths->removeItem(searchPaths->findText(dir));
    }

    searchPaths->insertItem(0, dir);
    searchPaths->setCurrentItem(dir);

    if (searchPaths->count() > pathsMaxCount) {
        searchPaths->removeItem(searchPaths->count() - 1);
    }

    updateLimitToProjectEnabled();
}

void GrepDialog::patternComboEditTextChanged( const QString& text)
{
    buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty());
}

bool GrepDialog::checkProjectsOpened()
{
    // only proceed if all projects have been opened
    if (KDevelop::ICore::self()->activeSession()->config()->group(QStringLiteral("General Options")).readEntry("Open Projects", QList<QUrl>()).count() !=
        KDevelop::ICore::self()->projectController()->projects().count())
        return false;

    const auto projects = KDevelop::ICore::self()->projectController()->projects();
    for (IProject* p : projects) {
        if (!p->isReady())
            return false;
    }

    // do the grep jobs one by one
    connect(m_plugin, &GrepViewPlugin::grepJobFinished, this, &GrepDialog::nextHistory);
    QTimer::singleShot(0, this, [=]() {nextHistory(true);});

    return true;
}

void GrepDialog::nextHistory(bool next)
{
    if (next && !m_historyJobSettings.empty()) {
        m_settings = m_historyJobSettings.takeFirst();
        startSearch();
    } else {
        close();
    }
}

bool GrepDialog::isPartOfChoice(const QUrl& url) const
{
    const auto choices = getDirectoryChoice(m_settings.searchPaths);
    for (const QUrl& choice : choices) {
        if(choice.isParentOf(url) || choice == url)
            return true;
    }
    return false;
}

void GrepDialog::startSearch()
{
    // if m_show is false, all settings are fixed in m_settings
    if (m_show)
        updateSettings();

    const QStringList include = GrepFindFilesThread::parseInclude(m_settings.files);
    const QStringList exclude = GrepFindFilesThread::parseExclude(m_settings.exclude);

    // search for unsaved documents
    QList<IDocument*> unsavedFiles;
    const auto documents = ICore::self()->documentController()->openDocuments();
    for (IDocument* doc : documents) {
        QUrl docUrl = doc->url();
        if (doc->state() != IDocument::Clean &&
            isPartOfChoice(docUrl) &&
            QDir::match(include, docUrl.fileName()) &&
            !WildcardHelpers::match(exclude, docUrl.toLocalFile())
        ) {
            unsavedFiles << doc;
        }
    }

    if(!ICore::self()->documentController()->saveSomeDocuments(unsavedFiles))
    {
        close();
        return;
    }

    const QString descriptionOrUrl(m_settings.searchPaths);
    QList<QUrl> choice = getDirectoryChoice(descriptionOrUrl);
    QString description = descriptionOrUrl;

    // Shorten the description
    if(descriptionOrUrl != allOpenFilesString() && descriptionOrUrl != allOpenProjectsString()) {
        auto prettyFileName = [](const QUrl& url) {
            return ICore::self()->projectController()->prettyFileName(url, KDevelop::IProjectController::FormatPlain);
        };

        if (choice.size() > 1) {
            description = i18np("%2, and %1 more item", "%2, and %1 more items", choice.size() - 1, prettyFileName(choice[0]));
        } else if (!choice.isEmpty()) {
            description = prettyFileName(choice[0]);
        }
    }

    GrepOutputView* toolView = m_toolView;
    if (!toolView) {
        toolView = static_cast<GrepOutputView*>(ICore::self()->uiController()->findToolView(
            i18nc("@title:window", "Find/Replace in Files"), m_plugin->toolViewFactory(),
            m_settings.fromHistory ? IUiController::Create : IUiController::CreateAndRaise));
        Q_ASSERT_X(toolView, Q_FUNC_INFO, "This branch may be taken only after UiController::loadAllAreas() returns.");
    }

    if (m_settings.fromHistory) {
        // when restored from history, only display the parameters
        toolView->renewModel(m_settings, i18nc("@item search result", "Search \"%1\" in %2", m_settings.pattern, description));
        emit m_plugin->grepJobFinished(true);
    } else {
        GrepOutputModel* outputModel =
            toolView->renewModel(m_settings,
                                i18nc("@item search result", "Search \"%1\" in %2 (at time %3)", m_settings.pattern, description,
                                    QTime::currentTime().toString(QStringLiteral("hh:mm"))));

        GrepJob* job = m_plugin->newGrepJob();
        connect(job, &GrepJob::showErrorMessage,
                toolView, &GrepOutputView::showErrorMessage);
        //the GrepOutputModel gets the 'showMessage' signal to store it and forward
        //it to toolView
        connect(job, &GrepJob::showMessage,
                outputModel, &GrepOutputModel::showMessageSlot);
        connect(outputModel, &GrepOutputModel::showMessage,
                toolView, &GrepOutputView::showMessage);

        connect(toolView, &GrepOutputView::outputViewIsClosed, job, [=]() {job->kill();});

        qCDebug(PLUGIN_GREPVIEW) << "starting search with settings" << m_settings;
        job->setOutputModel(outputModel);
        job->setDirectoryChoice(choice);
        job->setSettings(m_settings);

        ICore::self()->runController()->registerJob(job);
    }

    m_plugin->rememberSearchDirectory(descriptionOrUrl);

    // If m_show is false, the dialog is closed somewhere else,
    // or not closed but still destroyed via deleteLater() in GrepViewPlugin::showDialog().
    if (m_show)
        close();
}

void GrepDialog::updateSettings()
{
    m_settings.projectFilesOnly = limitToProjectCheck->isEnabled() && limitToProjectCheck->isChecked();

    m_settings.caseSensitive = caseSensitiveCheck->isChecked();
    m_settings.regexp = regexCheck->isChecked();

    m_settings.depth = depthSpin->value();

    m_settings.pattern = patternCombo->currentText();
    m_settings.searchTemplate = searchTemplateFromTemplateString(templateEdit->currentText());
    m_settings.replacementTemplate = replacementTemplateEdit->currentText();
    m_settings.files = filesCombo->currentText();
    m_settings.exclude = excludeCombo->currentText();

    m_settings.searchPaths = searchPaths->currentText();
}

void GrepDialog::updateLimitToProjectEnabled()
{
    Q_ASSERT_X(m_show, Q_FUNC_INFO, "The UI must be initialized.");
    const bool enabled = directoriesInProject(searchPaths->currentText());
    limitToProjectLabel->setEnabled(enabled);
    limitToProjectCheck->setEnabled(enabled);
}

#include "moc_grepdialog.cpp"