forked from hluk/CopyQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitemfakevim.cpp
869 lines (727 loc) · 26.9 KB
/
itemfakevim.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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
/*
Copyright (c) 2020, Lukas Holecek <[email protected]>
This file is part of CopyQ.
CopyQ 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.
CopyQ 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 CopyQ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "itemfakevim.h"
#include "ui_itemfakevimsettings.h"
#include "tests/itemfakevimtests.h"
#include "common/contenttype.h"
#include "fakevim/fakevimhandler.h"
using namespace FakeVim::Internal;
#include <QIcon>
#include <QLabel>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QMessageBox>
#include <QMetaMethod>
#include <QKeyEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QRegularExpression>
#include <QStatusBar>
#include <QTextBlock>
#include <QTextEdit>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QAbstractTextDocumentLayout>
#include <QScrollBar>
#include <QSettings>
#include <QStyle>
#include <QStyleHints>
#include <QtPlugin>
#define EDITOR(s) (m_textEdit ? m_textEdit->s : m_plainTextEdit->s)
namespace {
const char propertyWrapped[] = "CopyQ_fakevim_wrapped";
QLatin1String configReallyEnabled("really_enable");
QLatin1String configSourceFile("source_file");
// The same method for rendering document doesn't work for QPlainTextEdit.
// This is simplified code from Qt source code.
void drawPlainTextDocument(
QPlainTextEdit *textEdit,
const QAbstractTextDocumentLayout::PaintContext context,
QPainter *painter)
{
// WORKAROUND: Access protected members of QPlainTextEdit.
class PlainTextEdit final : public QPlainTextEdit {
public:
static QPointF getContentOffset(QPlainTextEdit *edit) {
return (edit->*(&PlainTextEdit::contentOffset))();
}
static QTextBlock getFirstVisibleBlock(QPlainTextEdit *edit) {
return (edit->*(&PlainTextEdit::firstVisibleBlock))();
}
};
QPointF offset = PlainTextEdit::getContentOffset(textEdit);
QTextBlock block = PlainTextEdit::getFirstVisibleBlock(textEdit);
QTextDocument *doc = textEdit->document();
const auto documentLayout = doc->documentLayout();
painter->setBrushOrigin(offset);
while (block.isValid()) {
const QRectF r = documentLayout->blockBoundingRect(block).translated(offset);
if (block.isVisible()) {
QTextLayout *layout = block.layout();
QVector<QTextLayout::FormatRange> selections;
int blpos = block.position();
int bllen = block.length();
for (int i = 0; i < context.selections.size(); ++i) {
const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
const int selStart = range.cursor.selectionStart() - blpos;
const int selEnd = range.cursor.selectionEnd() - blpos;
if (selStart < bllen && selEnd > 0
&& selEnd > selStart) {
QTextLayout::FormatRange o;
o.start = selStart;
o.length = selEnd - selStart;
o.format = range.format;
selections.append(o);
} else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
&& block.contains(range.cursor.position())) {
// for full width selections we don't require an actual selection, just
// a position to specify the line. that's more convenience in usage.
QTextLayout::FormatRange o;
QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
o.start = l.textStart();
o.length = l.textLength();
if (o.start + o.length == bllen - 1)
++o.length; // include newline
o.format = range.format;
selections.append(o);
}
}
layout->draw(painter, offset, selections);
}
offset.ry() += r.height();
if (offset.y() > context.clip.bottom())
break;
block = block.next();
}
}
class TextEditWrapper final : public QObject
{
public:
explicit TextEditWrapper(QAbstractScrollArea *editor)
: QObject(editor)
, m_textEditWidget(editor)
, m_textEdit(qobject_cast<QTextEdit *>(editor))
, m_plainTextEdit(qobject_cast<QPlainTextEdit *>(editor))
, m_handler(new FakeVimHandler(editor, nullptr))
, m_hasBlockSelection(false)
{
editor->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
if (m_textEdit) {
connect( m_textEdit, &QTextEdit::selectionChanged,
this, &TextEditWrapper::onSelectionChanged );
connect( m_textEdit, &QTextEdit::cursorPositionChanged,
this, &TextEditWrapper::onSelectionChanged );
} else if (m_plainTextEdit) {
connect( m_plainTextEdit, &QPlainTextEdit::selectionChanged,
this, &TextEditWrapper::onSelectionChanged );
connect( m_plainTextEdit, &QPlainTextEdit::cursorPositionChanged,
this, &TextEditWrapper::onSelectionChanged );
}
setLineWrappingEnabled(true);
editor->viewport()->installEventFilter(this);
auto completer = editor->findChild<QObject*>("CommandCompleter");
if (completer) {
m_completerPopup = completer->property("popup").value<QWidget*>();
Q_ASSERT(m_completerPopup);
if (m_completerPopup)
m_completerPopup->installEventFilter(this);
}
// Let FakeVim handle indentation.
m_handler->handleCommand(QLatin1String("set nopasskeys"));
}
~TextEditWrapper()
{
m_handler->disconnectFromEditor();
m_handler->deleteLater();
}
void install()
{
m_handler->installEventFilter();
m_handler->setupWidget();
m_handler->enterCommandMode();
}
bool eventFilter(QObject *obj, QEvent *ev) override
{
// Handle completion popup.
if (obj == m_completerPopup) {
if ( ev->type() == QEvent::KeyPress ) {
const auto kev = static_cast<QKeyEvent *>(ev);
const auto key = kev->key();
const auto mods = kev->modifiers();
if (mods.testFlag(Qt::ControlModifier)) {
if (key == Qt::Key_N || key == Qt::Key_P) {
const auto key2 = key == Qt::Key_N ? Qt::Key_Down : Qt::Key_Up;
QKeyEvent kev2(QEvent::KeyPress, key2, Qt::NoModifier);
QCoreApplication::sendEvent(obj, &kev2);
return true;
}
}
switch (key) {
case Qt::Key_Enter:
case Qt::Key_Return:
return false;
case Qt::Key_Down:
case Qt::Key_Up:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
return false;
default:
QCoreApplication::sendEvent(m_textEditWidget, ev);
return true;
}
}
return false;
}
if ( ev->type() != QEvent::Paint )
return false;
QWidget *viewport = editor()->viewport();
QPaintEvent *e = static_cast<QPaintEvent*>(ev);
const QRect r = e->rect();
QPainter painter(viewport);
const QTextCursor tc = EDITOR(textCursor());
m_context.cursorPosition = -1;
m_context.palette = editor()->palette();
const int h = m_textEdit ? horizontalOffset() : 0;
const int v = m_textEdit ? verticalOffset() : 0;
m_context.clip = r.translated(h, v);
painter.save();
// Draw base and text.
painter.translate(-h, -v);
paintDocument(&painter);
// Draw block selection.
if ( hasBlockSelection() ) {
QRect rect;
QTextCursor tc2 = tc;
tc2.setPosition(tc.position());
rect = EDITOR(cursorRect(tc2));
tc2.setPosition(tc.anchor());
rect = rect.united( EDITOR(cursorRect(tc2)) );
m_context.palette.setColor(QPalette::Base, m_context.palette.color(QPalette::Highlight));
m_context.palette.setColor(QPalette::Text, m_context.palette.color(QPalette::HighlightedText));
m_context.clip = rect.translated(h, v);
paintDocument(&painter);
}
painter.restore();
// Draw text cursor.
QRect rect = EDITOR(cursorRect());
if (EDITOR(overwriteMode()) || hasBlockSelection() ) {
QTextCursor tc2 = tc;
tc2.movePosition(QTextCursor::Right);
const QRect nextRect = EDITOR(cursorRect(tc2));
const int w = nextRect.left() - rect.left();
if (w > 3) {
rect.setWidth(w);
} else {
const QFontMetrics fm(editor()->font());
rect.setWidth( fm.averageCharWidth() );
}
} else {
rect.setWidth(2);
rect.adjust(-1, 0, 0, 0);
}
if ( hasBlockSelection() ) {
int from = tc.positionInBlock();
int to = tc.anchor() - tc.document()->findBlock(tc.anchor()).position();
if (from > to)
rect.moveLeft(rect.left() - rect.width());
}
painter.setCompositionMode(QPainter::CompositionMode_Difference);
const auto color = editor()->hasFocus() ? Qt::white : Qt::darkGray;
painter.fillRect(rect, color);
if (!hasBlockSelection() && m_cursorRect.width() != rect.width())
viewport->update();
m_cursorRect = rect;
return true;
}
FakeVimHandler &fakeVimHandler() { return *m_handler; }
void highlightMatches(const QString &pattern)
{
QTextCursor cur = EDITOR(textCursor());
Selection selection;
selection.format.setBackground(Qt::yellow);
selection.format.setForeground(Qt::black);
// Highlight matches.
QTextDocument *doc = document();
QRegularExpression re(pattern);
cur = doc->find(re);
m_searchSelection.clear();
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
m_searchSelection.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
updateSelections();
}
void setBlockSelection(bool on)
{
m_hasBlockSelection = on;
m_selection.clear();
updateSelections();
}
bool hasBlockSelection() const
{
return m_hasBlockSelection;
}
void setTextCursor(const QTextCursor &tc)
{
EDITOR(setTextCursor(tc));
}
QTextCursor textCursor() const
{
return EDITOR(textCursor());
}
QTextDocument *document() const
{
return EDITOR(document());
}
QAbstractScrollArea *editor() const { return m_textEditWidget; }
void setLineWrappingEnabled(bool enable)
{
if (m_textEdit)
m_textEdit->setLineWrapMode(enable ? QTextEdit::WidgetWidth : QTextEdit::NoWrap);
else if (m_plainTextEdit)
m_plainTextEdit->setLineWrapMode(enable ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
}
private:
void onSelectionChanged() {
m_hasBlockSelection = false;
m_selection.clear();
Selection selection;
const QPalette pal = editor()->palette();
selection.format.setBackground( pal.color(QPalette::Highlight) );
selection.format.setForeground( pal.color(QPalette::HighlightedText) );
selection.cursor = EDITOR(textCursor());
if ( selection.cursor.hasSelection() )
m_selection.append(selection);
updateSelections();
}
int horizontalOffset() const
{
QScrollBar *hbar = editor()->horizontalScrollBar();
return editor()->isRightToLeft() ? (hbar->maximum() - hbar->value()) : hbar->value();
}
int verticalOffset() const
{
return editor()->verticalScrollBar()->value();
}
void paintDocument(QPainter *painter)
{
painter->setClipRect(m_context.clip);
painter->fillRect(m_context.clip, m_context.palette.base());
if (m_textEdit)
document()->documentLayout()->draw(painter, m_context);
else if (m_plainTextEdit)
drawPlainTextDocument(m_plainTextEdit, m_context, painter);
}
void updateSelections()
{
m_context.selections.clear();
m_context.selections.reserve( m_searchSelection.size() + m_selection.size() );
m_context.selections << m_searchSelection << m_selection;
editor()->viewport()->update();
}
QAbstractScrollArea *m_textEditWidget;
QTextEdit *m_textEdit;
QPlainTextEdit *m_plainTextEdit;
FakeVimHandler *m_handler;
QObject *m_completerPopup = nullptr;
QRect m_cursorRect;
bool m_hasBlockSelection;
using Selection = QAbstractTextDocumentLayout::Selection;
using SelectionList = QVector<Selection>;
SelectionList m_searchSelection;
SelectionList m_selection;
QAbstractTextDocumentLayout::PaintContext m_context;
};
class Proxy final : public QObject
{
public:
Proxy(TextEditWrapper *editorWidget, QStatusBar *statusBar, QObject *parent = nullptr)
: QObject(parent)
, m_editorWidget(editorWidget)
, m_statusBar(statusBar)
, m_edit(new QLineEdit(statusBar))
, m_statusBarMessage(new QLabel(statusBar))
, m_statusBarData(new QLabel(statusBar))
, m_statusBarIcon(new QLabel(statusBar))
{
connect(m_edit, &QLineEdit::textEdited, this, &Proxy::cmdLineChanged);
connect(m_edit, &QLineEdit::cursorPositionChanged, this, &Proxy::cmdLineChanged);
connect(m_edit, &QLineEdit::selectionChanged, this, &Proxy::cmdLineChanged);
m_edit->setFrame(false);
m_edit->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
m_edit->installEventFilter( &m_editorWidget->fakeVimHandler() );
m_statusBar->insertWidget(0, m_edit, 4);
m_edit->hide();
m_statusBar->insertWidget(1, m_statusBarMessage, 1);
m_statusBarMessage->show();
m_statusBar->addPermanentWidget(m_statusBarData);
m_statusBarData->show();
m_statusBar->addPermanentWidget(m_statusBarIcon);
m_statusBarIcon->show();
}
void changeStatusData(const QString &info)
{
m_statusBarData->setText(info);
}
void highlightMatches(const QString &pattern)
{
m_editorWidget->highlightMatches(pattern);
}
void setStatusIcon(QStyle::StandardPixmap standardPixmap)
{
const auto icon = m_statusBarIcon->style()->standardIcon(standardPixmap);
const auto maxHeight = m_statusBarIcon->contentsRect().height();
const auto window = m_statusBarIcon->windowHandle();
auto sizes = icon.availableSizes();
std::sort(std::begin(sizes), std::end(sizes), [](const QSize &lhs, const QSize &rhs){
return lhs.height() > rhs.height();
});
const auto it = std::lower_bound(
sizes.begin(), sizes.end(), maxHeight,
[](const QSize &size, int height){
return size.height() > height;
});
const auto size = it == sizes.end() ? icon.actualSize(window, QSize(maxHeight, maxHeight)) : *it;
const auto pixmap = icon.pixmap(window, size);
m_statusBarIcon->setPixmap(pixmap);
}
void changeStatusMessage(
const QString &contents, int cursorPos, int anchorPos, int messageLevel)
{
if (cursorPos == -1) {
if ( m_edit->hasFocus() )
m_editorWidget->editor()->setFocus();
m_edit->hide();
m_statusBarMessage->setText(contents);
} else {
m_statusBarMessage->clear();
{
QSignalBlocker blocker(m_edit);
m_edit->setText(contents);
if (anchorPos != -1 && anchorPos != cursorPos)
m_edit->setSelection(anchorPos, cursorPos - anchorPos);
else
m_edit->setCursorPosition(cursorPos);
}
m_edit->show();
m_edit->setFocus();
}
if (messageLevel == MessageWarning)
setStatusIcon(QStyle::SP_MessageBoxWarning);
else if (messageLevel == MessageError)
setStatusIcon(QStyle::SP_MessageBoxCritical);
else
m_statusBarIcon->clear();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_editorWidget->editor(), tr("Information"), info);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if ( m_edit->hasFocus() )
m_editorWidget->editor()->setFocus();
if (cmd.cmd == "set") {
QString arg = cmd.args;
bool enable = !arg.startsWith("no");
if (enable)
arg.remove(0, 2);
*handled = setOption(arg, enable);
} else if ( wantSaveAndQuit(cmd) ) {
// :wq
saveAndClose();
*handled = true;
} else if ( wantSave(cmd) ) {
save(); // :w
*handled = true;
} else if ( wantQuit(cmd) ) {
if (cmd.hasBang)
invalidate(); // :q!
else
cancel(); // :q
*handled = true;
} else {
*handled = false;
}
}
void requestSetBlockSelection(const QTextCursor &cursor)
{
m_editorWidget->setTextCursor(cursor);
m_editorWidget->setBlockSelection(true);
}
void requestDisableBlockSelection()
{
m_editorWidget->setBlockSelection(false);
}
void requestBlockSelection(QTextCursor *cursor)
{
*cursor = m_editorWidget->textCursor();
m_editorWidget->setBlockSelection(true);
}
private:
void cmdLineChanged()
{
const int cursorPos = m_edit->cursorPosition();
int anchorPos = m_edit->selectionStart();
if (anchorPos == cursorPos)
anchorPos = cursorPos + m_edit->selectedText().length();
edited(m_edit->text(), cursorPos, anchorPos);
}
void edited(const QString &text, int cursorPos, int anchorPos)
{
m_editorWidget->fakeVimHandler().miniBufferTextEdited(text, cursorPos, anchorPos);
}
bool emitEditorSignal(const char *signal)
{
const auto editor = m_editorWidget->editor();
const QMetaObject *metaObject = editor->metaObject();
const int i = metaObject->indexOfSignal(signal);
if (i == -1)
return false;
metaObject->method(i).invoke(editor);
return true;
}
void clickDialogButton(QDialogButtonBox::StandardButton standardButton)
{
const auto window = m_editorWidget->editor()->window();
const auto buttonBox = window->findChild<QDialogButtonBox*>();
QPushButton *button = buttonBox->button(standardButton);
if (button)
button->click();
}
void save()
{
if ( !emitEditorSignal("save()") )
clickDialogButton(QDialogButtonBox::Apply);
}
void saveAndClose()
{
if ( !emitEditorSignal("save()") || !emitEditorSignal("cancel()") )
clickDialogButton(QDialogButtonBox::Ok);
}
void cancel()
{
if ( !emitEditorSignal("cancel()") )
clickDialogButton(QDialogButtonBox::Cancel);
}
void invalidate()
{
if ( !emitEditorSignal("invalidate()") )
clickDialogButton(QDialogButtonBox::Cancel);
}
bool wantSaveAndQuit(const ExCommand &cmd)
{
return cmd.cmd == "wq";
}
bool wantSave(const ExCommand &cmd)
{
return cmd.matches("w", "write") || cmd.matches("wa", "wall");
}
bool wantQuit(const ExCommand &cmd)
{
return cmd.matches("q", "quit") || cmd.matches("qa", "qall");
}
bool setOption(const QString &option, bool enable)
{
if (option == "linebreak" || option == "lbr")
m_editorWidget->setLineWrappingEnabled(enable);
else
return false;
return true;
}
TextEditWrapper *m_editorWidget;
QStatusBar *m_statusBar;
QLineEdit *m_edit;
QLabel *m_statusBarMessage;
QLabel *m_statusBarData;
QLabel *m_statusBarIcon;
};
void connectSignals(FakeVimHandler *handler, Proxy *proxy)
{
handler->commandBufferChanged
.connect([proxy](const QString &contents, int cursorPos, int anchorPos, int messageLevel) {
proxy->changeStatusMessage(contents, cursorPos, anchorPos, messageLevel);
}
);
handler->extraInformationChanged.connect(
[proxy](const QString &msg) {
proxy->changeExtraInformation(msg);
}
);
handler->statusDataChanged.connect(
[proxy](const QString &msg) {
proxy->changeStatusData(msg);
}
);
handler->highlightMatches.connect(
[proxy](const QString &needle) {
proxy->highlightMatches(needle);
}
);
handler->handleExCommandRequested.connect(
[proxy](bool *handled, const ExCommand &cmd) {
proxy->handleExCommand(handled, cmd);
}
);
handler->requestSetBlockSelection.connect(
[proxy](const QTextCursor &cursor) {
proxy->requestSetBlockSelection(cursor);
}
);
handler->requestDisableBlockSelection.connect(
[proxy]() {
proxy->requestDisableBlockSelection();
}
);
handler->requestBlockSelection.connect(
[proxy](QTextCursor *cursor) {
proxy->requestBlockSelection(cursor);
}
);
}
bool installEditor(QAbstractScrollArea *textEdit, const QString &sourceFileName, ItemFakeVimLoader *loader)
{
auto wrapper = new TextEditWrapper(textEdit);
// Position text cursor at the beginning of text instead of selecting all.
wrapper->setTextCursor( QTextCursor(wrapper->document()) );
QStatusBar *statusBar = new QStatusBar(textEdit);
statusBar->setObjectName("editor_status_bar");
const auto layout = textEdit->parentWidget()->layout();
if (layout)
layout->addWidget(statusBar);
statusBar->setFont(textEdit->font());
// Connect slots to FakeVimHandler signals.
auto proxy = new Proxy(wrapper, statusBar, wrapper);
connectSignals( &wrapper->fakeVimHandler(), proxy );
wrapper->install();
if (!sourceFileName.isEmpty())
wrapper->fakeVimHandler().handleCommand("source " + sourceFileName);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, wrapper, &QObject::deleteLater);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, statusBar, &QObject::deleteLater);
QObject::connect(loader, &ItemFakeVimLoader::deleteAllWrappers, textEdit, [textEdit](){
textEdit->setProperty(propertyWrapped, false);
});
return true;
}
template <typename TextEdit>
bool installEditor(QObject *obj, const QString &sourceFileName, ItemFakeVimLoader *loader)
{
auto textEdit = qobject_cast<TextEdit *>(obj);
return textEdit && !textEdit->isReadOnly() && installEditor(textEdit, sourceFileName, loader);
}
} // namespace
ItemFakeVimLoader::ItemFakeVimLoader()
{
}
ItemFakeVimLoader::~ItemFakeVimLoader() = default;
QVariant ItemFakeVimLoader::icon() const
{
return QIcon(":/fakevim/fakevim.png");
}
void ItemFakeVimLoader::setEnabled(bool enabled)
{
m_enabled = enabled;
updateCurrentlyEnabledState();
}
void ItemFakeVimLoader::applySettings(QSettings &settings)
{
settings.setValue(configReallyEnabled, ui->checkBoxEnable->isChecked());
settings.setValue(configSourceFile, ui->lineEditSourceFileName->text());
}
void ItemFakeVimLoader::loadSettings(const QSettings &settings)
{
m_reallyEnabled = settings.value(configReallyEnabled, false).toBool();
m_sourceFileName = settings.value(configSourceFile).toString();
updateCurrentlyEnabledState();
}
QWidget *ItemFakeVimLoader::createSettingsWidget(QWidget *parent)
{
ui.reset(new Ui::ItemFakeVimSettings);
QWidget *w = new QWidget(parent);
ui->setupUi(w);
ui->checkBoxEnable->setChecked(m_reallyEnabled);
ui->lineEditSourceFileName->setText(m_sourceFileName);
return w;
}
QObject *ItemFakeVimLoader::tests(const TestInterfacePtr &test) const
{
#ifdef HAS_TESTS
QVariantMap settings;
settings["really_enable"] = true;
settings["source_file"] = QString(ItemFakeVimTests::fileNameToSource());
QObject *tests = new ItemFakeVimTests(test);
tests->setProperty("CopyQ_test_settings", settings);
return tests;
#else
Q_UNUSED(test)
return nullptr;
#endif
}
bool ItemFakeVimLoader::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::Show)
wrapEditWidget(watched);
return false;
}
void ItemFakeVimLoader::updateCurrentlyEnabledState()
{
if ( qobject_cast<QGuiApplication*>(qApp) == nullptr )
return;
const bool enable = m_enabled && m_reallyEnabled;
if (m_currentlyEnabled == enable)
return;
if (enable) {
// WORKAROUND: Disallow blinking text cursor application-wide
// (unfortunately, there doesn't seem other way to do this).
m_oldCursorFlashTime = qApp->cursorFlashTime();
qApp->setCursorFlashTime(0);
qApp->installEventFilter(this);
for (auto topLevel : qApp->topLevelWidgets()) {
for ( auto textEdit : topLevel->findChildren<QTextEdit*>() )
wrapEditWidget(textEdit);
for ( auto textEdit : topLevel->findChildren<QPlainTextEdit*>() )
wrapEditWidget(textEdit);
}
} else {
emit deleteAllWrappers();
qApp->removeEventFilter(this);
qApp->setCursorFlashTime(m_oldCursorFlashTime);
}
m_currentlyEnabled = enable;
}
void ItemFakeVimLoader::wrapEditWidget(QObject *obj)
{
if ( !obj->property(propertyWrapped).toBool()
&& ( installEditor<QTextEdit>(obj, m_sourceFileName, this)
|| installEditor<QPlainTextEdit>(obj, m_sourceFileName, this) )
)
{
obj->setProperty(propertyWrapped, true);
}
}