forked from pbek/qmarkdowntextedit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qplaintexteditsearchwidget.cpp
490 lines (405 loc) · 15.6 KB
/
qplaintexteditsearchwidget.cpp
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
/*
* Copyright (c) 2014-2023 Patrizio Bekerle -- <[email protected]>
*
* 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; version 2 of the License.
*
* 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.
*
*/
#include "qplaintexteditsearchwidget.h"
#include <QDebug>
#include <QEvent>
#include <QKeyEvent>
#include "ui_qplaintexteditsearchwidget.h"
QPlainTextEditSearchWidget::QPlainTextEditSearchWidget(QPlainTextEdit *parent)
: QWidget(parent),
ui(new Ui::QPlainTextEditSearchWidget),
selectionColor(0, 180, 0, 100) {
ui->setupUi(this);
_textEdit = parent;
_darkMode = false;
hide();
ui->searchCountLabel->setStyleSheet(QStringLiteral("* {color: grey}"));
// hiding will leave a open space in the horizontal layout
ui->searchCountLabel->setEnabled(false);
_currentSearchResult = 0;
_searchResultCount = 0;
connect(ui->closeButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::deactivate);
connect(ui->searchLineEdit, &QLineEdit::textChanged, this,
&QPlainTextEditSearchWidget::searchLineEditTextChanged);
connect(ui->searchDownButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchDown);
connect(ui->searchUpButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doSearchUp);
connect(ui->replaceToggleButton, &QPushButton::toggled, this,
&QPlainTextEditSearchWidget::setReplaceMode);
connect(ui->replaceButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplace);
connect(ui->replaceAllButton, &QPushButton::clicked, this,
&QPlainTextEditSearchWidget::doReplaceAll);
connect(&_debounceTimer, &QTimer::timeout,
this, &QPlainTextEditSearchWidget::performSearch);
installEventFilter(this);
ui->searchLineEdit->installEventFilter(this);
ui->replaceLineEdit->installEventFilter(this);
#ifdef Q_OS_MAC
// set the spacing to 8 for OS X
layout()->setSpacing(8);
ui->buttonFrame->layout()->setSpacing(9);
// set the margin to 0 for the top buttons for OS X
QString buttonStyle = QStringLiteral("QPushButton {margin: 0}");
ui->closeButton->setStyleSheet(buttonStyle);
ui->searchDownButton->setStyleSheet(buttonStyle);
ui->searchUpButton->setStyleSheet(buttonStyle);
ui->replaceToggleButton->setStyleSheet(buttonStyle);
ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);
#endif
}
QPlainTextEditSearchWidget::~QPlainTextEditSearchWidget() { delete ui; }
void QPlainTextEditSearchWidget::activate() { activate(true); }
void QPlainTextEditSearchWidget::activateReplace() {
// replacing is prohibited if the text edit is readonly
if (_textEdit->isReadOnly()) {
return;
}
ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());
ui->searchLineEdit->selectAll();
activate();
setReplaceMode(true);
}
void QPlainTextEditSearchWidget::deactivate() {
stopDebounce();
hide();
// Clear the search extra selections when closing the search bar
clearSearchExtraSelections();
_textEdit->setFocus();
}
void QPlainTextEditSearchWidget::setReplaceMode(bool enabled) {
ui->replaceToggleButton->setChecked(enabled);
ui->replaceLabel->setVisible(enabled);
ui->replaceLineEdit->setVisible(enabled);
ui->modeLabel->setVisible(enabled);
ui->buttonFrame->setVisible(enabled);
ui->matchCaseSensitiveButton->setVisible(enabled);
}
bool QPlainTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) {
if (event->type() == QEvent::KeyPress) {
auto *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Escape) {
deactivate();
return true;
} else if ((!_debounceTimer.isActive() &&
keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&
(keyEvent->key() == Qt::Key_Return)) ||
(keyEvent->key() == Qt::Key_Up)) {
doSearchUp();
return true;
} else if (!_debounceTimer.isActive() &&
((keyEvent->key() == Qt::Key_Return) ||
(keyEvent->key() == Qt::Key_Down))) {
doSearchDown();
return true;
} else if (!_debounceTimer.isActive() && keyEvent->key() == Qt::Key_F3) {
doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));
return true;
}
// if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==
// Qt::Key_Tab)
// && ui->replaceToggleButton->isChecked()) {
// ui->replaceLineEdit->setFocus();
// }
return false;
}
return QWidget::eventFilter(obj, event);
}
void QPlainTextEditSearchWidget::searchLineEditTextChanged(
const QString &arg1) {
_searchTerm = arg1;
if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {
_debounceTimer.start();
ui->searchDownButton->setEnabled(false);
ui->searchUpButton->setEnabled(false);
} else {
performSearch();
}
}
void QPlainTextEditSearchWidget::performSearch()
{
doSearchCount();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::clearSearchExtraSelections() {
_searchExtraSelections.clear();
setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::updateSearchExtraSelections() {
_searchExtraSelections.clear();
const auto textCursor = _textEdit->textCursor();
_textEdit->moveCursor(QTextCursor::Start);
const QColor color = selectionColor;
QTextCharFormat extraFmt;
extraFmt.setBackground(color);
int findCounter = 0;
const int searchMode = ui->modeComboBox->currentIndex();
while (doSearch(true, false, false)) {
findCounter++;
// prevent infinite loops from regular expression searches like "$", "^" or "\b"
if (searchMode == RegularExpressionMode && findCounter >= 10000) {
break;
}
QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();
extra.format = extraFmt;
extra.cursor = _textEdit->textCursor();
_searchExtraSelections.append(extra);
}
_textEdit->setTextCursor(textCursor);
this->setSearchExtraSelections();
}
void QPlainTextEditSearchWidget::setSearchExtraSelections() const {
this->_textEdit->setExtraSelections(this->_searchExtraSelections);
}
void QPlainTextEditSearchWidget::stopDebounce()
{
_debounceTimer.stop();
ui->searchDownButton->setEnabled(true);
ui->searchUpButton->setEnabled(true);
}
void QPlainTextEditSearchWidget::doSearchUp() { doSearch(false); }
void QPlainTextEditSearchWidget::doSearchDown() { doSearch(true); }
bool QPlainTextEditSearchWidget::doReplace(bool forAll) {
if (_textEdit->isReadOnly()) {
return false;
}
QTextCursor cursor = _textEdit->textCursor();
if (!forAll && cursor.selectedText().isEmpty()) {
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
if (searchMode == RegularExpressionMode) {
QString text = cursor.selectedText();
text.replace(QRegularExpression(ui->searchLineEdit->text()),
ui->replaceLineEdit->text());
cursor.insertText(text);
} else {
cursor.insertText(ui->replaceLineEdit->text());
}
if (!forAll) {
const int position = cursor.position();
if (!doSearch(true)) {
// restore the last cursor position if text wasn't found any more
cursor.setPosition(position);
_textEdit->setTextCursor(cursor);
}
}
return true;
}
void QPlainTextEditSearchWidget::doReplaceAll() {
if (_textEdit->isReadOnly()) {
return;
}
// start at the top
_textEdit->moveCursor(QTextCursor::Start);
// replace until everything to the bottom is replaced
while (doSearch(true, false) && doReplace(true)) {
}
}
/**
* @brief Searches for text in the text edit
* @returns true if found
*/
bool QPlainTextEditSearchWidget::doSearch(bool searchDown,
bool allowRestartAtTop,
bool updateUI) {
if (_debounceTimer.isActive()) {
stopDebounce();
}
const QString text = ui->searchLineEdit->text();
if (text.isEmpty()) {
if (updateUI) {
ui->searchLineEdit->setStyleSheet(QLatin1String(""));
}
return false;
}
const int searchMode = ui->modeComboBox->currentIndex();
const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();
QFlags<QTextDocument::FindFlag> options =
searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;
if (searchMode == WholeWordsMode) {
options |= QTextDocument::FindWholeWords;
}
if (caseSensitive) {
options |= QTextDocument::FindCaseSensitively;
}
// block signal to reduce too many signals being fired and too many updates
_textEdit->blockSignals(true);
bool found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
_textEdit->blockSignals(false);
if (found) {
const int result =
searchDown ? ++_currentSearchResult : --_currentSearchResult;
_currentSearchResult = std::min(result, _searchResultCount);
updateSearchCountLabelText();
}
// start at the top (or bottom) if not found
if (!found && allowRestartAtTop) {
_textEdit->moveCursor(searchDown ? QTextCursor::Start
: QTextCursor::End);
found =
searchMode == RegularExpressionMode
?
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
_textEdit->find(
QRegularExpression(
text, caseSensitive
? QRegularExpression::NoPatternOption
: QRegularExpression::CaseInsensitiveOption),
options)
:
#else
_textEdit->find(
QRegExp(text, caseSensitive ? Qt::CaseSensitive
: Qt::CaseInsensitive),
options)
:
#endif
_textEdit->find(text, options);
if (found && updateUI) {
_currentSearchResult = searchDown ? 1 : _searchResultCount;
updateSearchCountLabelText();
}
}
if (updateUI) {
const QRect rect = _textEdit->cursorRect();
QMargins margins = _textEdit->layout()->contentsMargins();
const int searchWidgetHotArea = _textEdit->height() - this->height();
const int marginBottom =
(rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;
// move the search box a bit up if we would block the search result
if (margins.bottom() != marginBottom) {
margins.setBottom(marginBottom);
_textEdit->layout()->setContentsMargins(margins);
}
// add a background color according if we found the text or not
const QString bgColorCode =
_darkMode
? (found ? QStringLiteral("#135a13")
: QStringLiteral("#8d2b36"))
: found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB");
const QString fgColorCode =
_darkMode ? QStringLiteral("#cccccc") : QStringLiteral("#404040");
ui->searchLineEdit->setStyleSheet(
QStringLiteral("* { background: ") + bgColorCode +
QStringLiteral("; color: ") + fgColorCode + QStringLiteral("; }"));
// restore the search extra selections after the find command
this->setSearchExtraSelections();
}
return found;
}
/**
* @brief Counts the search results
*/
void QPlainTextEditSearchWidget::doSearchCount() {
// Note that we are moving the anchor, so the search will start from the top
// again! Alternative: Restore cursor position afterward, but then we will
// not know
// at what _currentSearchResult we currently are
_textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);
bool found;
_searchResultCount = 0;
_currentSearchResult = 0;
const int searchMode = ui->modeComboBox->currentIndex();
do {
found = doSearch(true, false, false);
if (found) {
_searchResultCount++;
}
// prevent infinite loops from regular expression searches like "$", "^" or "\b"
if (searchMode == RegularExpressionMode && _searchResultCount >= 10000) {
break;
}
} while (found);
updateSearchCountLabelText();
}
void QPlainTextEditSearchWidget::setDarkMode(bool enabled) {
_darkMode = enabled;
}
void QPlainTextEditSearchWidget::setSearchText(const QString &searchText) {
ui->searchLineEdit->setText(searchText);
}
void QPlainTextEditSearchWidget::setSearchMode(SearchMode searchMode) {
ui->modeComboBox->setCurrentIndex(searchMode);
}
void QPlainTextEditSearchWidget::setDebounceDelay(uint debounceDelay)
{
_debounceTimer.setInterval(static_cast<int>(debounceDelay));
}
void QPlainTextEditSearchWidget::activate(bool focus) {
setReplaceMode(ui->modeComboBox->currentIndex() !=
SearchMode::PlainTextMode);
show();
// preset the selected text as search text if there is any and there is no
// other search text
const QString selectedText = _textEdit->textCursor().selectedText();
if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {
ui->searchLineEdit->setText(selectedText);
}
if (focus) {
ui->searchLineEdit->setFocus();
}
ui->searchLineEdit->selectAll();
updateSearchExtraSelections();
doSearchDown();
}
void QPlainTextEditSearchWidget::reset() {
ui->searchLineEdit->clear();
setSearchMode(SearchMode::PlainTextMode);
setReplaceMode(false);
ui->searchCountLabel->setEnabled(false);
}
void QPlainTextEditSearchWidget::updateSearchCountLabelText() {
ui->searchCountLabel->setEnabled(true);
ui->searchCountLabel->setText(QStringLiteral("%1/%2").arg(
_currentSearchResult == 0 ? QChar('-')
: QString::number(_currentSearchResult),
_searchResultCount == 0 ? QChar('-')
: QString::number(_searchResultCount)));
}
void QPlainTextEditSearchWidget::setSearchSelectionColor(const QColor &color) {
selectionColor = color;
}
void QPlainTextEditSearchWidget::on_modeComboBox_currentIndexChanged(
int index) {
Q_UNUSED(index)
doSearchCount();
doSearchDown();
}
void QPlainTextEditSearchWidget::on_matchCaseSensitiveButton_toggled(
bool checked) {
Q_UNUSED(checked)
doSearchCount();
doSearchDown();
}