-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqcommandedit.cpp
519 lines (459 loc) · 13.2 KB
/
qcommandedit.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/* QCommandEdit - a widget for entering commands, with completion and history
* Copyright (C) 2018 Federico Ferri
*
* 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 3 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. If not, see <http://www.gnu.org/licenses/>.
*/
#include "qcommandedit.h"
#include <QApplication>
#include <QTimer>
#include <QTextLayout>
#include <QPainter>
#include <QToolTip>
QCommandEdit::QCommandEdit(QWidget *parent)
: QLineEdit(parent),
showMatchingHistory_(false),
autoAcceptLongestCommonCompletionPrefix_(true)
{
historyState_.reset();
completionState_.reset();
connect(this, &QCommandEdit::returnPressed, this, &QCommandEdit::onReturnPressed);
connect(this, &QCommandEdit::escapePressed, this, &QCommandEdit::onEscapePressed);
connect(this, &QCommandEdit::upPressed, this, &QCommandEdit::onUpPressed);
connect(this, &QCommandEdit::downPressed, this, &QCommandEdit::onDownPressed);
connect(this, &QCommandEdit::tabPressed, this, &QCommandEdit::onTabPressed);
connect(this, &QCommandEdit::shiftTabPressed, this, &QCommandEdit::onShiftTabPressed);
connect(this, &QCommandEdit::textEdited, this, &QCommandEdit::onTextEdited);
connect(this, &QCommandEdit::selectionChanged, this, &QCommandEdit::onSelectionChanged);
connect(this, &QCommandEdit::cursorPositionChanged, this, &QCommandEdit::onCursorPositionChanged);
installEventFilter(this);
}
void QCommandEdit::setShowMatchingHistory(bool show)
{
showMatchingHistory_ = show;
if(show)
searchMatchingHistoryAndShowGhost();
}
void QCommandEdit::setAutoAcceptLongestCommonCompletionPrefix(bool accept)
{
autoAcceptLongestCommonCompletionPrefix_ = accept;
}
void QCommandEdit::paintEvent(QPaintEvent *event)
{
QLineEdit::paintEvent(event);
/* show ghost suffix. only shown if:
* - widget has focus
* - cursor is at end
* - there is some text
*/
if(!hasFocus()) return;
if(ghostSuffix_.isEmpty()) return;
QString txt = text();
if(txt.isEmpty()) return;
if(cursorPosition() < txt.length()) return;
ensurePolished();
QRect cr = cursorRect();
QPoint pos = cr.topRight() - QPoint(cr.width() / 2, 0);
QPainter p(this);
p.setPen(QPen(Qt::gray, 1));
QTextLayout l(ghostSuffix_, font());
l.beginLayout();
QTextLine line = l.createLine();
line.setLineWidth(width() - pos.x());
line.setPosition(pos);
l.endLayout();
l.draw(&p, QPoint(0, 0));
}
void QCommandEdit::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Escape)
{
Q_EMIT escapePressed();
return;
}
if(event->key() == Qt::Key_Up)
{
Q_EMIT upPressed();
return;
}
if(event->key() == Qt::Key_Down)
{
Q_EMIT downPressed();
return;
}
QLineEdit::keyPressEvent(event);
}
bool QCommandEdit::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if(keyEvent->key() == Qt::Key_Tab)
{
Q_EMIT tabPressed();
return true;
}
if(keyEvent->key() == Qt::Key_Backtab)
{
Q_EMIT shiftTabPressed();
return true;
}
}
return QLineEdit::eventFilter(obj, event);
}
/*!
* \brief Clear the text and reset history/completion states
*/
void QCommandEdit::clear()
{
setText("");
ghostSuffix_ = "";
historyState_.reset();
completionState_.reset();
setToolTipAtCursor("");
}
/*!
* \brief Replacew the history content
* \param history The new history content
*/
void QCommandEdit::setHistory(const QStringList &history)
{
if(historyState_.index_ != -1)
clear();
historyState_.history_ = history;
historyState_.reset();
}
/*!
* \brief Navigate thru command history
* \param delta 1 to go forward or -1 to go backward
*/
void QCommandEdit::navigateHistory(int delta)
{
if(delta == 0) return;
// clip delta to +1/-1:
delta = (delta < -1 ? -1 : delta > 1 ? 1 : delta);
// compute actual index (-1 => last):
int newIndex = historyState_.index_;
if(newIndex == -1) newIndex = historyState_.history_.length();
if(historyState_.prefixFilter_.isEmpty())
{
// simply navigate up/down
setHistoryIndex(newIndex + delta);
return;
}
// search matching history
while(1)
{
newIndex += delta;
if(newIndex < 0 || newIndex >= historyState_.history_.length())
break;
if(historyState_.history_[newIndex].startsWith(historyState_.prefixFilter_))
{
setHistoryIndex(newIndex);
return;
}
}
if(newIndex >= historyState_.history_.length())
{
// reached history end => go back at the orginal edit state
QString savedFilter = historyState_.prefixFilter_;
setHistoryIndex(newIndex);
historyState_.prefixFilter_ = savedFilter;
}
}
/*!
* \brief Select an entry from command history and write it in the editor
* \param index Index of the history entry
*/
void QCommandEdit::setHistoryIndex(int index)
{
if(index < 0 || index > historyState_.history_.length())
return;
ghostSuffix_ = "";
if(index >= historyState_.history_.length())
{
// going past last item resets the editor to whatever text
// has been entered before beginning history navigation
setText(historyState_.prefixFilter_);
historyState_.reset();
searchMatchingHistoryAndShowGhost();
}
else
{
historyState_.index_ = index;
setText(historyState_.history_[index]);
}
QTimer::singleShot(0, this, &QCommandEdit::moveCursorToEnd);
setToolTipAtCursor("");
}
static QString longestCommonPrefix(const QStringList &strs)
{
QString result;
if(strs.isEmpty()) return result;
result = strs[0];
for(int i = 1; i < strs.size(); i++)
{
for(int j = 0; j < std::min(result.length(), strs[i].length()); j++)
{
if(j == strs[i].length())
{
result = strs[i];
break;
}
if(result.at(j) != strs[i].at(j))
{
result = result.left(j);
break;
}
}
}
return result;
}
/*!
* \brief Insert some text at the cursor position, replacing selection if any
* \param text The text to insert
* \param selected If true, the new text will be selected
*
* After inserting the new text, the cursor poisition will be at end of new text.
* New text will be selected or selection will be empty depending on the
* selected parameter.
*/
void QCommandEdit::insertTextAtCursor(const QString &txt, bool selected)
{
int c = hasSelectedText() ? selectionStart() : cursorPosition();
QString oldText = text();
QString before = oldText.left(c);
QString after = oldText.mid(c + selectedText().length());
QString newText = before + txt + after;
setText(newText);
setCursorPosition(before.length() + txt.length());
if(selected)
setSelection(before.length(), txt.length());
}
/*!
* \brief Set the list of completions for the current cursor position
* \param completion The list of completions
*/
void QCommandEdit::setCompletion(const QStringList &completion)
{
completionState_.completion_ = completion;
if(autoAcceptLongestCommonCompletionPrefix_)
{
QString lcp = longestCommonPrefix(completion);
if(!lcp.isEmpty() && completionState_.requested_)
{
QStringList completionTrimmed;
for(const QString &s : completion)
completionTrimmed << s.mid(lcp.length());
bool oldBlockSignals = blockSignals(true);
insertTextAtCursor(lcp, false);
blockSignals(oldBlockSignals);
completionState_.completion_ = completionTrimmed;
if(completionTrimmed.isEmpty())
{
completionState_.reset();
return;
}
}
}
if(completionState_.requested_)
navigateCompletion(1);
}
/*!
* \brief Reset the completion state
*/
void QCommandEdit::resetCompletion()
{
completionState_.reset();
}
/*!
* \brief Set a proposed completion by inserting a selected text at the cursor
* \param s the completion text to insert
*
* This will insert a proposed completion at the cursor position.
* The completion text will be inserted and selected.
* If there is already some selected text, it will be replaced.
*
* The completion insertion point is the cursor position, of the selection
* start if there is selected text.
*/
void QCommandEdit::setCurrentCompletion(const QString &s)
{
bool oldBlockSignals = blockSignals(true);
insertTextAtCursor(s, true);
blockSignals(oldBlockSignals);
searchMatchingHistoryAndShowGhost();
}
/*!
* \brief Navigate thru completion choices
* \param delta 1 to choose next or -1 to choose previous
*/
void QCommandEdit::navigateCompletion(int delta)
{
if(delta == 0) return;
// clip delta to +1/-1:
delta = (delta < -1 ? -1 : delta > 1 ? 1 : delta);
// compute actual index
int newIndex = completionState_.index_;
newIndex += delta;
if(newIndex < 0 || newIndex >= completionState_.completion_.length())
return;
completionState_.index_ = newIndex;
setCurrentCompletion(completionState_.completion_[newIndex]);
}
/*!
* \brief Accept the currently selected completion choice
*/
void QCommandEdit::acceptCompletion()
{
if(hasSelectedText())
{
QString currentCompletion = selectedText();
cancelCompletion();
int c = cursorPosition();
QString t = text();
setText(t.left(c) + currentCompletion + t.mid(c));
setCursorPosition(c + currentCompletion.length());
completionState_.reset();
searchMatchingHistoryAndShowGhost();
}
}
/*!
* \brief Cancel the completion
*/
void QCommandEdit::cancelCompletion()
{
if(hasSelectedText())
{
setCurrentCompletion("");
completionState_.reset();
}
}
/*!
* \brief Display a tooltip at the cursor position
* \param tip The tooltip text
*/
void QCommandEdit::setToolTipAtCursor(const QString &tip)
{
if(tip.isEmpty())
{
QToolTip::hideText();
}
else
{
setToolTip(tip);
QFontMetrics fm(QToolTip::font());
QRect r = fm.boundingRect(QRect(0, 0, 500, 50), 0, tip);
QPoint cur = mapToGlobal(cursorRect().topLeft());
QHelpEvent *event = new QHelpEvent(QEvent::ToolTip,
QPoint(pos().x(), pos().y()),
QPoint(cur.x(), cur.y() - height() - r.height() - 4));
QApplication::postEvent(this, event);
}
}
/*!
* \brief Move cursor to end of line
*/
void QCommandEdit::moveCursorToEnd()
{
setCursorPosition(text().size());
}
void QCommandEdit::onReturnPressed()
{
if(text().isEmpty()) return;
if(hasSelectedText())
acceptCompletion();
else
Q_EMIT execute(text());
}
void QCommandEdit::onEscapePressed()
{
if(text().isEmpty())
Q_EMIT escape();
if(hasSelectedText())
cancelCompletion();
else
clear();
}
void QCommandEdit::onUpPressed()
{
navigateHistory(-1);
}
void QCommandEdit::onDownPressed()
{
navigateHistory(1);
}
void QCommandEdit::onTabPressed()
{
if(completionState_.completion_.isEmpty())
{
if(completionState_.requested_)
return;
completionState_.requested_ = true;
Q_EMIT askCompletion(text(), cursorPosition());
return;
}
navigateCompletion(1);
}
void QCommandEdit::onShiftTabPressed()
{
navigateCompletion(-1);
}
void QCommandEdit::onSelectionChanged()
{
completionState_.reset();
}
void QCommandEdit::onCursorPositionChanged(int old, int now)
{
Q_UNUSED(old);
Q_UNUSED(now);
completionState_.reset();
}
void QCommandEdit::onTextEdited()
{
resetCompletion();
historyState_.prefixFilter_ = text();
if(cursorPosition() == text().length())
searchMatchingHistoryAndShowGhost();
}
void QCommandEdit::searchMatchingHistoryAndShowGhost()
{
if(!text().isEmpty() && showMatchingHistory_)
{
for(int i = historyState_.history_.length() - 1; i >= 0; --i)
{
if(historyState_.history_[i].startsWith(text()))
{
ghostSuffix_ = historyState_.history_[i].mid(text().length());
repaint();
return;
}
}
}
if(!ghostSuffix_.isEmpty())
{
ghostSuffix_ = "";
repaint();
}
}
void QCommandEdit::HistoryState::reset()
{
index_ = -1;
prefixFilter_ = "";
}
void QCommandEdit::CompletionState::reset()
{
completion_.clear();
requested_ = false;
index_ = -1;
}