forked from KDE/ghostwriter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkdownEditor.cpp
More file actions
2306 lines (1983 loc) · 64.4 KB
/
Copy pathMarkdownEditor.cpp
File metadata and controls
2306 lines (1983 loc) · 64.4 KB
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************
*
* Copyright (C) 2014-2020 wereturtle
* Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Graeme Gott <graeme@gottcode.org>
* Copyright (C) Dmitry Shachnev 2012
*
* 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 <QApplication>
#include <QChar>
#include <QColor>
#include <QDesktopWidget>
#include <QDir>
#include <QFileInfo>
#include <QGuiApplication>
#include <QHeaderView>
#include <QMenu>
#include <QMimeData>
#include <QPainter>
#include <QPainterPath>
#include <QPixmap>
#include <QScreen>
#include <QScrollBar>
#include <QString>
#include <QTextBoundaryFinder>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include "CmarkGfmAPI.h"
#include "ColorHelper.h"
#include "MarkdownEditor.h"
#include "MarkdownHighlighter.h"
#include "MarkdownStates.h"
#include "spelling/dictionary_manager.h"
#include "spelling/dictionary_ref.h"
#include "spelling/spell_checker.h"
#define GW_TEXT_FADE_FACTOR 1.5
MarkdownEditor::MarkdownEditor
(
MarkdownDocument* textDocument,
QWidget* parent
)
: QPlainTextEdit(parent),
textDocument(textDocument),
dictionary(DictionaryManager::instance().requestDictionary()),
autoMatchEnabled(true),
bulletPointCyclingEnabled(true),
mouseButtonDown(false)
{
setDocument(textDocument);
setAcceptDrops(true);
preferredLayout = new QGridLayout();
preferredLayout->setSpacing(0);
preferredLayout->setMargin(0);
preferredLayout->setContentsMargins(0, 0, 0, 0);
preferredLayout->addWidget(this, 0, 0);
blockquoteRegex.setPattern("^ {0,3}(>\\s*)+");
numberedListRegex.setPattern("^\\s*([0-9]+)[.)]\\s+");
bulletListRegex.setPattern("^\\s*[+*-]\\s+");
taskListRegex.setPattern("^\\s*[-*+] \\[([x ])\\]\\s+");
emptyBlockquoteRegex.setPattern("^ {0,3}(>\\s*)+$");
emptyNumberedListRegex.setPattern("^\\s*([0-9]+)[.)]\\s+$");
emptyBulletListRegex.setPattern("^\\s*[+*-]\\s+$");
emptyTaskListRegex.setPattern("^\\s*[-*+] \\[([x ])\\]\\s+$");
this->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// Make sure QPlainTextEdit does not draw a cursor. (We'll paint it manually.)
setCursorWidth(0);
setCenterOnScroll(true);
ensureCursorVisible();
spellCheckEnabled = false;
installEventFilter(this);
viewport()->installEventFilter(this);
hemingwayModeEnabled = false;
focusMode = FocusModeDisabled;
insertSpacesForTabs = false;
setTabulationWidth(4);
editorWidth = EditorWidthMedium;
editorCorners = InterfaceStyleRounded;
markupPairs.insert('"', '"');
markupPairs.insert('\'', '\'');
markupPairs.insert('(', ')');
markupPairs.insert('[', ']');
markupPairs.insert('{', '}');
markupPairs.insert('*', '*');
markupPairs.insert('_', '_');
markupPairs.insert('`', '`');
markupPairs.insert('<', '>');
// Set automatching for the above markup pairs to be
// enabled by default.
//
autoMatchFilter.insert('"', true);
autoMatchFilter.insert('\'', true);
autoMatchFilter.insert('(', true);
autoMatchFilter.insert('[', true);
autoMatchFilter.insert('{', true);
autoMatchFilter.insert('*', true);
autoMatchFilter.insert('_', true);
autoMatchFilter.insert('`', true);
autoMatchFilter.insert('<', true);
nonEmptyMarkupPairs.insert('*', '*');
nonEmptyMarkupPairs.insert('_', '_');
nonEmptyMarkupPairs.insert('<', '>');
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));
connect(this->document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(onContentsChanged(int,int,int)));
connect(this->document(), SIGNAL(textBlockRemoved(const QTextBlock&)), this, SLOT(onTextBlockRemoved(const QTextBlock&)));
connect(this, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
highlighter = new MarkdownHighlighter(this);
addWordToDictionaryAction = new QAction(tr("Add word to dictionary"), this);
checkSpellingAction = new QAction(tr("Check spelling..."), this);
typingPausedSignalSent = true;
typingHasPaused = true;
typingTimer = new QTimer(this);
connect
(
typingTimer,
SIGNAL(timeout()),
this,
SLOT(checkIfTypingPaused())
);
typingTimer->start(1000);
typingPausedScaledSignalSent = true;
scaledTypingHasPaused = true;
scaledTypingTimer = new QTimer(this);
connect
(
scaledTypingTimer,
SIGNAL(timeout()),
this,
SLOT(checkIfTypingPausedScaled())
);
scaledTypingTimer->start(1000);
setColorScheme
(
QColor(Qt::black),
QColor(Qt::white),
QColor(Qt::black),
QColor(Qt::blue),
QColor(Qt::black),
QColor(Qt::black),
QColor(Qt::black),
QColor(Qt::black),
QColor(Qt::red)
);
textCursorVisible = true;
cursorBlinkTimer = new QTimer(this);
connect(cursorBlinkTimer, SIGNAL(timeout()), this, SLOT(toggleCursorBlink()));
cursorBlinkTimer->start(500);
}
MarkdownEditor::~MarkdownEditor()
{
}
void MarkdownEditor::paintEvent(QPaintEvent* event)
{
QPainter painter(viewport());
QRect viewportRect = viewport()->rect();
painter.fillRect(viewportRect, Qt::transparent);
QPointF offset(contentOffset());
QTextBlock block = firstVisibleBlock();
bool firstVisible = true;
QRectF blockAreaRect; // Code or block quote rect.
bool inBlockArea = false;
BlockType blockType = BlockTypeNone;
bool clipTop = false;
bool drawBlock = false;
int dy = 0;
bool done = false;
int cornerRadius = 5;
if (InterfaceStyleSquare == editorCorners)
{
cornerRadius = 0;
}
// Draw text block area backgrounds for code blocks and block quotes.
// The backgrounds are drawn per each block area (consisting of multiple
// text blocks or lines), rather than one rectangle area per text block/
// line in case there are margins between each text block. This way,
// the background will extend to cover the margins between text blocks
// as well.
//
// NOTE: Algorithm for looping through text blocks is a partial lift from
// Qt's QPlainTextEdit paintEvent() code. Please refer to the
// LGPL v. 3 license for the original Qt code.
//
while (block.isValid() && !done)
{
QRectF r = blockBoundingRect(block).translated(offset);
// If the block begins a new text block area...
if (!inBlockArea && atBlockAreaStart(block, blockType))
{
blockAreaRect = r;
dy = 0;
inBlockArea = true;
BlockType prevType;
// If this is the first visible block within the viewport
// and if the previous block is part of the text block area,
// then the rectangle to draw for the block area will have
// its top clipped by the viewport and will need to be
// drawn specially.
//
if
(
firstVisible
&& atBlockAreaStart(block.previous(), prevType)
&& (blockType == prevType)
)
{
clipTop = true;
}
}
// Else if the block ends a text block area...
else if (inBlockArea && atBlockAreaEnd(block, blockType))
{
drawBlock = true;
inBlockArea = false;
blockAreaRect.setHeight(dy);
}
// If the block is at the end of the document and ends a text
// block area...
//
if (inBlockArea && (block == this->document()->lastBlock()))
{
drawBlock = true;
inBlockArea = false;
dy += r.height();
blockAreaRect.setHeight(dy);
}
offset.ry() += r.height();
dy += r.height();
// If this is the last text block visible within the viewport...
if (offset.y() > viewportRect.height())
{
if (inBlockArea)
{
blockAreaRect.setHeight(dy);
drawBlock = true;
}
// Finished drawing.
done = true;
}
if (drawBlock)
{
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(blockColor));
// If the first visible block is "clipped" such that the previous block
// is part of the text block area, then only draw a rectangle with the
// bottom corners rounded, and with the top corners square to reflect
// that the first visible block is part of a larger block of text.
//
if (clipTop)
{
QPainterPath path;
path.setFillRule(Qt::WindingFill);
path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);
qreal adjustedHeight = blockAreaRect.height() / 2;
path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));
painter.drawPath(path.simplified());
clipTop = false;
}
// Else draw the entire rectangle with all corners rounded.
else
{
painter.drawRoundedRect(blockAreaRect, cornerRadius, cornerRadius);
}
drawBlock = false;
}
// This fixes the RTL bug of QPlainTextEdit
// https://bugreports.qt.io/browse/QTBUG-7516.
//
// Credit goes to Patrizio Bekerle (qmarkdowntextedit) for discovering
// this workaround.
//
if (block.text().isRightToLeft())
{
QTextLayout* layout = block.layout();
QTextOption opt = document()->defaultTextOption();
opt = QTextOption(Qt::AlignRight);
opt.setTextDirection(Qt::RightToLeft);
layout->setTextOption(opt);
}
block = block.next();
firstVisible = false;
}
painter.end();
// Draw the visible editor text.
QPlainTextEdit::paintEvent(event);
// Draw the text cursor/caret.
if (textCursorVisible && this->hasFocus())
{
// Get the cursor rect so that we have the ideal height for it,
// and then set it to be 2 pixels wide. (The width will be zero,
// because we set it to be that in the constructor so that
// QPlainTextEdit will not draw another cursor underneath this one.)
//
QRect r = cursorRect();
r.setWidth(2);
QPainter painter(viewport());
painter.fillRect(r, QBrush(cursorColor));
painter.end();
}
}
void MarkdownEditor::setDictionary(const QString& language)
{
dictionary = DictionaryManager::instance().requestDictionary(language);
highlighter->setDictionary(dictionary);
}
QLayout* MarkdownEditor::getPreferredLayout()
{
return preferredLayout;
}
bool MarkdownEditor::getHemingwayModeEnabled() const
{
return hemingwayModeEnabled;
}
/**
* Sets whether Hemingway mode is enabled.
*/
void MarkdownEditor::setHemingWayModeEnabled(bool enabled)
{
hemingwayModeEnabled = enabled;
}
FocusMode MarkdownEditor::getFocusMode()
{
return focusMode;
}
void MarkdownEditor::setFocusMode(FocusMode mode)
{
focusMode = mode;
if (FocusModeDisabled != mode)
{
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(focusText()));
connect(this, SIGNAL(selectionChanged()), this, SLOT(focusText()));
connect(this, SIGNAL(textChanged()), this, SLOT(focusText()));
focusText();
}
else
{
disconnect(this, SIGNAL(cursorPositionChanged()), this, SLOT(focusText()));
disconnect(this, SIGNAL(selectionChanged()), this, SLOT(focusText()));
disconnect(this, SIGNAL(textChanged()), this, SLOT(focusText()));
this->setExtraSelections(QList<QTextEdit::ExtraSelection>());
}
}
void MarkdownEditor::setColorScheme
(
const QColor& defaultTextColor,
const QColor& backgroundColor,
const QColor& markupColor,
const QColor& linkColor,
const QColor& headingColor,
const QColor& emphasisColor,
const QColor& blockquoteColor,
const QColor& codeColor,
const QColor& spellingErrorColor
)
{
highlighter->setColorScheme
(
defaultTextColor,
backgroundColor,
markupColor,
linkColor,
headingColor,
emphasisColor,
blockquoteColor,
codeColor,
spellingErrorColor
);
this->cursorColor = linkColor;
blockColor = defaultTextColor;
int blockAlpha = 20;
if (backgroundColor.alpha() < 255)
{
blockAlpha = 18;
}
else if (ColorHelper::getLuminance(blockColor) < 0.5)
{
blockAlpha = 10;
}
blockColor.setAlpha(blockAlpha);
QColor fadedForegroundColor = defaultTextColor;
fadedForegroundColor.setAlpha(100);
fadeColor = QBrush(fadedForegroundColor);
focusText();
}
void MarkdownEditor::setAspect(EditorAspect aspect)
{
this->aspect = aspect;
}
void MarkdownEditor::setFont(const QString& family, double pointSize)
{
QFont font(family, pointSize);
QPlainTextEdit::setFont(font);
highlighter->setFont(family, pointSize);
setTabulationWidth(tabWidth);
}
void MarkdownEditor::setShowTabsAndSpacesEnabled(bool enabled)
{
QTextOption option = textDocument->defaultTextOption();
if (enabled)
{
option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces);
}
else
{
option.setFlags(option.flags() & ~QTextOption::ShowTabsAndSpaces);
}
textDocument->setDefaultTextOption(option);
}
void MarkdownEditor::setupPaperMargins(int width)
{
if (EditorWidthFull == editorWidth)
{
preferredLayout->setContentsMargins(0, 0, 0, 0);
setViewportMargins(0, 0, 0, 0);
return;
}
int screenWidth = QGuiApplication::primaryScreen()->size().width();
int proposedEditorWidth = width;
int margin = 0;
switch (editorWidth)
{
case EditorWidthNarrow:
proposedEditorWidth = screenWidth / 3;
break;
case EditorWidthMedium:
proposedEditorWidth = screenWidth / 2;
break;
case EditorWidthWide:
proposedEditorWidth = 2 * (screenWidth / 3);
break;
default:
break;
}
if (proposedEditorWidth <= width)
{
margin = (width - proposedEditorWidth) / 2;
}
if (EditorAspectStretch == aspect)
{
preferredLayout->setContentsMargins(0, 0, 0, 0);
setViewportMargins(margin, 20, margin, 0);
}
else
{
preferredLayout->setContentsMargins(margin, 20, margin, 20);
setViewportMargins(10, 10, 10, 10);
}
}
void MarkdownEditor::dragEnterEvent(QDragEnterEvent* e)
{
if (e->mimeData()->hasUrls())
{
e->acceptProposedAction();
}
else
{
QPlainTextEdit::dragEnterEvent(e);
}
}
void MarkdownEditor::dragMoveEvent(QDragMoveEvent* e)
{
e->acceptProposedAction();
}
void MarkdownEditor::dragLeaveEvent(QDragLeaveEvent* e)
{
e->accept();
}
void MarkdownEditor::dropEvent(QDropEvent* e)
{
if (e->mimeData()->hasUrls() && (e->mimeData()->urls().size() == 1))
{
e->acceptProposedAction();
QUrl url = e->mimeData()->urls().first();
QString path = url.toLocalFile();
bool isRelativePath = false;
QFileInfo fileInfo(path);
QString fileExtension = fileInfo.suffix().toLower();
QTextCursor dropCursor = cursorForPosition(e->pos());
// If the file extension indicates an image type, then insert an
// image link into the text.
if
(
(fileExtension == "jpg") ||
(fileExtension == "jpeg") ||
(fileExtension == "gif") ||
(fileExtension == "bmp") ||
(fileExtension == "png") ||
(fileExtension == "tif") ||
(fileExtension == "tiff") ||
(fileExtension == "svg")
)
{
if (!textDocument->isNew())
{
QFileInfo docInfo(textDocument->getFilePath());
if (docInfo.exists())
{
path = docInfo.dir().relativeFilePath(path);
isRelativePath = true;
}
}
if (!isRelativePath)
{
path = url.toString();
}
dropCursor.insertText(QString("").arg(path));
// We have to call the super class so that clean up occurs,
// otherwise the editor's cursor will freeze. We also have to use
// a dummy drop event with dummy MIME data, otherwise the parent
// class will insert the file path into the document.
//
QMimeData* dummyMimeData = new QMimeData();
dummyMimeData->setText("");
QDropEvent* dummyEvent =
new QDropEvent
(
e->pos(),
e->possibleActions(),
dummyMimeData,
e->mouseButtons(),
e->keyboardModifiers()
);
QPlainTextEdit::dropEvent(dummyEvent);
delete dummyEvent;
delete dummyMimeData;
}
// Else insert URL path as normal, using the parent class.
else
{
QPlainTextEdit::dropEvent(e);
}
}
else
{
QPlainTextEdit::dropEvent(e);
}
}
/*
* This method contains a code snippet that was lifted and modified from ReText
*/
void MarkdownEditor::keyPressEvent(QKeyEvent* e)
{
int key = e->key();
QTextCursor cursor(this->textCursor());
switch (key)
{
case Qt::Key_Return:
if (!cursor.hasSelection())
{
if (e->modifiers() & Qt::ShiftModifier)
{
// Insert Markdown-style line break
cursor.insertText(" ");
highlighter->rehighlightBlock(cursor.block());
}
if (e->modifiers() & Qt::ControlModifier)
{
cursor.insertText("\n");
}
else
{
handleCarriageReturn();
}
}
else
{
QPlainTextEdit::keyPressEvent(e);
}
break;
case Qt::Key_Delete:
if (!hemingwayModeEnabled)
{
QPlainTextEdit::keyPressEvent(e);
}
break;
case Qt::Key_Backspace:
if (!hemingwayModeEnabled)
{
if (!handleBackspaceKey())
{
QPlainTextEdit::keyPressEvent(e);
}
}
break;
case Qt::Key_Tab:
if (!handleWhitespaceInEmptyMatch('\t'))
{
indentText();
}
break;
case Qt::Key_Backtab:
unindentText();
break;
case Qt::Key_Space:
if (!handleWhitespaceInEmptyMatch(' '))
{
QPlainTextEdit::keyPressEvent(e);
}
break;
default:
if (e->text().size() == 1)
{
QChar ch = e->text().at(0);
if (!handleEndPairCharacterTyped(ch) && !insertPairedCharacters(ch))
{
QPlainTextEdit::keyPressEvent(e);
}
}
else
{
QPlainTextEdit::keyPressEvent(e);
}
break;
}
}
bool MarkdownEditor::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress)
{
mouseButtonDown = true;
}
else if (event->type() == QEvent::MouseButtonRelease)
{
mouseButtonDown = false;
}
else if (event->type() == QEvent::MouseButtonDblClick)
{
mouseButtonDown = true;
}
if (event->type() != QEvent::ContextMenu || !spellCheckEnabled || this->isReadOnly())
{
return QPlainTextEdit::eventFilter(watched, event);
}
else
{
// Check spelling of text block under mouse
QContextMenuEvent* contextEvent = static_cast<QContextMenuEvent*>(event);
// If the context menu event was triggered by pressing the menu key,
// use the current text cursor rather than the event position to get
// a cursor position, since the event position is the mouse position
// rather than the text cursor position.
//
if (QContextMenuEvent::Keyboard == contextEvent->reason())
{
cursorForWord = this->textCursor();
}
// Else process as mouse event.
//
else
{
cursorForWord = cursorForPosition(contextEvent->pos());
}
QTextCharFormat::UnderlineStyle spellingErrorUnderlineStyle =
(QTextCharFormat::UnderlineStyle)
QApplication::style()->styleHint
(
QStyle::SH_SpellCheckUnderlineStyle
);
// Get the formatting for the cursor position under the mouse,
// and see if it has the spell check error underline style.
//
bool wordHasSpellingError = false;
int blockPosition = cursorForWord.positionInBlock();
#if (QT_VERSION_MAJOR == 5) && (QT_VERSION_MINOR < 6)
QList<QTextLayout::FormatRange> formatList =
cursorForWord.block().layout()->additionalFormats();
#else
QVector<QTextLayout::FormatRange> formatList =
cursorForWord.block().layout()->formats();
#endif
int mispelledWordStartPos = 0;
int mispelledWordLength = 0;
for (int i = 0; i < formatList.length(); i++)
{
QTextLayout::FormatRange formatRange = formatList[i];
if
(
(blockPosition >= formatRange.start)
&& (blockPosition <= (formatRange.start + formatRange.length))
&& (formatRange.format.underlineStyle() == spellingErrorUnderlineStyle)
)
{
mispelledWordStartPos = formatRange.start;
mispelledWordLength = formatRange.length;
wordHasSpellingError = true;
break;
}
}
// The word under the mouse is spelled correctly, so use the default
// processing for the context menu and return.
//
if (!wordHasSpellingError)
{
return QPlainTextEdit::eventFilter(watched, event);
}
// Select the misspelled word.
cursorForWord.movePosition
(
QTextCursor::PreviousCharacter,
QTextCursor::MoveAnchor,
blockPosition - mispelledWordStartPos
);
cursorForWord.movePosition
(
QTextCursor::NextCharacter,
QTextCursor::KeepAnchor,
mispelledWordLength
);
wordUnderMouse = cursorForWord.selectedText();
QStringList suggestions = dictionary.suggestions(wordUnderMouse);
QMenu* popupMenu = createStandardContextMenu();
QAction* firstAction = popupMenu->actions().first();
spellingActions.clear();
if (!suggestions.empty())
{
for (int i = 0; i < suggestions.size(); i++)
{
QAction* suggestionAction = new QAction(suggestions[i], this);
// Need the following line because KDE Plasma 5 will insert a hidden ampersand
// into the menu text as a keyboard accelerator. Go off of the data in the
// QAction rather than the text to avoid this.
//
suggestionAction->setData(suggestions[i]);
spellingActions.append(suggestionAction);
popupMenu->insertAction(firstAction, suggestionAction);
}
}
else
{
QAction* noSuggestionsAction =
new QAction(tr("No spelling suggestions found"), this);
noSuggestionsAction->setEnabled(false);
spellingActions.append(noSuggestionsAction);
popupMenu->insertAction(firstAction, noSuggestionsAction);
}
popupMenu->insertSeparator(firstAction);
popupMenu->insertAction(firstAction, addWordToDictionaryAction);
popupMenu->insertSeparator(firstAction);
popupMenu->insertAction(firstAction, checkSpellingAction);
popupMenu->insertSeparator(firstAction);
// Show menu
connect(popupMenu, SIGNAL(triggered(QAction*)), this, SLOT(suggestSpelling(QAction*)));
QPoint menuPos;
// If event was triggered by a key press, use the text cursor
// coordinates to display the popup menu.
//
if (QContextMenuEvent::Keyboard == contextEvent->reason())
{
QRect cr = this->cursorRect();
menuPos.setX(cr.x());
menuPos.setY(cr.y() + (cr.height() / 2));
menuPos = viewport()->mapToGlobal(menuPos);
}
// Else use the mouse coordinates from the context menu event.
//
else
{
menuPos = viewport()->mapToGlobal(contextEvent->pos());
}
popupMenu->exec(menuPos);
delete popupMenu;
for (int i = 0; i < spellingActions.size(); i++)
{
delete spellingActions[i];
}
spellingActions.clear();
return true;
}
}
void MarkdownEditor::wheelEvent(QWheelEvent *e)
{
Qt::KeyboardModifiers modifier = e->modifiers();
#if QT_VERSION >= 0x050000
int numDegrees = 0;
QPoint angleDelta = e->angleDelta();
if (!angleDelta.isNull())
{
numDegrees = angleDelta.y();
}
#else
int numDegrees = e->delta();
#endif
if ((Qt::ControlModifier == modifier) && (0 != numDegrees))
{
int fontSize = this->font().pointSize();
if (numDegrees > 0)
{
fontSize += 1;
}
else
{
fontSize -= 1;
}
// check for negative value
if (fontSize <= 0)
{
fontSize = 1;
}
setFont(this->font().family(), fontSize);
emit fontSizeChanged(fontSize);
}
else
{
QPlainTextEdit::wheelEvent(e);
}
}
void MarkdownEditor::navigateDocument(const int position)
{
QTextCursor cursor = this->textCursor();
cursor.setPosition(position);
this->setTextCursor(cursor);
this->activateWindow();
}
void MarkdownEditor::bold()
{
insertFormattingMarkup("**");
}
void MarkdownEditor::italic()
{
insertFormattingMarkup("*");
}
void MarkdownEditor::strikethrough()
{
insertFormattingMarkup("~~");
}
void MarkdownEditor::insertComment()
{
QTextCursor cursor = this->textCursor();
if (cursor.hasSelection())
{
QString text = cursor.selectedText();
text = QString("<!-- " + text + " -->");
cursor.insertText(text);
}
else
{
cursor.insertText("<!-- -->");
cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, 4);
this->setTextCursor(cursor);
}
}
void MarkdownEditor::createBulletListWithAsteriskMarker()
{
insertPrefixForBlocks("* ");
}
void MarkdownEditor::createBulletListWithMinusMarker()
{
insertPrefixForBlocks("- ");
}
void MarkdownEditor::createBulletListWithPlusMarker()
{
insertPrefixForBlocks("+ ");
}