plugin_search.cpp 66.4 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 46
#include <kiconloader.h>

#include <KXMLGUIFactory>
#include <KConfigGroup>
47

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

static QUrl localFileDirUp (const QUrl &url)
{
    if (!url.isLocalFile())
        return url;
    
    // else go up
    return QUrl::fromLocalFile (QFileInfo (url.toLocalFile()).dir().absolutePath());
}
65 66 67 68 69 70 71 72 73 74 75 76

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;

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

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

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:
    bool operator<(const QTreeWidgetItem &other)const {
91
        if (childCount() == 0) {
92 93 94 95
            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();
96 97 98 99 100 101 102 103
            if (line < oLine) {
                return true;
            }
            if ((line == oLine) && (column < oColumn)) {
                return true;
            }
            return false;
        }
104 105
        int sepCount = data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
        int oSepCount = other.data(0, ReplaceMatches::FileUrlRole).toString().count(QDir::separator());
106 107
        if (sepCount < oSepCount) return true;
        if (sepCount > oSepCount) return false;
108
        return data(0, ReplaceMatches::FileUrlRole).toString().toLower() < other.data(0, ReplaceMatches::FileUrlRole).toString().toLower();
109 110 111
    }
};

112 113 114
Results::Results(QWidget *parent): QWidget(parent), matches(0)
{
    setupUi(this);
115

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


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

KatePluginSearch::KatePluginSearch(QObject* parent, const QList<QVariant>&)
123
    : KTextEditor::Plugin (parent),
124
    m_searchCommand(0)
Kåre Särs's avatar
Kåre Särs committed
125
{
126 127
    // FIXME KF5
    //KGlobal::locale()->insertCatalog("katesearch");
128

129
    m_searchCommand = new KateSearchCommand(this);
Kåre Särs's avatar
Kåre Särs committed
130 131 132 133
}

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

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

146
    return view;
Kåre Särs's avatar
Kåre Särs committed
147 148 149
}


150
bool ContainerWidget::focusNextPrevChild (bool next)
151
{
152 153 154
    QWidget* fw = focusWidget();
    bool found = false;
    emit nextFocus(fw, &found, next);
155

156 157 158 159
    if (found) {
        return true;
    }
    return QWidget::focusNextPrevChild(next);
160 161
}

162
void KatePluginSearchView::nextFocus(QWidget *currentWidget, bool *found, bool next)
163
{
164 165 166 167 168 169
    *found = false;

    if (!currentWidget) {
        return;
    }

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

219
KatePluginSearchView::KatePluginSearchView(KTextEditor::Plugin *plugin, KTextEditor::MainWindow *mainWin, KTextEditor::Application* application)
220
: QObject (mainWin),
221
m_kateApp(application),
222
m_curResults(0),
223
m_searchJustOpened(false),
224
m_switchToProjectModeWhenAvailable(false),
225 226
m_searchDiskFilesDone(true),
m_searchOpenFilesDone(true),
227 228
m_projectPluginView(0),
m_mainWindow (mainWin)
Kåre Särs's avatar
Kåre Särs committed
229
{
Joseph Wenninger's avatar
Joseph Wenninger committed
230 231
    KXMLGUIClient::setComponentName (QStringLiteral("katesearch"), i18n ("Kate Search & Replace"));
    setXMLFile( QStringLiteral("ui.rc") );
232
  
Joseph Wenninger's avatar
Joseph Wenninger committed
233
    m_toolView = mainWin->createToolView (plugin, QStringLiteral("kate_plugin_katesearch"),
234
                                          KTextEditor::MainWindow::Bottom,
Joseph Wenninger's avatar
Joseph Wenninger committed
235
                                          SmallIcon(QStringLiteral("edit-find")),
236 237
                                          i18n("Search and Replace"));

238
    ContainerWidget *container = new ContainerWidget(m_toolView);
239
    m_ui.setupUi(container);
Kåre Särs's avatar
Kåre Särs committed
240
    container->setFocusProxy(m_ui.searchCombo);
241
    connect(container, SIGNAL(nextFocus(QWidget*,bool*,bool)), this, SLOT(nextFocus(QWidget*,bool*,bool)));
242

Joseph Wenninger's avatar
Joseph Wenninger committed
243
    QAction *a = actionCollection()->addAction(QStringLiteral("search_in_files"));
Kåre Särs's avatar
Kåre Särs committed
244
    a->setText(i18n("Search in Files"));
245
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
246

Joseph Wenninger's avatar
Joseph Wenninger committed
247
    a = actionCollection()->addAction(QStringLiteral("search_in_files_new_tab"));
248 249
    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
250
    connect(a, SIGNAL(triggered(bool)), this, SLOT(addTab()));
251
    connect(a, SIGNAL(triggered(bool)), this, SLOT(openSearchView()));
252

Joseph Wenninger's avatar
Joseph Wenninger committed
253
    a = actionCollection()->addAction(QStringLiteral("go_to_next_match"));
254 255 256
    a->setText(i18n("Go to Next Match"));
    connect(a, SIGNAL(triggered(bool)), this, SLOT(goToNextMatch()));

Joseph Wenninger's avatar
Joseph Wenninger committed
257
    a = actionCollection()->addAction(QStringLiteral("go_to_prev_match"));
258 259 260
    a->setText(i18n("Go to Previous Match"));
    connect(a, SIGNAL(triggered(bool)), this, SLOT(goToPreviousMatch()));

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

Joseph Wenninger's avatar
Joseph Wenninger committed
264 265 266 267 268 269 270 271
    m_ui.displayOptions->setIcon(SmallIcon(QStringLiteral("arrow-down-double")));
    m_ui.searchButton->setIcon(SmallIcon(QStringLiteral("edit-find")));
    m_ui.stopButton->setIcon(SmallIcon(QStringLiteral("process-stop")));
    m_ui.searchPlaceCombo->setItemIcon(0, SmallIcon(QStringLiteral("text-plain")));
    m_ui.searchPlaceCombo->setItemIcon(1, SmallIcon(QStringLiteral("folder")));
    m_ui.folderUpButton->setIcon(SmallIcon(QStringLiteral("go-up")));
    m_ui.currentFolderButton->setIcon(SmallIcon(QStringLiteral("view-refresh")));
    m_ui.newTabButton->setIcon(SmallIcon(QStringLiteral("tab-new")));
272

273 274
    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*\""));
275

276 277
    // the order here is important to get the tabBar hidden for only one tab
    addTab();
278
    m_ui.resultTabWidget->tabBar()->hide();
279 280 281 282 283 284 285 286 287 288

    // 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);

289
    connect(m_ui.newTabButton,     SIGNAL(clicked()), this, SLOT(addTab()));
Christoph Cullmann's avatar
Christoph Cullmann committed
290
    connect(m_ui.resultTabWidget,  SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
291
    connect(m_ui.resultTabWidget,  SIGNAL(currentChanged(int)), this, SLOT(resultTabChanged(int)));
292

293
    connect(m_ui.folderUpButton,   SIGNAL(clicked()), this, SLOT(navigateFolderUp()));
294 295
    connect(m_ui.currentFolderButton, SIGNAL(clicked()), this, SLOT(setCurrentFolder()));

296 297 298 299
    connect(m_ui.searchCombo,      SIGNAL(editTextChanged(QString)), &m_changeTimer, SLOT(start()));
    connect(m_ui.matchCase,        SIGNAL(stateChanged(int)), &m_changeTimer, SLOT(start()));
    connect(m_ui.useRegExp,        SIGNAL(stateChanged(int)), &m_changeTimer, SLOT(start()));
    m_changeTimer.setInterval(300);
Kåre Särs's avatar
Kåre Särs committed
300
    m_changeTimer.setSingleShot(true);
301 302 303 304 305 306 307 308 309 310
    connect(&m_changeTimer, SIGNAL(timeout()), this, SLOT(startSearchWhileTyping()));

    connect(m_ui.searchCombo,      SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.folderRequester,  SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.filterCombo,      SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.excludeCombo,     SIGNAL(returnPressed()), this, SLOT(startSearch()));
    connect(m_ui.searchButton,     SIGNAL(clicked()),       this, SLOT(startSearch()));

    connect(m_ui.displayOptions,   SIGNAL(toggled(bool)), this, SLOT(toggleOptions(bool)));
    connect(m_ui.searchPlaceCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(searchPlaceChanged()));
311

312
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchOpenFiles, SLOT(cancelSearch()));
313 314
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_searchDiskFiles, SLOT(cancelSearch()));
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_folderFilesList, SLOT(cancelSearch()));
315
    connect(m_ui.stopButton,       SIGNAL(clicked()), &m_replacer,        SLOT(cancelReplace()));
316

317 318 319 320 321 322 323 324
    connect(m_ui.nextButton,       SIGNAL(clicked()), this, SLOT(goToNextMatch()));

    connect(m_ui.replaceButton,     SIGNAL(clicked(bool)),   this, SLOT(replaceSingleMatch()));
    connect(m_ui.replaceCheckedBtn, SIGNAL(clicked(bool)),   this, SLOT(replaceChecked()));
    connect(m_ui.replaceCombo,      SIGNAL(returnPressed()), this, SLOT(replaceChecked()));



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

327 328
    connect(&m_searchOpenFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
Kåre Särs's avatar
Kåre Särs committed
329
    connect(&m_searchOpenFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
330
    connect(&m_searchOpenFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
Kåre Särs's avatar
Kåre Särs committed
331

332
    connect(&m_folderFilesList, SIGNAL(finished()),  this, SLOT(folderFileListChanged()));
333

334 335
    connect(&m_searchDiskFiles, SIGNAL(matchFound(QString,QString,int,int,QString,int)),
            this,                 SLOT(matchFound(QString,QString,int,int,QString,int)));
336
    connect(&m_searchDiskFiles, SIGNAL(searchDone()),  this, SLOT(searchDone()));
337
    connect(&m_searchDiskFiles, SIGNAL(searching(QString)), this, SLOT(searching(QString)));
338

339
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
340
            &m_searchOpenFiles, SLOT(cancelSearch()));
341

342
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
343 344
            &m_replacer, SLOT(cancelReplace()));

345
    connect(m_kateApp, SIGNAL(documentWillBeDeleted(KTextEditor::Document*)),
346 347
            this, SLOT(clearDocMarks(KTextEditor::Document*)));

348 349 350
    connect(&m_replacer, SIGNAL(matchReplaced(KTextEditor::Document*,int,int,int)),
            this, SLOT(addMatchMark(KTextEditor::Document*,int,int,int)));

351 352 353 354 355
    // Hook into line edit context menus
    m_ui.searchCombo->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_ui.searchCombo, SIGNAL(customContextMenuRequested(QPoint)), this,
            SLOT(searchContextMenu(QPoint)));

356
    connect(m_mainWindow, SIGNAL(unhandledShortcutOverride(QEvent*)),
357 358
            this, SLOT(handleEsc(QEvent*)));

359
    // watch for project plugin view creation/deletion
Christoph Cullmann's avatar
Christoph Cullmann committed
360 361
    connect(m_mainWindow, SIGNAL(pluginViewCreated (const QString &, QObject *))
        , this, SLOT(slotPluginViewCreated (const QString &, QObject *)));
362

Christoph Cullmann's avatar
Christoph Cullmann committed
363 364
    connect(m_mainWindow, SIGNAL(pluginViewDeleted (const QString &, QObject *))
        , this, SLOT(slotPluginViewDeleted (const QString &, QObject *)));
365

Christoph Cullmann's avatar
Christoph Cullmann committed
366
    connect(m_mainWindow, SIGNAL(viewChanged(KTextEditor::View *)), this, SLOT(docViewChanged()));
367 368


369
    // update once project plugin state manually
Joseph Wenninger's avatar
Joseph Wenninger committed
370
    m_projectPluginView = m_mainWindow->pluginView (QStringLiteral("kateprojectplugin"));
371 372
    slotProjectFileNameChanged ();

373
    m_replacer.setDocumentManager(m_kateApp);
374
    connect(&m_replacer, SIGNAL(replaceDone()), this, SLOT(replaceDone()));
375

376 377
    searchPlaceChanged();

378 379
    m_toolView->installEventFilter(this);

380
    m_mainWindow->guiFactory()->addClient(this);
Kåre Särs's avatar
Kåre Särs committed
381 382 383 384
}

KatePluginSearchView::~KatePluginSearchView()
{
385 386
    clearMarks();

387
    m_mainWindow->guiFactory()->removeClient(this);
388
    delete m_toolView;
Kåre Särs's avatar
Kåre Särs committed
389 390
}

391
void KatePluginSearchView::navigateFolderUp()
392 393
{
    // navigate one folder up
394
    m_ui.folderRequester->setUrl(localFileDirUp (m_ui.folderRequester->url()));
395 396
}

397 398
void KatePluginSearchView::setCurrentFolder()
{
399
    if (!m_mainWindow) {
400 401
        return;
    }
402
    KTextEditor::View* editView = m_mainWindow->activeView();
403 404
    if (editView && editView->document()) {
        // upUrl as we want the folder not the file
405
        m_ui.folderRequester->setUrl(localFileDirUp (editView->document()->url()));
406 407 408
    }
}

409 410 411 412 413 414 415 416 417 418 419 420

QString KatePluginSearchView::currentWord(const KTextEditor::Document& document, const KTextEditor::Cursor& cursor ) const
{
    QString textLine = document.line(cursor.line());

    int len = textLine.length();

    if (cursor.column() > len) {       // Probably because of non-wrapping cursor mode.
        return QString();
    }

    int start = cursor.column();
421
    for(int currPos = cursor.column()-1; currPos >= 0; currPos--) {
422
        if (textLine.at(currPos).isLetterOrNumber() || (textLine[currPos]==QLatin1Char('_')) || (textLine[currPos]==QLatin1Char('~'))) {
423 424 425 426 427 428 429 430 431
            start = currPos;
        }
        else {
            break;
        }
    }

    int end = cursor.column();
    while (end < len && (textLine.at(end).isLetterOrNumber()
432
                     || (textLine[end]==QLatin1Char('_')) || (textLine[end]==QLatin1Char('~')))) {
433 434 435 436 437 438
        end++;
    }

    return textLine.mid(start, (end - start));
}

439
void KatePluginSearchView::openSearchView()
Kåre Särs's avatar
Kåre Särs committed
440
{
441
    if (!m_mainWindow) {
Kåre Särs's avatar
Kåre Särs committed
442 443 444
        return;
    }
    if (!m_toolView->isVisible()) {
445
        m_mainWindow->showToolView(m_toolView);
446
    }
447
    m_ui.searchCombo->setFocus(Qt::OtherFocusReason);
448
    m_ui.displayOptions->setChecked(true);
449

450
    KTextEditor::View* editView = m_mainWindow->activeView();
451
    if (editView && editView->document()) {
452
        if (m_ui.folderRequester->text().isEmpty()) {
453
            // upUrl as we want the folder not the file
454
            m_ui.folderRequester->setUrl(localFileDirUp (editView->document()->url()));
455
        }
456
        QString selection;
457
        if (editView->selection()) {
458
            selection = editView->selectionText();
459
            // remove possible trailing '\n'
460
            if (selection.endsWith(QLatin1Char('\n'))) {
461 462
                selection = selection.left(selection.size() -1);
            }
463
        }
464 465 466 467
        if (selection.isEmpty()) {
            selection = currentWord(*editView->document(), editView->cursorPosition());
        }

468
        if (!selection.isEmpty() && !selection.contains(QLatin1Char('\n'))) {
469 470 471 472 473
            m_ui.searchCombo->blockSignals(true);
            m_ui.searchCombo->lineEdit()->setText(selection);
            m_ui.searchCombo->blockSignals(false);
        }

474 475
        m_ui.searchCombo->lineEdit()->selectAll();
        m_searchJustOpened = true;
476
        startSearchWhileTyping();
Kåre Särs's avatar
Kåre Särs committed
477 478 479
    }
}

480 481
void KatePluginSearchView::handleEsc(QEvent *e)
{
482
    if (!m_mainWindow) return;
483 484 485 486 487

    QKeyEvent *k = static_cast<QKeyEvent *>(e);
    if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) {

        if (m_toolView->isVisible()) {
488
            m_mainWindow->hideToolView(m_toolView);
489 490 491 492 493 494 495
        }
        else {
            clearMarks();
        }
    }
}

496 497 498 499 500
void KatePluginSearchView::setSearchString(const QString &pattern)
{
    m_ui.searchCombo->lineEdit()->setText(pattern);
}

501 502 503 504 505 506 507 508 509
void KatePluginSearchView::toggleOptions(bool show)
{
    m_ui.stackedWidget->setCurrentIndex((show) ? 1:0);
}

void KatePluginSearchView::setSearchPlace(int place)
{
    m_ui.searchPlaceCombo->setCurrentIndex(place);
}
510 511 512 513

QStringList KatePluginSearchView::filterFiles(const QStringList& files) const
{
    QString types = m_ui.filterCombo->currentText();
514
    QString excludes = m_ui.excludeCombo->currentText();
Joseph Wenninger's avatar
Joseph Wenninger committed
515
    if (((types.isEmpty() || types == QStringLiteral("*"))) && (excludes.isEmpty())) {
516 517 518 519
        // shortcut for use all files
        return files;
    }

520
    QStringList tmpTypes = types.split(QLatin1Char(','));
521 522 523 524 525 526 527
    QVector<QRegExp> typeList;
    for (int i=0; i<tmpTypes.size(); i++) {
        QRegExp rx(tmpTypes[i]);
        rx.setPatternSyntax(QRegExp::Wildcard);
        typeList << rx;
    }

528
    QStringList tmpExcludes = excludes.split(QLatin1Char(','));
529 530 531 532 533 534 535
    QVector<QRegExp> excludeList;
    for (int i=0; i<tmpExcludes.size(); i++) {
        QRegExp rx(tmpExcludes[i]);
        rx.setPatternSyntax(QRegExp::Wildcard);
        excludeList << rx;
    }

536 537 538
    QStringList filteredFiles;
    foreach (QString fileName, files) {
        bool isInSubDir = fileName.startsWith(m_resultBaseDir);
539
        QString nameToCheck = fileName;
540
        if (isInSubDir) {
541
            nameToCheck = fileName.mid(m_resultBaseDir.size());
542 543
        }

544 545 546 547 548 549 550 551 552 553 554 555
        bool skip = false;
        for (int i=0; i<excludeList.size(); i++) {
            if (excludeList[i].exactMatch(nameToCheck)) {
                skip = true;
                break;
            }
        }
        if (skip) {
            continue;
        }


556
        for (int i=0; i<typeList.size(); i++) {
557
            if (typeList[i].exactMatch(nameToCheck)) {
558 559 560 561 562 563 564 565
                filteredFiles << fileName;
                break;
            }
        }
    }
    return filteredFiles;
}

566
void KatePluginSearchView::folderFileListChanged()
Kåre Särs's avatar
Kåre Särs committed
567
{
568 569
    m_searchDiskFilesDone = false;
    m_searchOpenFilesDone = false;
570

571
    if (!m_curResults) {
572
        qWarning() << "This is a bug";
573 574 575
        m_searchDiskFilesDone = true;
        m_searchOpenFilesDone = true;
        searchDone();
576 577
        return;
    }
578
    QStringList fileList = m_folderFilesList.fileList();
579

580
    QList<KTextEditor::Document*> openList;
581 582
    for (int i=0; i<m_kateApp->documents().size(); i++) {
        int index = fileList.indexOf(m_kateApp->documents()[i]->url().toString());
583
        if (index != -1) {
584
            openList << m_kateApp->documents()[i];
585 586
            fileList.removeAt(index);
        }
Kåre Särs's avatar
Kåre Särs committed
587
    }
588 589 590 591 592 593

    // 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);
594 595
    }
    else {
596
        m_searchOpenFilesDone = true;
Kåre Särs's avatar
Kåre Särs committed
597 598
    }

599
    m_searchDiskFiles.startSearch(fileList, m_curResults->regExp);
Kåre Särs's avatar
Kåre Särs committed
600 601
}

602

Kåre Särs's avatar
Kåre Särs committed
603 604
void KatePluginSearchView::searchPlaceChanged()
{
605
    m_ui.displayOptions->setChecked(true);
606

607 608 609 610 611
    const bool inFolder = (m_ui.searchPlaceCombo->currentIndex() == 1);
    const bool inProject = (m_ui.searchPlaceCombo->currentIndex() == 2);

    m_ui.filterCombo->setEnabled(inFolder || inProject);

612
    m_ui.excludeCombo->setEnabled(inFolder || inProject);
613 614 615 616 617 618 619 620 621 622 623 624
    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);

    // ... 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());
Kåre Särs's avatar
Kåre Särs committed
625 626
}

627
void KatePluginSearchView::addHeaderItem()
628
{
629
    QTreeWidgetItem *item = new QTreeWidgetItem(m_curResults->tree, QStringList());
630 631
    item->setCheckState(0, Qt::Checked);
    item->setFlags(item->flags() | Qt::ItemIsTristate);
632
    m_curResults->tree->expandItem(item);
633 634
}

635
QTreeWidgetItem * KatePluginSearchView::rootFileItem(const QString &url, const QString &fName)
636
{
637
    if (!m_curResults) {
638 639 640
        return 0;
    }

641
    // FIXME KF5
642
    QUrl kurl = QUrl::fromUserInput(url);
643
    QString path = kurl.isLocalFile() ? localFileDirUp (kurl).path() : kurl.url();
644
    path.replace(m_resultBaseDir, QString());
645
    QString name = kurl.fileName();
646 647 648
    if (url.isEmpty()) {
        name = fName;
    }
649

650
    // make sure we have a root item
651
    if (m_curResults->tree->topLevelItemCount() == 0) {
652
        addHeaderItem();
653 654 655
    }
    QTreeWidgetItem *root = m_curResults->tree->topLevelItem(0);

656 657 658
    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
659 660 661
        return root;
    }

662
    for (int i=0; i<root->childCount(); i++) {
663
        //qDebug() << root->child(i)->data(0, ReplaceMatches::FileNameRole).toString() << fName;
664 665 666
        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;
667
            QString tmpUrl = QString::fromLatin1("%1<b>%2</b>: <b>%3</b>").arg(path).arg(name).arg(matches);
668
            root->child(i)->setData(0, Qt::DisplayRole, tmpUrl);
669
            root->child(i)->setData(0, ReplaceMatches::LineRole, matches);
670
            return root->child(i);
671 672
        }
    }
673

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

677
    TreeWidgetItem *item = new TreeWidgetItem(root, QStringList(tmpUrl));
678 679 680
    item->setData(0, ReplaceMatches::FileUrlRole, url);
    item->setData(0, ReplaceMatches::FileNameRole, fName);
    item->setData(0, ReplaceMatches::LineRole, 1);
681
    item->setCheckState(0, Qt::Checked);
682
    item->setFlags(item->flags() | Qt::ItemIsTristate);
683 684 685
    return item;
}

686 687 688 689 690
void KatePluginSearchView::addMatchMark(KTextEditor::Document* doc, int line, int column, int matchLen)
{
    if (!doc) return;

    KTextEditor::MovingInterface* miface = qobject_cast<KTextEditor::MovingInterface*>(doc);
691
    KTextEditor::ConfigInterface* ciface = qobject_cast<KTextEditor::ConfigInterface*>(m_mainWindow->activeView());
692
    KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute());
693 694 695

    bool replace = ((sender() == &m_replacer) || (sender() == 0) || (sender() == m_ui.replaceButton));
    if (replace) {
696
        QColor replaceColor(Qt::green);
Joseph Wenninger's avatar
Joseph Wenninger committed
697
        if (ciface) replaceColor = ciface->configValue(QStringLiteral("replace-highlight-color")).value<QColor>();
698
        attr->setBackground(replaceColor);
699 700
    }
    else {
701
        QColor searchColor(Qt::yellow);
Joseph Wenninger's avatar
Joseph Wenninger committed
702
        if (ciface) searchColor = ciface->configValue(QStringLiteral("search-highlight-color")).value<QColor>();
703
        attr->setBackground(searchColor);
704
    }
705 706 707 708 709 710 711 712
    // calculate end line in case of multi-line match
    int endLine = line;
    int endColumn = column+matchLen;
    while ((endLine < doc->lines()) &&  (endColumn > doc->line(endLine).size())) {
        endColumn -= doc->line(endLine).size();
        endColumn--; // remove one for '\n'
        endLine++;
    }
713

714
    KTextEditor::Range range(line, column, endLine, endColumn);
715

716
    if (m_curResults && !replace) {
717 718
        // special handling for "(?=\\n)" in multi-line search
        QRegExp tmpReg = m_curResults->regExp;
Joseph Wenninger's avatar
Joseph Wenninger committed
719
        if (m_curResults->regExp.pattern().endsWith(QStringLiteral("(?=\\n)"))) {
720
            QString newPatern = tmpReg.pattern();
Joseph Wenninger's avatar
Joseph Wenninger committed
721
            newPatern.replace(QStringLiteral("(?=\\n)"), QStringLiteral("$"));
722 723 724 725
            tmpReg.setPattern(newPatern);
        }

        if (tmpReg.indexIn(doc->text(range)) != 0) {
726
            qDebug() << doc->text(range) << "Does not match" << m_curResults->regExp.pattern();
727 728 729 730
            return;
        }
    }

731 732 733 734 735 736 737 738 739 740
    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);

    KTextEditor::MarkInterface* iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
    if (!iface) return;
    iface->setMarkDescription(KTextEditor::MarkInterface::markType32, i18n("SearchHighLight"));
    iface->setMarkPixmap(KTextEditor::MarkInterface::markType32,
741
                         QIcon().pixmap(0,0));
742 743 744 745 746 747
    iface->addMark(line, KTextEditor::MarkInterface::markType32);

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

748
void KatePluginSearchView::matchFound(const QString &url, const QString &fName, int line, int column,
749
                                      const QString &lineContent, int matchLen)
Kåre Särs's avatar
Kåre Särs committed
750
{
751
    if (!m_curResults) {
752 753
        return;
    }
754

755 756
    QString pre = lineContent.left(column).toHtmlEscaped();
    QString match = lineContent.mid(column, matchLen).toHtmlEscaped();
Joseph Wenninger's avatar
Joseph Wenninger committed
757
    match.replace(QLatin1Char('\n'), QStringLiteral("\\n"));
758
    QString post = lineContent.mid(column + matchLen).toHtmlEscaped();
Kåre Särs's avatar
Kåre Särs committed
759
    QStringList row;
Joseph Wenninger's avatar
Joseph Wenninger committed
760
    row << i18n("Line: <b>%1</b>: %2", line+1, pre+QStringLiteral("<b>")+match+QStringLiteral("</b>")+post);
761

762 763
    TreeWidgetItem *item = new TreeWidgetItem(rootFileItem(url, fName), row);
    item->setData(0, ReplaceMatches::FileUrlRole, url);
764
    item->setData(0, Qt::ToolTipRole, url);
765 766 767 768 769 770 771
    item->setData(0, ReplaceMatches::FileNameRole, fName);
    item->setData(0, ReplaceMatches::LineRole, line);
    item->setData(0, ReplaceMatches::ColumnRole, column);
    item->setData(0, ReplaceMatches::MatchLenRole, matchLen);
    item->setData(0, ReplaceMatches::PreMatchRole, pre);
    item->setData(0, ReplaceMatches::MatchRole, match);
    item->setData(0, ReplaceMatches::PostMatchRole, post);
772
    item->setCheckState (0, Qt::Checked);
773 774 775

    m_curResults->matches++;

776
    // Add mark if the document is open
777 778 779 780 781
    KTextEditor::Document* doc;
    if (url.isEmpty()) {
        doc = m_replacer.findNamed(fName);
    }
    else {
782
        doc = m_kateApp->findUrl(QUrl::fromUserInput(url));
783
    }
784
    addMatchMark(doc, line, column, matchLen);
785 786 787 788
}

void KatePluginSearchView::clearMarks()
{
789
    // FIXME: check for ongoing search...
790
    KTextEditor::MarkInterface* iface;
791
    foreach (KTextEditor::Document* doc, m_kateApp->documents()) {
792 793 794 795 796 797
        iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
        if (iface) {
            const QHash<int, KTextEditor::Mark*> marks = iface->marks();
            QHashIterator<int, KTextEditor::Mark*> i(marks);
            while (i.hasNext()) {
                i.next();
798 799
                if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                    iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
800 801 802 803 804 805
                }
            }
        }
    }
    qDeleteAll(m_matchRanges);
    m_matchRanges.clear();
Kåre Särs's avatar
Kåre Särs committed
806 807
}

808 809
void KatePluginSearchView::clearDocMarks(KTextEditor::Document* doc)
{
810
    //qDebug() << sender();
811 812 813 814 815 816 817 818
    // FIXME: check for ongoing search...
    KTextEditor::MarkInterface* iface;
    iface = qobject_cast<KTextEditor::MarkInterface*>(doc);
    if (iface) {
        const QHash<int, KTextEditor::Mark*> marks = iface->marks();
        QHashIterator<int, KTextEditor::Mark*> i(marks);
        while (i.hasNext()) {
            i.next();
819 820
            if (i.value()->type & KTextEditor::MarkInterface::markType32) {
                iface->removeMark(i.value()->line, KTextEditor::MarkInterface::markType32);
821 822 823 824 825 826 827
            }
        }
    }

    int i = 0;
    while (i<m_matchRanges.size()) {
        if (m_matchRanges.at(i)->document() == doc) {
828
            //qDebug() << "removing mark in" << doc->url();
829 830 831 832 833 834 835 836 837
            delete m_matchRanges.at(i);
            m_matchRanges.removeAt(i);
        }
        else {
            i++;
        }
    }
}

838 839 840
void KatePluginSearchView::startSearch()
{
    m_changeTimer.stop(); // make sure not to start a "while you type" search now
841
    m_mainWindow->showToolView(m_toolView); // in case we are invoked from the command interface
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    m_switchToProjectModeWhenAvailable = false; // now that we started, don't switch back automatically

    if (m_ui.searchCombo->currentText().isEmpty()) {
        // return pressed in the folder combo or filter combo
        return;
    }
    m_ui.searchCombo->addToHistory(m_ui.searchCombo->currentText());
    if(m_ui.filterCombo->findText(m_ui.filterCombo->currentText()) == -1) {
        m_ui.filterCombo->insertItem(0, m_ui.filterCombo->currentText());
        m_ui.filterCombo->setCurrentIndex(0);
    }
    if(m_ui.excludeCombo->findText(m_ui.excludeCombo->currentText()) == -1) {
        m_ui.excludeCombo->insertItem(0, m_ui.excludeCombo->currentText());
        m_ui.excludeCombo->setCurrentIndex(0);
    }
    m_curResults = qobject_cast<Results *>(m_ui.resultTabWidget->currentWidget());
    if (!m_curResults) {
859
        qWarning() << "This is a bug";
860 861 862 863 864 865 866 867 868 869 870
        return;
    }

    m_ui.newTabButton->setDisabled(true);
    m_ui.searchCombo->setDisabled(true);
    m_ui.searchButton->setDisabled(true);
    m_ui.displayOptions->setChecked (false);
    m_ui.displayOptions->setDisabled(true);
    m_ui.replaceCheckedBtn->setDisabled(true);
    m_ui.replaceButton->setDisabled(true);
    m_ui.nextAndStop->setCurrentIndex(1);
871
    m_ui.replaceCombo->setDisabled(true);
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892


    QRegExp reg(m_ui.searchCombo->currentText(),
                m_ui.matchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive,
                m_ui.useRegExp->isChecked() ? QRegExp::RegExp : QRegExp::FixedString);
    m_curResults->regExp = reg;

    clearMarks();
    m_curResults->tree->clear();
    m_curResults->matches = 0;

    m_ui.resultTabWidget->setTabText(m_ui.resultTabWidget->currentIndex(),
                                     m_ui.searchCombo->currentText());

    m_toolView->setCursor(Qt::WaitCursor);
    m_searchDiskFilesDone = false;
    m_searchOpenFilesDone = false;

    if (m_ui.searchPlaceCombo->currentIndex() ==  0) {
        m_searchDiskFilesDone = true;
        m_resultBaseDir.clear();
893
        const QList<KTextEditor::Document*> documents = m_kateApp->documents();
894
        addHeaderItem();