-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrichtextedit.cpp
More file actions
626 lines (541 loc) · 19.2 KB
/
Copy pathrichtextedit.cpp
File metadata and controls
626 lines (541 loc) · 19.2 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
#include "richtextedit.h"
#include "helpfunc.h"
#include <QApplication>
#include <QClipboard>
#include <QEvent>
#include <QInputMethodEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QTextBlock>
#include <QTextFrame>
#include <QTextFragment>
#include <QTextImageFormat>
#include <QTextTable>
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
# pragma execution_character_set("utf-8")
#endif
bool RichTextEdit::blockHasChecklistPrefix(const QTextBlock &block)
{
return textHasChecklistPrefix(block.text());
}
int RichTextEdit::checklistBodyStartOffset(const QString &text)
{
if (!textHasChecklistPrefix(text))
{
return 0;
}
// 用户可能删除 checkbox 后面的空格,正文起点需要兼容“有空格”和“无空格”两种状态。
if (text.size() > 1 && text.at(1) == QLatin1Char(' '))
{
return 2;
}
return 1;
}
bool RichTextEdit::blockIsEmptyChecklist(const QTextBlock &block)
{
QString text = block.text();
return blockHasChecklistPrefix(block) && text.size() <= checklistBodyStartOffset(text);
}
bool RichTextEdit::blockChecklistChecked(const QTextBlock &block)
{
QString text = block.text();
return !text.isEmpty() && text.at(0) == checklistCheckedChar();
}
QTextCharFormat RichTextEdit::checklistBodyDefaultFormat(QTextDocument *document)
{
// 光标紧贴 checkbox 输入正文时,不能继承 checkbox 的 Segoe UI Symbol 字体。
QTextCharFormat format;
QFont font = document->defaultFont();
format.setFont(font);
setTextCharFormatFontFamily(format, font.family());
format.setFontStrikeOut(false);
return format;
}
QRect RichTextEdit::checklistMarkerHitRect(const QTextBlock &block) const
{
QTextCursor startCursor(document());
startCursor.setPosition(block.position());
QTextCursor endCursor(startCursor);
endCursor.movePosition(QTextCursor::NextCharacter);
QRect rect = cursorRect(startCursor).united(cursorRect(endCursor));
rect.adjust(-4, -3, 4, 3);
return rect;
}
void RichTextEdit::applyChecklistTextState(QTextDocument *document, const QTextBlock &block, bool checked)
{
QString text = block.text();
int startOffset = 1;
if (text.size() <= startOffset)
{
return;
}
// 删除线只作用在正文非空白字符上,避免“勾选后再输入空格,取消勾选空格仍带删除线”。
QTextCharFormat spaceFormat;
spaceFormat.setFontStrikeOut(false);
QTextCharFormat format;
format.setFontStrikeOut(checked);
int runStart = startOffset;
bool runIsSpace = text.at(runStart).isSpace();
for (int i = startOffset + 1; i <= text.size(); ++i)
{
bool atEnd = (i == text.size());
bool isSpace = !atEnd && text.at(i).isSpace();
if (!atEnd && isSpace == runIsSpace)
{
continue;
}
QTextCursor cursor(document);
cursor.setPosition(block.position() + runStart);
cursor.setPosition(block.position() + i, QTextCursor::KeepAnchor);
cursor.mergeCharFormat(runIsSpace ? spaceFormat : format);
runStart = i;
runIsSpace = isSpace;
}
}
void RichTextEdit::applyChecklistMarkerFormat(QTextDocument *document, const QTextBlock &block)
{
if (!blockHasChecklistPrefix(block))
{
return;
}
QTextCursor cursor(document);
cursor.setPosition(block.position());
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
// checkbox 借用正文格式取得字号,但字体/粗体/删除线必须单独固定,避免被整篇格式污染。
QTextCharFormat format;
QString text = block.text();
int startOffset = checklistBodyStartOffset(text);
if (text.size() > startOffset)
{
QTextCursor bodyCursor(document);
bodyCursor.setPosition(block.position() + startOffset);
bodyCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
format = bodyCursor.charFormat();
}
else
{
format = block.charFormat();
QFont font = document->defaultFont();
if (format.fontPointSize() <= 0)
{
format.setFontPointSize(font.pointSizeF());
}
if (format.font().pixelSize() <= 0 && font.pixelSize() > 0)
{
QFont currentFont = format.font();
currentFont.setPixelSize(font.pixelSize());
format.setFont(currentFont);
}
}
QFont markerFont = format.font();
markerFont.setFamily(checklistMarkerFontFamily());
markerFont.setBold(false);
markerFont.setWeight(QFont::Normal);
if (markerFont.pointSizeF() > 0)
{
markerFont.setPointSizeF(markerFont.pointSizeF() + 2.0);
}
else if (markerFont.pixelSize() > 0)
{
markerFont.setPixelSize(markerFont.pixelSize() + 2);
}
format.setFont(markerFont);
setTextCharFormatFontFamily(format, checklistMarkerFontFamily());
format.setFontWeight(QFont::Normal);
format.setFontStrikeOut(false);
cursor.mergeCharFormat(format);
}
void RichTextEdit::refreshChecklistBlockFormats(QTextDocument *document, const QTextBlock &block)
{
if (!blockHasChecklistPrefix(block))
{
return;
}
applyChecklistTextState(document, block, blockChecklistChecked(block));
applyChecklistMarkerFormat(document, block);
}
void RichTextEdit::applyChecklistInputFormat()
{
QTextCursor cursor = textCursor();
QTextBlock block = cursor.block();
QString text = block.text();
if (!textHasChecklistPrefix(text) || cursor.positionInBlock() != 1)
{
return;
}
// 光标位于 checkbox 后且无空格时,下一次输入要切回正文格式,否则会继续用 checkbox 字体。
QTextCharFormat format;
if (text.size() > 1)
{
QTextCursor bodyCursor(document());
bodyCursor.setPosition(block.position() + 1);
bodyCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
format = bodyCursor.charFormat();
}
else
{
format = checklistBodyDefaultFormat(document());
}
setCurrentCharFormat(format);
}
bool RichTextEdit::isCodeBlockTable(const QTextTable *table)
{
if (!table || table->rows() != 1 || table->columns() != 1)
{
return false;
}
QTextTableFormat format = table->format();
QTextLength width = format.width();
return width.type() == QTextLength::PercentageLength
&& qRound(width.rawValue()) == 80
&& qRound(format.border()) == 1
&& qRound(format.cellPadding()) == 8
&& qRound(format.cellSpacing()) == 0
&& format.background().color() == codeBlockBackgroundColor()
&& format.borderBrush().color() == codeBlockBorderColor();
}
QTextCharFormat RichTextEdit::codeBlockTextFormat(const QTextCharFormat &baseFormat)
{
QTextCharFormat format = baseFormat;
QFont font = format.font();
font.setFamily(codeBlockFontFamily());
font.setStyleHint(QFont::Monospace);
font.setBold(false);
font.setWeight(QFont::Normal);
format.setFont(font);
setTextCharFormatFontFamily(format, codeBlockFontFamily());
format.setFontWeight(QFont::Normal);
format.setFontStrikeOut(false);
return format;
}
void RichTextEdit::refreshCodeBlockTableFormats(QTextTable *table)
{
if (!isCodeBlockTable(table))
{
return;
}
for (int row = 0; row < table->rows(); ++row)
{
for (int col = 0; col < table->columns(); ++col)
{
QTextTableCell cell = table->cellAt(row, col);
QTextCursor contentCursor = cell.firstCursorPosition();
QTextCursor endCursor = cell.lastCursorPosition();
int startPos = contentCursor.position();
int endPos = endCursor.position();
if (endPos > startPos)
{
contentCursor.setPosition(startPos);
contentCursor.setPosition(endPos, QTextCursor::KeepAnchor);
contentCursor.mergeCharFormat(codeBlockTextFormat(contentCursor.charFormat()));
}
for (QTextBlock block = cell.firstCursorPosition().block(); block.isValid(); block = block.next())
{
QTextCursor blockCursor(block);
blockCursor.select(QTextCursor::BlockUnderCursor);
blockCursor.mergeBlockCharFormat(codeBlockTextFormat(blockCursor.blockCharFormat()));
if (block == cell.lastCursorPosition().block())
{
break;
}
}
}
}
}
void RichTextEdit::applyCodeBlockInputFormat()
{
QTextTable *table = textCursor().currentTable();
if (!isCodeBlockTable(table))
{
return;
}
setCurrentCharFormat(codeBlockTextFormat(currentCharFormat()));
}
QUrl RichTextEdit::originalImageResourceUrl(const QString &name) const
{
QUrl url(name);
url.setFragment(QStringLiteral("cutex-original"));
return url;
}
QImage RichTextEdit::imageResource(QTextDocument *document, const QString &name) const
{
QImage image = document->resource(QTextDocument::ImageResource, originalImageResourceUrl(name)).value<QImage>();
if (image.isNull())
image = document->resource(QTextDocument::ImageResource, QUrl(name)).value<QImage>();
return image;
}
RichTextEdit::RichTextEdit(QWidget *parent):QxTextEdit(parent)
{
m_menu = new QMenu(this);
m_action_copy = new QAction(tr("复制"), m_menu);
m_action_save = new QAction(tr("另存为"), m_menu);
m_menu->addAction(m_action_copy);
m_menu->addAction(m_action_save);
connect(this, SIGNAL(imageRightClicked()), this, SLOT(sltImageRightClicked()));
connect(m_action_copy, SIGNAL(triggered()), this, SLOT(sltCopyImage()));
connect(m_action_save, SIGNAL(triggered()), this, SLOT(sltSaveImage()));
flattenInactivePalette();
qApp->installEventFilter(this);
}
void RichTextEdit::flattenInactivePalette()
{
QPalette p = QApplication::palette();
const QPalette::ColorRole roles[] = {
QPalette::Text, QPalette::Base, QPalette::WindowText,
QPalette::Window, QPalette::Highlight, QPalette::HighlightedText
};
for (QPalette::ColorRole role : roles)
{
p.setColor(QPalette::Inactive, role, p.color(QPalette::Active, role));
}
setPalette(p);
viewport()->setPalette(p);
viewport()->update();
}
void RichTextEdit::refreshImageResources()
{
QTextDocument* doc = document();
for (QTextBlock block = doc->begin(); block.isValid(); block = block.next())
{
for (QTextBlock::iterator it = block.begin(); !it.atEnd(); ++it)
{
QTextFragment fragment = it.fragment();
if (!fragment.isValid() || !fragment.charFormat().isImageFormat())
{
continue;
}
QTextImageFormat fmt = fragment.charFormat().toImageFormat();
QString name = fmt.name();
if (name.isEmpty())
{
continue;
}
QUrl imageUrl(name);
QUrl originalUrl = originalImageResourceUrl(name);
QImage image = doc->resource(QTextDocument::ImageResource, originalUrl).value<QImage>();
if (image.isNull())
{
image = doc->resource(QTextDocument::ImageResource, imageUrl).value<QImage>();
if (!image.isNull())
{
doc->addResource(QTextDocument::ImageResource, originalUrl, image);
}
}
if (image.isNull())
{
continue;
}
double width = fmt.width();
double height = fmt.height();
if (width <= 0.0)
{
width = image.width();
}
if (height <= 0.0)
{
height = image.height();
}
QSize targetSize(qMax(1, qRound(width)), qMax(1, qRound(height)));
QImage displayImage = image;
if (targetSize != image.size())
{
displayImage = image.scaled(targetSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
doc->addResource(QTextDocument::ImageResource, imageUrl, displayImage);
}
}
doc->markContentsDirty(0, doc->characterCount());
viewport()->update();
}
void RichTextEdit::refreshChecklistFormats()
{
// 加载 HTML、整篇字体变化、保存还原后都需要重新校正待办的 marker 和正文状态。
QTextDocument* doc = document();
for (QTextBlock block = doc->begin(); block.isValid(); block = block.next())
{
refreshChecklistBlockFormats(doc, block);
}
}
void RichTextEdit::refreshCodeBlockFormats()
{
QTextFrame *rootFrame = document()->rootFrame();
if (!rootFrame)
{
return;
}
for (QTextFrame::iterator it = rootFrame->begin(); !it.atEnd(); ++it)
{
QTextFrame *childFrame = it.currentFrame();
QTextTable *table = dynamic_cast<QTextTable *>(childFrame);
refreshCodeBlockTableFormats(table);
}
applyCodeBlockInputFormat();
}
bool RichTextEdit::eventFilter(QObject *watched, QEvent *event)
{
if (watched == qApp && event->type() == QEvent::ApplicationPaletteChange)
{
flattenInactivePalette();
}
return QxTextEdit::eventFilter(watched, event);
}
void RichTextEdit::mousePressEvent(QMouseEvent *event)
{
QTextCursor clickCursor = cursorForPosition(event->pos());
QTextBlock block = clickCursor.block();
// 只响应 checkbox 字符附近的点击,避免点到正文开头也误触发勾选。
if (event->button() == Qt::LeftButton && block.isValid() && blockHasChecklistPrefix(block) &&
checklistMarkerHitRect(block).contains(event->pos()))
{
QTextCursor cursor(document());
cursor.beginEditBlock();
cursor.setPosition(block.position());
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
QString mark = cursor.selectedText();
if (mark == QString(checklistUncheckedChar()))
{
cursor.insertText(QString(checklistCheckedChar()));
refreshChecklistBlockFormats(document(), block);
cursor.endEditBlock();
return;
}
if (mark == QString(checklistCheckedChar()))
{
cursor.insertText(QString(checklistUncheckedChar()));
refreshChecklistBlockFormats(document(), block);
cursor.endEditBlock();
return;
}
cursor.endEditBlock();
}
QxTextEdit::mousePressEvent(event);
}
void RichTextEdit::keyPressEvent(QKeyEvent *event)
{
if (!textCursor().hasSelection() && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter))
{
QTextCursor cursor = textCursor();
QTextBlock block = cursor.block();
if (blockHasChecklistPrefix(block))
{
if (blockIsEmptyChecklist(block))
{
// 空待办回车表示退出待办模式,删除 marker 和可选空格。
int removeSize = checklistBodyStartOffset(block.text());
cursor.beginEditBlock();
cursor.setPosition(block.position());
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, removeSize);
cursor.removeSelectedText();
QTextCharFormat charFormat = currentCharFormat();
charFormat.setFontStrikeOut(false);
setCurrentCharFormat(charFormat);
QTextCharFormat blockCharFormat = cursor.blockCharFormat();
blockCharFormat.setFontStrikeOut(false);
cursor.setBlockCharFormat(blockCharFormat);
cursor.endEditBlock();
setTextCursor(cursor);
return;
}
QxTextEdit::keyPressEvent(event);
cursor = textCursor();
// 新建下一条待办前清掉删除线状态,避免勾选项回车后新行继承删除线。
QTextCharFormat charFormat = currentCharFormat();
charFormat.setFontStrikeOut(false);
setCurrentCharFormat(charFormat);
QTextCharFormat blockCharFormat = cursor.blockCharFormat();
blockCharFormat.setFontStrikeOut(false);
cursor.setBlockCharFormat(blockCharFormat);
cursor.insertText(checklistPrefix(false));
refreshChecklistBlockFormats(document(), cursor.block());
setTextCursor(cursor);
return;
}
}
if (!textCursor().hasSelection())
{
// 普通键盘输入前先修正输入格式,处理“删掉 checkbox 后空格再打字”的情况。
applyChecklistInputFormat();
applyCodeBlockInputFormat();
}
int revision = document()->revision();
QxTextEdit::keyPressEvent(event);
if (document()->revision() != revision)
{
refreshChecklistBlockFormats(document(), textCursor().block());
refreshCodeBlockTableFormats(textCursor().currentTable());
}
}
void RichTextEdit::inputMethodEvent(QInputMethodEvent *event)
{
if (!textCursor().hasSelection())
{
// 中文输入法不一定走 keyPressEvent,也需要在 IME 提交前修正输入格式。
applyChecklistInputFormat();
applyCodeBlockInputFormat();
}
int revision = document()->revision();
QxTextEdit::inputMethodEvent(event);
if (document()->revision() != revision)
{
refreshChecklistBlockFormats(document(), textCursor().block());
refreshCodeBlockTableFormats(textCursor().currentTable());
}
}
void RichTextEdit::sltImageRightClicked()
{
m_menu->popup(QCursor::pos());
}
void RichTextEdit::sltCopyImage()
{
QTextCursor cursor = textCursor();
if (!cursor.hasSelection() && cursor.charFormat().isImageFormat()) {
QTextImageFormat fmt = cursor.charFormat().toImageFormat();
QImage image = imageResource(document(), fmt.name());
QClipboard* clip = QApplication::clipboard();
clip->setImage(image);
}
}
void RichTextEdit::sltSaveImage()
{
QTextCursor cursor = textCursor();
if (!cursor.hasSelection() && cursor.charFormat().isImageFormat()) {
QTextImageFormat fmt = cursor.charFormat().toImageFormat();
QImage image = imageResource(document(), fmt.name());
QString filePath = QFileDialog::getSaveFileName(this, tr("图片另存为"), tr("图片"), tr("Image (*.png)"));
if (filePath.isEmpty())
{
return;
}
image.save(filePath, "png");
}
}
void RichTextEdit::dealBackTab()
{
QTextCursor cur = textCursor();
int pos = cur.position();
int anchor = cur.anchor();
cur.setPosition(pos);
cur.setPosition(pos-1,QTextCursor::KeepAnchor);
if (cur.selectedText() == "\t")
{
cur.removeSelectedText();
cur.setPosition(anchor-1);
cur.setPosition(pos-1,QTextCursor::KeepAnchor);
}
else
{
cur.setPosition(anchor);
cur.setPosition(anchor-1,QTextCursor::KeepAnchor);
if (cur.selectedText() == "\t")
{
cur.removeSelectedText();
cur.setPosition(anchor-1);
cur.setPosition(pos-1,QTextCursor::KeepAnchor);
}
else
{
cur.setPosition(anchor);
cur.setPosition(pos,QTextCursor::KeepAnchor);
}
}
}