plugin_search.cpp 86.9 KB
Newer Older
Kåre Särs's avatar
Kåre Särs committed
1
/*   Kate search plugin
2
 *
3
 * Copyright (C) 2011-2013 by Kåre Särs <kare.sars@iki.fi>
Kåre Särs's avatar
Kåre Särs committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program in a file called COPYING; if not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

#include "plugin_search.h"

23 24
#include "htmldelegate.h"

25
#include <ktexteditor/application.h>
26
#include <ktexteditor/editor.h>
Kåre Särs's avatar
Kåre Särs committed
27 28
#include <ktexteditor/view.h>
#include <ktexteditor/document.h>
29 30 31
#include <ktexteditor/markinterface.h>
#include <ktexteditor/movinginterface.h>
#include <ktexteditor/movingrange.h>
32
#include <ktexteditor/configinterface.h>
Kåre Särs's avatar
Kåre Särs committed
33

34
#include "kacceleratormanager.h"
Kåre Särs's avatar
Kåre Särs committed
35
#include <kactioncollection.h>
36
#include <klocalizedstring.h>
Kåre Särs's avatar
Kåre Särs committed
37 38 39
#include <kpluginfactory.h>
#include <kpluginloader.h>
#include <kaboutdata.h>
40
#include <kurlcompletion.h>
41
#include <klineedit.h>
42
#include <kcolorscheme.h>
43 44 45

#include <KXMLGUIFactory>
#include <KConfigGroup>
46

47 48
#include <QKeyEvent>
#include <QClipboard>
49
#include <QMenu>
50
#include <QMetaObject>
51
#include <QTextDocument>
52
#include <QScrollBar>
53 54
#include <QFileInfo>
#include <QDir>
55 56
#include <QComboBox>
#include <QCompleter>
57 58 59 60 61

static QUrl localFileDirUp (const QUrl &url)
{
    if (!url.isLocalFile())
        return url;
62

63 64 65
    // else go up
    return QUrl::fromLocalFile (QFileInfo (url.toLocalFile()).dir().absolutePath());
}
66 67 68 69 70 71 72 73 74 75 76 77

static QAction *menuEntry(QMenu *menu,
                          const QString &before, const QString &after, const QString &desc,
                          QString menuBefore = QString(), QString menuAfter = QString());

static QAction *menuEntry(QMenu *menu,
                          const QString &before, const QString &after, const QString &desc,
                          QString menuBefore, QString menuAfter)
{
    if (menuBefore.isEmpty()) menuBefore = before;
    if (menuAfter.isEmpty())  menuAfter = after;

78
    QAction *const action = menu->addAction(menuBefore + menuAfter + QLatin1Char('\t') + desc);
79
    if (!action) return nullptr;
80

81
    action->setData(QString(before + QLatin1Char(' ') + after));
82 83
    return action;
}
Kåre Särs's avatar
Kåre Särs committed
84

85 86 87 88 89 90
class TreeWidgetItem : public QTreeWidgetItem {
public:
    TreeWidgetItem(QTreeWidget* parent):QTreeWidgetItem(parent){}
    TreeWidgetItem(QTreeWidget* parent, const QStringList &list):QTreeWidgetItem(parent, list){}
    TreeWidgetItem(QTreeWidgetItem* parent, const QStringList &list):QTreeWidgetItem(parent, list){}
private:
Kevin Funk's avatar
Kevin Funk committed
91
    bool operator<(const QTreeWidgetItem &other) const override {
92
        if (childCount() == 0) {
93 94 95 96
            int line = data(0, ReplaceMatches::LineRole).toInt();
            int column = data(0, ReplaceMatches::ColumnRole).toInt();
            int oLine = other.data(0, ReplaceMatches::LineRole).toInt();
            int oColumn = other.data(0, ReplaceMatches::ColumnRole).toInt();
97 98 99 100 101 102 103 104
            if (line < oLine) {
                return true;
            }
            if ((line == oLine) && (column < oColumn)) {
                return true;
            }
            return false;
        }
105 106
        int sepCount = data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
        int oSepCount = other.data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
107 108
        if (sepCount < oSepCount) return true;
        if (sepCount > oSepCount) return false;
109
        return data(0, ReplaceMatches::FileUrlRole).toString().toLower() < other.data(0, ReplaceMatches::FileUrlRole).toString().toLower();
110 111 112
    }
};

113
Results::Results(QWidget *parent): QWidget(parent), matches(0), useRegExp(false), searchPlaceIndex(0)
114 115
{
    setupUi(this);
116

117 118 119 120
    tree->setItemDelegate(new SPHtmlDelegate(tree));
}


121
K_PLUGIN_FACTORY_WITH_JSON (KatePluginSearchFactory, "katesearch.json", registerPlugin<KatePluginSearch>();)
Kåre Särs's avatar
Kåre Särs committed
122 123

KatePluginSearch::KatePluginSearch(QObject* parent, const QList<QVariant>&)
124
    : KTextEditor::Plugin (parent),
125
    m_searchCommand(nullptr)
Kåre Särs's avatar
Kåre Särs committed
126
{
127
    m_searchCommand = new KateSearchCommand(this);
Kåre Särs's avatar
Kåre Särs committed
128 129 130 131
}

KatePluginSearch::~KatePluginSearch()
{
132
    delete m_searchCommand;
Kåre Särs's avatar
Kåre Särs committed
133 134
}

135
QObject *KatePluginSearch::createView(KTextEditor::MainWindow *mainWindow)
Kåre Särs's avatar
Kåre Särs committed
136
{
137
    KatePluginSearchView *view = new KatePluginSearchView(this, mainWindow, KTextEditor::Editor::instance()->application());
138 139 140 141
    connect(m_searchCommand, &KateSearchCommand::setSearchPlace, view, &KatePluginSearchView::setSearchPlace);
    connect(m_searchCommand, &KateSearchCommand::setCurrentFolder, view, &KatePluginSearchView::setCurrentFolder);
    connect(m_searchCommand, &KateSearchCommand::setSearchString, view, &KatePluginSearchView::setSearchString);
    connect(m_searchCommand, &KateSearchCommand::startSearch, view, &KatePluginSearchView::startSearch);
142
    connect(m_searchCommand, SIGNAL(newTab()), view, SLOT(addTab()));
143
    return view;
Kåre Särs's avatar
Kåre Särs committed
144 145 146
}


147
bool ContainerWidget::focusNextPrevChild (bool next)
148
{
149 150 151
    QWidget* fw = focusWidget();
    bool found = false;
    emit nextFocus(fw, &found, next);
152

153 154 155 156
    if (found) {
        return true;
    }
    return QWidget::focusNextPrevChild(next);
157 158
}

159
void KatePluginSearchView::nextFocus(QWidget *currentWidget, bool *found, bool next)
160
{
161 162 163 164 165 166
    *found = false;

    if (!currentWidget) {
        return;
    }

167
    // we use the object names here because there can be multiple replaceButtons (on multiple result tabs)
168
    if (next) {
169
        if (currentWidget->objectName() == QStringLiteral("tree") || currentWidget == m_ui.binaryCheckBox) {
170 171 172 173
            m_ui.newTabButton->setFocus();
            *found = true;
            return;
        }
174 175
        if (currentWidget == m_ui.displayOptions) {
            if (m_ui.displayOptions->isChecked()) {
176
                m_ui.folderRequester->setFocus();
177 178 179 180 181 182 183 184 185 186 187 188
                *found = true;
                return;
            }
            else {
                Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
                if (!res) {
                    return;
                }
                res->tree->setFocus();
                *found = true;
                return;
            }
189
        }
190
    }
191 192
    else {
        if (currentWidget == m_ui.newTabButton) {
193
            if (m_ui.displayOptions->isChecked()) {
194
                m_ui.binaryCheckBox->setFocus();
195 196 197 198 199 200 201 202 203 204
            }
            else {
                Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
                if (!res) {
                    return;
                }
                res->tree->setFocus();
            }
            *found = true;
            return;
205 206
        }
        else {
Joseph Wenninger's avatar
Joseph Wenninger committed
207
            if (currentWidget->objectName() == QStringLiteral("tree")) {
208 209
                m_ui.displayOptions->setFocus();
                *found = true;
210 211 212
                return;
            }
        }
213 214 215
    }
}

216
KatePluginSearchView::KatePluginSearchView(KTextEditor::Plugin *plugin, KTextEditor::MainWindow *mainWin, KTextEditor::Application* application)
217
: QObject (mainWin),
218
m_kateApp(application),
219
m_curResults(nullptr),
220
m_searchJustOpened(false),
221
m_switchToProjectModeWhenAvailable(false),
222 223
m_searchDiskFilesDone(true),
m_searchOpenFilesDone(true),
224
m_projectPluginView(nullptr),
225
m_mainWindow (mainWin)
Kåre Särs's avatar
Kåre Särs committed
226
{
Joseph Wenninger's avatar
Joseph Wenninger committed
227 228
    KXMLGUIClient::setComponentName (QStringLiteral("katesearch"), i18n ("Kate Search & Replace"));
    setXMLFile( QStringLiteral("ui.rc") );
229

Joseph Wenninger's avatar
Joseph Wenninger committed
230
    m_toolView = mainWin->createToolView (plugin, QStringLiteral("kate_plugin_katesearch"),
231
                                          KTextEditor::MainWindow::Bottom,
232
                                          QIcon::fromTheme(QStringLiteral("edit-find")),
233 234
                                          i18n("Search and Replace"));

235
    ContainerWidget *container = new ContainerWidget(m_toolView);
236
    m_ui.setupUi(container);
Kåre Särs's avatar
Kåre Särs committed
237
    container->setFocusProxy(m_ui.searchCombo);
238
    connect(container, &ContainerWidget::nextFocus, this, &KatePluginSearchView::nextFocus);
239

Joseph Wenninger's avatar
Joseph Wenninger committed
240
    QAction *a = actionCollection()->addAction(QStringLiteral("search_in_files"));
241
    actionCollection()->setDefaultShortcut(a, QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_F));
Kåre Särs's avatar
Kåre Särs committed
242
    a->setText(i18n("Search in Files"));
243
    connect(a, &QAction::triggered, this, &KatePluginSearchView::openSearchView);
244

Joseph Wenninger's avatar
Joseph Wenninger committed
245
    a = actionCollection()->addAction(QStringLiteral("search_in_files_new_tab"));
246 247
    a->setText(i18n("Search in Files (in new tab)"));
    // first add tab, then open search view, since open search view switches to show the search options
248 249
    connect(a, &QAction::triggered, this, &KatePluginSearchView::addTab);
    connect(a, &QAction::triggered, this, &KatePluginSearchView::openSearchView);
250

Joseph Wenninger's avatar
Joseph Wenninger committed
251
    a = actionCollection()->addAction(QStringLiteral("go_to_next_match"));
252
    a->setText(i18n("Go to Next Match"));
253
    connect(a, &QAction::triggered, this, &KatePluginSearchView::goToNextMatch);
254

Joseph Wenninger's avatar
Joseph Wenninger committed
255
    a = actionCollection()->addAction(QStringLiteral("go_to_prev_match"));
256
    a->setText(i18n("Go to Previous Match"));
257
    connect(a, &QAction::triggered, this, &KatePluginSearchView::goToPreviousMatch);
258

259
    m_ui.resultTabWidget->tabBar()->setSelectionBehaviorOnRemove(QTabBar::SelectLeftTab);
260
    KAcceleratorManager::setNoAccel(m_ui.resultTabWidget);
261

262
    // Gnome does not seem to have all icons we want, so we use fall-back icons for those that are missing.
263 264 265 266
    QIcon dispOptIcon = QIcon::fromTheme(QStringLiteral("games-config-options"), QIcon::fromTheme(QStringLiteral("preferences-system")));
    QIcon matchCaseIcon = QIcon::fromTheme(QStringLiteral("format-text-superscript"), QIcon::fromTheme(QStringLiteral("format-text-bold")));
    QIcon useRegExpIcon = QIcon::fromTheme(QStringLiteral("code-context"), QIcon::fromTheme(QStringLiteral("edit-find-replace")));
    QIcon expandResultsIcon = QIcon::fromTheme(QStringLiteral("view-list-tree"), QIcon::fromTheme(QStringLiteral("format-indent-more")));
267 268

    m_ui.displayOptions->setIcon(dispOptIcon);
269
    m_ui.searchButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-find")));
270
    m_ui.nextButton->setIcon(QIcon::fromTheme(QStringLiteral("go-down-search")));
271
    m_ui.stopButton->setIcon(QIcon::fromTheme(QStringLiteral("process-stop")));
272 273 274
    m_ui.matchCase->setIcon(matchCaseIcon);
    m_ui.useRegExp->setIcon(useRegExpIcon);
    m_ui.expandResults->setIcon(expandResultsIcon);
275 276 277
    m_ui.searchPlaceCombo->setItemIcon(CurrentFile, QIcon::fromTheme(QStringLiteral("text-plain")));
    m_ui.searchPlaceCombo->setItemIcon(OpenFiles, QIcon::fromTheme(QStringLiteral("text-plain")));
    m_ui.searchPlaceCombo->setItemIcon(Folder, QIcon::fromTheme(QStringLiteral("folder")));
278 279 280
    m_ui.folderUpButton->setIcon(QIcon::fromTheme(QStringLiteral("go-up")));
    m_ui.currentFolderButton->setIcon(QIcon::fromTheme(QStringLiteral("view-refresh")));
    m_ui.newTabButton->setIcon(QIcon::fromTheme(QStringLiteral("tab-new")));
281

282 283
    m_ui.filterCombo->setToolTip(i18n("Comma separated list of file types to search in. Example: \"*.cpp,*.h\"\n"));
    m_ui.excludeCombo->setToolTip(i18n("Comma separated list of files and directories to exclude from the search. Example: \"build*\""));
284

285 286
    // the order here is important to get the tabBar hidden for only one tab
    addTab();
287
    m_ui.resultTabWidget->tabBar()->hide();
288 289 290 291 292 293 294 295 296 297

    // get url-requester's combo box and sanely initialize
    KComboBox* cmbUrl = m_ui.folderRequester->comboBox();
    cmbUrl->setDuplicatesEnabled(false);
    cmbUrl->setEditable(true);
    m_ui.folderRequester->setMode(KFile::Directory | KFile::LocalOnly);
    KUrlCompletion* cmpl = new KUrlCompletion(KUrlCompletion::DirCompletion);
    cmbUrl->setCompletionObject(cmpl);
    cmbUrl->setAutoDeleteCompletionObject(true);

298 299 300
    connect(m_ui.newTabButton, &QToolButton::clicked, this, &KatePluginSearchView::addTab);
    connect(m_ui.resultTabWidget, &QTabWidget::tabCloseRequested, this, &KatePluginSearchView::tabCloseRequested);
    connect(m_ui.resultTabWidget, &QTabWidget::currentChanged, this, &KatePluginSearchView::resultTabChanged);
301

302 303 304
    connect(m_ui.folderUpButton, &QToolButton::clicked, this, &KatePluginSearchView::navigateFolderUp);
    connect(m_ui.currentFolderButton, &QToolButton::clicked, this, &KatePluginSearchView::setCurrentFolder);
    connect(m_ui.expandResults, &QToolButton::clicked, this, &KatePluginSearchView::expandResults);
305

306 307
    connect(m_ui.searchCombo, &QComboBox::editTextChanged, &m_changeTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
    connect(m_ui.matchCase, &QToolButton::toggled, &m_changeTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
308
    connect(m_ui.matchCase, &QToolButton::toggled, this, [=]{
309 310 311 312 313
        Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
        if (res) {
            res->matchCase = m_ui.matchCase->isChecked();
        }
    });
314
    connect(m_ui.useRegExp, &QToolButton::toggled, &m_changeTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
315
    connect(m_ui.useRegExp, &QToolButton::toggled, this, [=]{
316 317 318 319 320
        Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
        if (res) {
            res->useRegExp = m_ui.useRegExp->isChecked();
        }
    });
321
    m_changeTimer.setInterval(300);
Kåre Särs's avatar
Kåre Särs committed
322
    m_changeTimer.setSingleShot(true);
323
    connect(&m_changeTimer, &QTimer::timeout, this, &KatePluginSearchView::startSearchWhileTyping);
324

325
    connect(m_ui.searchCombo->lineEdit(), &QLineEdit::returnPressed, this, &KatePluginSearchView::startSearch);
326
// connecting to returnPressed() of the folderRequester doesn't work, I haven't found out why yet. But connecting to the linedit works:
327 328 329 330
    connect(m_ui.folderRequester->comboBox()->lineEdit(), &QLineEdit::returnPressed, this, &KatePluginSearchView::startSearch);
    connect(m_ui.filterCombo, static_cast<void (KComboBox::*)()>(&KComboBox::returnPressed), this, &KatePluginSearchView::startSearch);
    connect(m_ui.excludeCombo, static_cast<void (KComboBox::*)()>(&KComboBox::returnPressed), this, &KatePluginSearchView::startSearch);
    connect(m_ui.searchButton, &QPushButton::clicked, this, &KatePluginSearchView::startSearch);
331

332 333
    connect(m_ui.displayOptions, &QToolButton::toggled, this, &KatePluginSearchView::toggleOptions);
    connect(m_ui.searchPlaceCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &KatePluginSearchView::searchPlaceChanged);
334 335 336 337 338
    connect(m_ui.searchPlaceCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int) {
        if (m_ui.searchPlaceCombo->currentIndex() == Folder) {
            m_ui.displayOptions->setChecked(true);
        }
    });
339

340 341 342 343
    connect(m_ui.stopButton, &QPushButton::clicked, &m_searchOpenFiles, &SearchOpenFiles::cancelSearch);
    connect(m_ui.stopButton, &QPushButton::clicked, &m_searchDiskFiles, &SearchDiskFiles::cancelSearch);
    connect(m_ui.stopButton, &QPushButton::clicked, &m_folderFilesList, &FolderFilesList::cancelSearch);
    connect(m_ui.stopButton, &QPushButton::clicked, &m_replacer, &ReplaceMatches::cancelReplace);
344

345
    connect(m_ui.nextButton, &QToolButton::clicked, this, &KatePluginSearchView::goToNextMatch);
346

347 348 349
    connect(m_ui.replaceButton, &QPushButton::clicked, this, &KatePluginSearchView::replaceSingleMatch);
    connect(m_ui.replaceCheckedBtn, &QPushButton::clicked, this, &KatePluginSearchView::replaceChecked);
    connect(m_ui.replaceCombo->lineEdit(), &QLineEdit::returnPressed, this, &KatePluginSearchView::replaceChecked);
350 351 352



Kåre Särs's avatar
Kåre Särs committed
353 354
    m_ui.displayOptions->setChecked(true);

355 356 357
    connect(&m_searchOpenFiles, &SearchOpenFiles::matchFound, this, &KatePluginSearchView::matchFound);
    connect(&m_searchOpenFiles, &SearchOpenFiles::searchDone, this, &KatePluginSearchView::searchDone);
    connect(&m_searchOpenFiles, static_cast<void (SearchOpenFiles::*)(const QString&)>(&SearchOpenFiles::searching), this, &KatePluginSearchView::searching);
Kåre Särs's avatar
Kåre Särs committed
358

359 360
    connect(&m_folderFilesList, &FolderFilesList::finished, this, &KatePluginSearchView::folderFileListChanged);
    connect(&m_folderFilesList, &FolderFilesList::searching, this, &KatePluginSearchView::searching);
361

362 363 364
    connect(&m_searchDiskFiles, &SearchDiskFiles::matchFound, this, &KatePluginSearchView::matchFound);
    connect(&m_searchDiskFiles, &SearchDiskFiles::searchDone, this, &KatePluginSearchView::searchDone);
    connect(&m_searchDiskFiles, static_cast<void (SearchDiskFiles::*)(const QString&)>(&SearchDiskFiles::searching), this, &KatePluginSearchView::searching);
365

366
    connect(m_kateApp, &KTextEditor::Application::documentWillBeDeleted, &m_searchOpenFiles, &SearchOpenFiles::cancelSearch);
367

368
    connect(m_kateApp, &KTextEditor::Application::documentWillBeDeleted, &m_replacer, &ReplaceMatches::cancelReplace);
369

370
    connect(m_kateApp, &KTextEditor::Application::documentWillBeDeleted, this, &KatePluginSearchView::clearDocMarks);
371

372
    connect(&m_replacer, &ReplaceMatches::matchReplaced, this, &KatePluginSearchView::addMatchMark);
373

374 375
    connect(&m_replacer, &ReplaceMatches::replaceStatus, this, &KatePluginSearchView::replaceStatus);

376 377
    // Hook into line edit context menus
    m_ui.searchCombo->setContextMenuPolicy(Qt::CustomContextMenu);
378
    connect(m_ui.searchCombo, &QComboBox::customContextMenuRequested, this, &KatePluginSearchView::searchContextMenu);
379
    m_ui.searchCombo->completer()->setCompletionMode(QCompleter::PopupCompletion);
380
    m_ui.searchCombo->completer()->setCaseSensitivity(Qt::CaseSensitive);
381 382 383 384
    m_ui.searchCombo->setInsertPolicy(QComboBox::NoInsert);
    m_ui.searchCombo->lineEdit()->setClearButtonEnabled(true);
    m_ui.searchCombo->setMaxCount(25);

385
    m_ui.replaceCombo->completer()->setCompletionMode(QCompleter::PopupCompletion);
386
    m_ui.replaceCombo->completer()->setCaseSensitivity(Qt::CaseSensitive);
387 388 389 390
    m_ui.replaceCombo->setInsertPolicy(QComboBox::NoInsert);
    m_ui.replaceCombo->lineEdit()->setClearButtonEnabled(true);
    m_ui.replaceCombo->setMaxCount(25);

391 392
    m_toolView->setMinimumHeight(container->sizeHint().height());

393
    connect(m_mainWindow, &KTextEditor::MainWindow::unhandledShortcutOverride, this, &KatePluginSearchView::handleEsc);
394

395
    // watch for project plugin view creation/deletion
396
    connect(m_mainWindow, &KTextEditor::MainWindow::pluginViewCreated, this, &KatePluginSearchView::slotPluginViewCreated);
397

398
    connect(m_mainWindow, &KTextEditor::MainWindow::pluginViewDeleted, this, &KatePluginSearchView::slotPluginViewDeleted);
399

400
    connect(m_mainWindow, &KTextEditor::MainWindow::viewChanged, this, &KatePluginSearchView::docViewChanged);
401 402


403
    // update once project plugin state manually
Joseph Wenninger's avatar
Joseph Wenninger committed
404
    m_projectPluginView = m_mainWindow->pluginView (QStringLiteral("kateprojectplugin"));
405 406
    slotProjectFileNameChanged ();

407
    m_replacer.setDocumentManager(m_kateApp);
408
    connect(&m_replacer, &ReplaceMatches::replaceDone, this, &KatePluginSearchView::replaceDone);
409

410 411
    searchPlaceChanged();

412 413
    m_toolView->installEventFilter(this);

414
    m_mainWindow->guiFactory()->addClient(this);
Kåre Särs's avatar
Kåre Särs committed
415 416 417 418
}

KatePluginSearchView::~KatePluginSearchView()
{
419 420
    clearMarks();

421
    m_mainWindow->guiFactory()->removeClient(this);
422
    delete m_toolView;
Kåre Särs's avatar
Kåre Särs committed
423 424
}

425
void KatePluginSearchView::navigateFolderUp()
426 427
{
    // navigate one folder up
428
    m_ui.folderRequester->setUrl(localFileDirUp(m_ui.folderRequester->url()));
429 430
}

431 432
void KatePluginSearchView::setCurrentFolder()
{
433
    if (!m_mainWindow) {
434 435
        return;
    }
436
    KTextEditor::View* editView = m_mainWindow->activeView();
437 438
    if (editView && editView->document()) {
        // upUrl as we want the folder not the file
439
        m_ui.folderRequester->setUrl(localFileDirUp(editView->document()->url()));
440
    }
441
    m_ui.displayOptions->setChecked(true);
442 443
}

444
void KatePluginSearchView::openSearchView()
Kåre Särs's avatar
Kåre Särs committed
445
{
446
    if (!m_mainWindow) {
Kåre Särs's avatar
Kåre Särs committed
447 448 449
        return;
    }
    if (!m_toolView->isVisible()) {
450
        m_mainWindow->showToolView(m_toolView);
451
    }
452
    m_ui.searchCombo->setFocus(Qt::OtherFocusReason);
453 454 455
    if (m_ui.searchPlaceCombo->currentIndex() == Folder) {
        m_ui.displayOptions->setChecked(true);
    }
456

457
    KTextEditor::View* editView = m_mainWindow->activeView();
458
    if (editView && editView->document()) {
459
        if (m_ui.folderRequester->text().isEmpty()) {
460
            // upUrl as we want the folder not the file
461
            m_ui.folderRequester->setUrl(localFileDirUp (editView->document()->url()));
462
        }
463
        QString selection;
464
        if (editView->selection()) {
465
            selection = editView->selectionText();
466
            // remove possible trailing '\n'
467
            if (selection.endsWith(QLatin1Char('\n'))) {
468 469
                selection = selection.left(selection.size() -1);
            }
470
        }
471
        if (selection.isEmpty()) {
472
            selection = editView->document()->wordAt(editView->cursorPosition());
473 474
        }

475
        if (!selection.isEmpty() && !selection.contains(QLatin1Char('\n'))) {
476 477 478 479 480
            m_ui.searchCombo->blockSignals(true);
            m_ui.searchCombo->lineEdit()->setText(selection);
            m_ui.searchCombo->blockSignals(false);
        }

481 482
        m_ui.searchCombo->lineEdit()->selectAll();
        m_searchJustOpened = true;
483
        startSearchWhileTyping();
Kåre Särs's avatar
Kåre Särs committed
484 485 486
    }
}

487 488
void KatePluginSearchView::handleEsc(QEvent *e)
{
489
    if (!m_mainWindow) return;
490 491 492

    QKeyEvent *k = static_cast<QKeyEvent *>(e);
    if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) {
493 494 495 496
        static ulong lastTimeStamp;
        if (lastTimeStamp == k->timestamp()) {
            // Same as previous... This looks like a bug somewhere...
            return;
497
        }
498 499
        lastTimeStamp = k->timestamp();
        if (!m_matchRanges.isEmpty()) {
500 501
            clearMarks();
        }
502 503 504
        else if (m_toolView->isVisible()) {
            m_mainWindow->hideToolView(m_toolView);
        }
505 506 507
    }
}

508 509 510 511 512
void KatePluginSearchView::setSearchString(const QString &pattern)
{
    m_ui.searchCombo->lineEdit()->setText(pattern);
}

513 514 515 516 517 518 519 520 521
void KatePluginSearchView::toggleOptions(bool show)
{
    m_ui.stackedWidget->setCurrentIndex((show) ? 1:0);
}

void KatePluginSearchView::setSearchPlace(int place)
{
    m_ui.searchPlaceCombo->setCurrentIndex(place);
}
522 523 524 525

QStringList KatePluginSearchView::filterFiles(const QStringList& files) const
{
    QString types = m_ui.filterCombo->currentText();
526
    QString excludes = m_ui.excludeCombo->currentText();
Joseph Wenninger's avatar
Joseph Wenninger committed
527
    if (((types.isEmpty() || types == QStringLiteral("*"))) && (excludes.isEmpty())) {
528 529 530 531
        // shortcut for use all files
        return files;
    }

532
    QStringList tmpTypes = types.split(QLatin1Char(','));
533 534
    QVector<QRegExp> typeList;
    for (int i=0; i<tmpTypes.size(); i++) {
535
        QRegExp rx(tmpTypes[i].trimmed());
536 537 538 539
        rx.setPatternSyntax(QRegExp::Wildcard);
        typeList << rx;
    }

540
    QStringList tmpExcludes = excludes.split(QLatin1Char(','));
541 542
    QVector<QRegExp> excludeList;
    for (int i=0; i<tmpExcludes.size(); i++) {
543
        QRegExp rx(tmpExcludes[i].trimmed());
544 545 546 547
        rx.setPatternSyntax(QRegExp::Wildcard);
        excludeList << rx;
    }

548 549 550
    QStringList filteredFiles;
    foreach (QString fileName, files) {
        bool isInSubDir = fileName.startsWith(m_resultBaseDir);
551
        QString nameToCheck = fileName;
552
        if (isInSubDir) {
553
            nameToCheck = fileName.mid(m_resultBaseDir.size());
554 555
        }

556 557 558 559 560 561 562 563 564 565 566 567
        bool skip = false;
        for (int i=0; i<excludeList.size(); i++) {
            if (excludeList[i].exactMatch(nameToCheck)) {
                skip = true;
                break;
            }
        }
        if (skip) {
            continue;
        }


568
        for (int i=0; i<typeList.size(); i++) {
569
            if (typeList[i].exactMatch(nameToCheck)) {
570 571 572 573 574 575 576 577
                filteredFiles << fileName;
                break;
            }
        }
    }
    return filteredFiles;
}

578
void KatePluginSearchView::folderFileListChanged()
Kåre Särs's avatar
Kåre Särs committed
579
{
580 581
    m_searchDiskFilesDone = false;
    m_searchOpenFilesDone = false;
582

583
    if (!m_curResults) {
584
        qWarning() << "This is a bug";
585 586 587
        m_searchDiskFilesDone = true;
        m_searchOpenFilesDone = true;
        searchDone();
588 589
        return;
    }
590
    QStringList fileList = m_folderFilesList.fileList();
591

592
    QList<KTextEditor::Document*> openList;
593
    for (int i=0; i<m_kateApp->documents().size(); i++) {
594
        int index = fileList.indexOf(m_kateApp->documents()[i]->url().toLocalFile());
595
        if (index != -1) {
596
            openList << m_kateApp->documents()[i];
597 598
            fileList.removeAt(index);
        }
Kåre Särs's avatar
Kåre Särs committed
599
    }
600 601 602 603 604 605

    // search order is important: Open files starts immediately and should finish
    // earliest after first event loop.
    // The DiskFile might finish immediately
    if (openList.size() > 0) {
        m_searchOpenFiles.startSearch(openList, m_curResults->regExp);
606 607
    }
    else {
608
        m_searchOpenFilesDone = true;
Kåre Särs's avatar
Kåre Särs committed
609 610
    }

611
    m_searchDiskFiles.startSearch(fileList, m_curResults->regExp);
Kåre Särs's avatar
Kåre Särs committed
612 613
}

614

Kåre Särs's avatar
Kåre Särs committed
615 616
void KatePluginSearchView::searchPlaceChanged()
{
617 618
    int searchPlace = m_ui.searchPlaceCombo->currentIndex();
    const bool inFolder = (searchPlace == Folder);
619

620 621
    m_ui.filterCombo->setEnabled(searchPlace >= Folder);
    m_ui.excludeCombo->setEnabled(searchPlace >= Folder);
622 623 624 625 626 627 628 629
    m_ui.folderRequester->setEnabled(inFolder);
    m_ui.folderUpButton->setEnabled(inFolder);
    m_ui.currentFolderButton->setEnabled(inFolder);
    m_ui.recursiveCheckBox->setEnabled(inFolder);
    m_ui.hiddenCheckBox->setEnabled(inFolder);
    m_ui.symLinkCheckBox->setEnabled(inFolder);
    m_ui.binaryCheckBox->setEnabled(inFolder);

630 631 632 633
    if (inFolder && sender() == m_ui.searchPlaceCombo) {
        setCurrentFolder();
    }

634 635 636 637
    // ... and the labels:
    m_ui.folderLabel->setEnabled(m_ui.folderRequester->isEnabled());
    m_ui.filterLabel->setEnabled(m_ui.filterCombo->isEnabled());
    m_ui.excludeLabel->setEnabled(m_ui.excludeCombo->isEnabled());
638 639 640 641 642

    Results *res = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
    if (res) {
        res->searchPlaceIndex = searchPlace;
    }
Kåre Särs's avatar
Kåre Särs committed
643 644
}

645
void KatePluginSearchView::addHeaderItem()
646
{
647
    QTreeWidgetItem *item = new QTreeWidgetItem(m_curResults->tree, QStringList());
648 649
    item->setCheckState(0, Qt::Checked);
    item->setFlags(item->flags() | Qt::ItemIsTristate);
650
    m_curResults->tree->expandItem(item);
651 652
}

653
QTreeWidgetItem * KatePluginSearchView::rootFileItem(const QString &url, const QString &fName)
654
{
655
    if (!m_curResults) {
656
        return nullptr;
657 658
    }

659
    QUrl fullUrl = QUrl::fromUserInput(url);
660
    QString path = fullUrl.isLocalFile() ? localFileDirUp(fullUrl).path() : fullUrl.url();
661 662 663
    if (!path.isEmpty() && !path.endsWith(QLatin1Char('/'))) {
        path += QLatin1Char('/');
    }
664
    path.replace(m_resultBaseDir, QString());
665
    QString name = fullUrl.fileName();
666 667 668
    if (url.isEmpty()) {
        name = fName;
    }
669

670
    // make sure we have a root item
671
    if (m_curResults->tree->topLevelItemCount() == 0) {
672
        addHeaderItem();
673 674 675
    }
    QTreeWidgetItem *root = m_curResults->tree->topLevelItem(0);

676 677 678
    if (root->data(0, ReplaceMatches::FileNameRole).toString() == fName) {
        // The root item contains the document name ->
        // this is search as you type, return the root item
679 680 681
        return root;
    }

682
    for (int i=0; i<root->childCount(); i++) {
683
        //qDebug() << root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() << fName;
684 685 686
        if ((root->child(i)->data(0, ReplaceMatches::FileUrlRole).toString() == url)&&
            (root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() == fName)) {
            int matches = root->child(i)->data(0, ReplaceMatches::LineRole).toInt() + 1;
687
            QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(matches);
688
            root->child(i)->setData(0, Qt::DisplayRole, tmpUrl);
689
            root->child(i)->setData(0, ReplaceMatches::LineRole, matches);
690
            return root->child(i);
691 692
        }
    }
693

694
    // file item not found create a new one
695
    QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(1);
696

697
    TreeWidgetItem *item = new TreeWidgetItem(root, QStringList(tmpUrl));
698 699 700
    item->setData(0, ReplaceMatches::FileUrlRole, url);
    item->setData(0, ReplaceMatches::FileNameRole, fName);
    item->setData(0, ReplaceMatches::LineRole, 1);
701
    item->setCheckState(0, Qt::Checked);
702
    item->setFlags(item->flags() | Qt::ItemIsTristate);
703 704 705
    return item;
}

706
void KatePluginSearchView::addMatchMark(KTextEditor::Document* doc, int line, int column, int endLine, int endColumn)
707 708 709
{
    if (!doc) return;

710
    KTextEditor::View* activeView = m_mainWindow->activeView();
711
    KTextEditor::MovingInterface* miface = qobject_cast<KTextEditor::MovingInterface*>(doc);
712
    KTextEditor::ConfigInterface* ciface = qobject_cast<KTextEditor::ConfigInterface*>(activeView);
713
    KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute());
714

715
    bool replace = ((sender() == &m_replacer) || (sender() == nullptr) || (sender() == m_ui.replaceButton));
716
    if (replace) {
717
        QColor replaceColor(Qt::green);
Joseph Wenninger's avatar
Joseph Wenninger committed
718
        if (ciface) replaceColor = ciface->configValue(QStringLiteral("replace-highlight-color")).value<QColor>();
719
        attr->setBackground(replaceColor);
720 721 722 723

        if (activeView) {
            attr->setForeground(activeView->defaultStyleAttribute(KTextEditor::dsNormal)->foreground().color());
        }
724 725
    }
    else {
726
        QColor searchColor(Qt::yellow);
Joseph Wenninger's avatar
Joseph Wenninger committed
727
        if (ciface) searchColor = ciface->configValue(QStringLiteral("search-highlight-color")).value<QColor>();
728
        attr->setBackground(searchColor);
729 730 731 732

        if (activeView) {
            attr->setForeground(activeView->defaultStyleAttribute(KTextEditor::dsNormal)->foreground().color());
        }
733
    }
734

735
    KTextEditor::Range range(line, column, endLine, endColumn);
736

737
    if (m_curResults && !replace) {
738
        // special handling for "(?=\\n)" in multi-line search
739
        QRegularExpression tmpReg = m_curResults->regExp;
Joseph Wenninger's avatar
Joseph Wenninger committed
740
        if (m_curResults->regExp.pattern().endsWith(QStringLiteral("(?=\\n)"))) {
741
            QString newPatern = tmpReg.pattern();
Joseph Wenninger's avatar
Joseph Wenninger committed
742
            newPatern.replace(QStringLiteral("(?=\\n)"), QStringLiteral("$"));
743 744 745
            tmpReg.setPattern(newPatern);
        }

746
        // Check that the match still matches ;)
747
        if (tmpReg.match(doc->text(range)).capturedStart() != 0) {
748
            qDebug() << doc->text(range) << "Does not match" << m_curResults->regExp.pattern();
749 750 751 752
            return;
        }
    }

753
    // Highlight the match
754 755 756 757 758 759
    KTextEditor::MovingRange* mr = miface->newMovingRange(range);
    mr->setAttribute(attr);
    mr->setZDepth(-90000.0); // Set the z-depth to slightly worse than the selection
    mr->setAttributeOnlyForViews(true);
    m_matchRanges.append(mr);

760
    // Add a match mark
761 762 763
    KTextEditor::MarkInterface* iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
    if (!iface) return;
    iface->setMarkDescription(KTextEditor::MarkInterface::markType32, i18n("SearchHighLight"));
764
    iface->setMarkPixmap(KTextEditor::MarkInterface::markType32, QIcon().pixmap(0,0));
765 766 767 768 769 770
    iface->addMark(line, KTextEditor::MarkInterface::markType32);

    connect(doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)),
            this, SLOT(clearMarks()), Qt::UniqueConnection);
}

771 772 773
void KatePluginSearchView::matchFound(const QString &url, const QString &fName,
                                      const QString &lineContent, int matchLen,
                                      int startLine, int startColumn, int endLine, int endColumn)
Kåre Särs's avatar
Kåre Särs committed
774
{
775
    if (!m_curResults) {
776 777
        return;
    }
778

779 780
    QString pre = lineContent.left(startColumn).toHtmlEscaped();
    QString match = lineContent.mid(startColumn, matchLen).toHtmlEscaped();
Joseph Wenninger's avatar
Joseph Wenninger committed
781
    match.replace(QLatin1Char('\n'), QStringLiteral("\\n"));
782
    QString post = lineContent.mid(startColumn + matchLen).toHtmlEscaped();
Kåre Särs's avatar
Kåre Särs committed
783
    QStringList row;
784
    row << i18n("Line: <b>%1</b>: %2", startLine+1, pre+QStringLiteral("<b>")+match+QStringLiteral("</b>")+post);
785

786 787
    TreeWidgetItem *item = new TreeWidgetItem(rootFileItem(url, fName), row);
    item->setData(0, ReplaceMatches::FileUrlRole, url);
788
    item->setData(0, Qt::ToolTipRole, url);