Repository navigation
Expand file tree
/
Copy pathtermwidget.cpp
More file actions
1637 lines (1464 loc) · 48.9 KB
/
Copy pathtermwidget.cpp
File metadata and controls
1637 lines (1464 loc) · 48.9 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
#include "termwidget.h"
#include <QApplication>
#include <QClipboard>
#include <QContextMenuEvent>
#include <QFontDatabase>
#include <QFontMetricsF>
#include <QGuiApplication>
#include <QInputMethodEvent>
#include <QKeyEvent>
#include <QKeySequence>
#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QScrollBar>
#include <QSignalBlocker>
#include <QWheelEvent>
#include <cmath>
#include <cstring>
#include "termpalette.h"
#include "terminalsettings.h"
namespace {
const int kRepaintIntervalMs = 8;
const int kCursorBlinkIntervalMs = 500;
const int kScrollStep = 3;
QString cellText(const VTermScreenCell &cell) {
QString text;
for (int i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i) {
const uint32_t codePoint = cell.chars[i];
if (codePoint == 0) {
break;
}
if (codePoint == 0xFFFFFFFFu) { // wide-char continuation marker
continue;
}
uint unit = codePoint;
text.append(QString::fromUcs4(&unit, 1));
}
return text;
}
bool isWideContinuation(const VTermScreenCell &cell) {
return cell.chars[0] == 0xFFFFFFFFu;
}
bool isWideCodePoint(uint codePoint) {
return (codePoint >= 0x1100 && codePoint <= 0x115F) ||
(codePoint >= 0x2E80 && codePoint <= 0x303E) ||
(codePoint >= 0x3041 && codePoint <= 0x33FF) ||
(codePoint >= 0x3400 && codePoint <= 0x4DBF) ||
(codePoint >= 0x4E00 && codePoint <= 0x9FFF) ||
(codePoint >= 0xA000 && codePoint <= 0xA4CF) ||
(codePoint >= 0xAC00 && codePoint <= 0xD7A3) ||
(codePoint >= 0xF900 && codePoint <= 0xFAFF) ||
(codePoint >= 0xFE30 && codePoint <= 0xFE4F) ||
(codePoint >= 0xFF00 && codePoint <= 0xFF60) ||
(codePoint >= 0xFFE0 && codePoint <= 0xFFE6) ||
(codePoint >= 0x1F300 && codePoint <= 0x1F64F) ||
(codePoint >= 0x20000 && codePoint <= 0x3FFFD);
}
bool isCombiningCodePoint(uint codePoint) {
return (codePoint >= 0x0300 && codePoint <= 0x036F) ||
(codePoint >= 0x1AB0 && codePoint <= 0x1AFF) ||
(codePoint >= 0x20D0 && codePoint <= 0x20FF) ||
(codePoint >= 0xFE20 && codePoint <= 0xFE2F);
}
int codePointWidth(uint codePoint) {
if (codePoint == 0) {
return 0;
}
if (isCombiningCodePoint(codePoint)) {
return 0;
}
return isWideCodePoint(codePoint) ? 2 : 1;
}
// Length of the longest prefix of |data| that ends on a UTF-8 character
// boundary. libvterm keeps decoder state per encoding instance, and a text
// run that starts with an ASCII byte uses a different instance than a run that
// starts with a continuation byte, so callers must not split a sequence.
int completeUtf8Prefix(const QByteArray &data) {
const int size = data.size();
if (size == 0) {
return 0;
}
int leadIndex = size - 1;
int continuationCount = 0;
while (leadIndex >= 0 &&
(static_cast<unsigned char>(data.at(leadIndex)) & 0xC0) == 0x80) {
--leadIndex;
++continuationCount;
if (continuationCount > 3) {
return size; // bogus data, let libvterm deal with it
}
}
if (leadIndex < 0) {
return size; // only continuation bytes: not ours to judge
}
const unsigned char lead = static_cast<unsigned char>(data.at(leadIndex));
int expected = 0;
if (lead < 0x80) {
expected = 1;
} else if ((lead & 0xE0) == 0xC0) {
expected = 2;
} else if ((lead & 0xF0) == 0xE0) {
expected = 3;
} else if ((lead & 0xF8) == 0xF0) {
expected = 4;
} else {
return size; // invalid lead byte: pass everything through
}
const int available = size - leadIndex;
if (available < expected) {
return leadIndex; // hold the partial sequence back
}
return size;
}
} // namespace
TerminalWidget::TerminalWidget(QWidget *parent) : QWidget(parent) {
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_InputMethodEnabled);
setAttribute(Qt::WA_KeyCompression, false);
setFocusPolicy(Qt::StrongFocus);
setMouseTracking(true);
setCursor(Qt::IBeamCursor);
glyphCacheEnabled_ = qgetenv("TERMWIDGET_NO_GLYPH_CACHE").isEmpty();
chooseDefaultFont();
updateCellMetrics();
initTerminal(rows_, cols_);
scrollBar_ = new QScrollBar(Qt::Vertical, this);
scrollBar_->setRange(0, 0);
scrollBar_->setSingleStep(1);
scrollBar_->setFocusPolicy(Qt::NoFocus);
connect(scrollBar_, &QScrollBar::valueChanged, this, [this](int value) {
// Scrollbar value grows downwards (0 = oldest line at the top), while
// scrollOffset_ counts lines up from the newest line, so invert.
const int offset = scrollBar_->maximum() - value;
if (offset == scrollOffset_) {
return;
}
scrollOffset_ = offset;
update();
});
repaintTimer_.setSingleShot(true);
repaintTimer_.setInterval(kRepaintIntervalMs);
connect(&repaintTimer_, &QTimer::timeout, this, &TerminalWidget::flushRepaint);
cursorTimer_.setInterval(kCursorBlinkIntervalMs);
connect(&cursorTimer_, &QTimer::timeout, this, [this]() {
if (!cursorBlink_ || !cursorVisible_ || !hasFocus() || scrollOffset_ != 0) {
return;
}
cursorOn_ = !cursorOn_;
const QRect cursor = cursorRect();
if (!cursor.isEmpty()) {
update(cursor);
}
});
cursorTimer_.start();
}
TerminalWidget::~TerminalWidget() {
if (vt_) {
vterm_free(vt_);
vt_ = nullptr;
screen_ = nullptr;
state_ = nullptr;
}
}
// ---------------------------------------------------------------------------
// setup
// ---------------------------------------------------------------------------
void TerminalWidget::chooseDefaultFont() {
const QStringList available = QFontDatabase().families();
QFont font = TerminalSettings::defaultFont();
font_ = font;
boldFont_ = font;
boldFont_.setBold(true);
// CJK glyphs are drawn with their own font, scaled in updateCellMetrics() so
// that one full-width glyph covers exactly two cells even when no mono CJK
// font is installed (the common case on stock Linux/Windows systems).
const QStringList cjkCandidates = {
QStringLiteral("Sarasa Mono SC"), QStringLiteral("Sarasa Term SC"),
QStringLiteral("Noto Sans Mono CJK SC"), QStringLiteral("Sarasa Mono TC"),
QStringLiteral("Microsoft YaHei"), QStringLiteral("Noto Sans CJK SC"),
QStringLiteral("Source Han Sans SC"), QStringLiteral("WenQuanYi Micro Hei"),
QStringLiteral("PingFang SC"), QStringLiteral("Hiragino Sans GB")};
QString cjkFamily;
for (const QString &candidate : cjkCandidates) {
if (available.contains(candidate, Qt::CaseInsensitive)) {
cjkFamily = candidate;
break;
}
}
if (cjkFamily.isEmpty()) {
cjkFamily = font_.family();
}
QFont cjkFont(cjkFamily);
cjkFont.setPointSize(11);
cjkFont.setKerning(false);
cjkBaseFont_ = cjkFont;
cjkFont_ = cjkFont;
}
void TerminalWidget::updateCellMetrics() {
const QFontMetricsF metrics(font_);
cellWidth_ = qMax<qreal>(1.0, metrics.horizontalAdvance(QStringLiteral("W")));
cellHeight_ = qMax<qreal>(1.0, std::ceil(metrics.height()));
fontAscent_ = metrics.ascent();
// Scale the CJK font so a full-width glyph is exactly 2 cells wide.
cjkFont_ = cjkBaseFont_;
const QFontMetricsF cjkMetrics(cjkFont_);
const qreal cjkAdvance =
cjkMetrics.horizontalAdvance(QString(QChar(0x4E2D))); // U+4E2D 中
if (cjkAdvance > 0.1) {
const qreal factor = (2.0 * cellWidth_) / cjkAdvance;
if (qAbs(factor - 1.0) > 0.02 && factor > 0.1) {
cjkFont_.setPointSizeF(qMax<qreal>(4.0, cjkFont_.pointSizeF() * factor));
}
}
}
void TerminalWidget::initTerminal(int rows, int cols) {
rows_ = qMax(1, rows);
cols_ = qMax(1, cols);
vt_ = vterm_new(rows_, cols_);
vterm_set_utf8(vt_, 1);
screen_ = vterm_obtain_screen(vt_);
state_ = vterm_obtain_state(vt_);
static const VTermScreenCallbacks screenCallbacks = {
&TerminalWidget::cbDamage, &TerminalWidget::cbMoveRect,
&TerminalWidget::cbMoveCursor, &TerminalWidget::cbSetTermProp,
&TerminalWidget::cbBell, &TerminalWidget::cbResize,
&TerminalWidget::cbPushLine, &TerminalWidget::cbPopLine,
&TerminalWidget::cbClearScrollback};
vterm_screen_set_callbacks(screen_, &screenCallbacks, this);
vterm_screen_set_damage_merge(screen_, VTERM_DAMAGE_ROW);
vterm_screen_enable_altscreen(screen_, 1);
vterm_screen_enable_reflow(screen_, true);
vterm_output_set_callback(vt_, &TerminalWidget::cbOutput, this);
// OSC 52 (clipboard) support: libvterm base64-decodes into this buffer.
static const VTermSelectionCallbacks selectionCallbacks = {
&TerminalWidget::cbSelectionSet, &TerminalWidget::cbSelectionQuery};
vterm_state_set_selection_callbacks(state_, &selectionCallbacks, this,
oscSelectionStorage_,
sizeof(oscSelectionStorage_));
vterm_state_set_bold_highbright(state_, 1);
applyPaletteAndColors();
vterm_screen_reset(screen_, 1);
}
void TerminalWidget::applyPaletteAndColors() {
if (!state_ || !screen_) {
return;
}
const QColor *palette = terminalPalette();
for (int i = 0; i < 256; ++i) {
VTermColor color;
vterm_color_rgb(&color, uint8_t(palette[i].red()), uint8_t(palette[i].green()),
uint8_t(palette[i].blue()));
vterm_state_set_palette_color(state_, i, &color);
}
VTermColor fg;
VTermColor bg;
vterm_color_rgb(&fg, uint8_t(defaultFg_.red()), uint8_t(defaultFg_.green()),
uint8_t(defaultFg_.blue()));
vterm_color_rgb(&bg, uint8_t(defaultBg_.red()), uint8_t(defaultBg_.green()),
uint8_t(defaultBg_.blue()));
vterm_state_set_default_colors(state_, &fg, &bg);
vterm_screen_set_default_colors(screen_, &fg, &bg);
}
void TerminalWidget::setTerminalFont(const QFont &font) {
font_ = font;
font_.setStyleHint(QFont::Monospace);
font_.setFixedPitch(true);
boldFont_ = font_;
boldFont_.setBold(true);
// If the chosen family covers CJK, draw wide cells with it directly;
// otherwise keep the fallback CJK family and follow the new point size.
if (QFontMetricsF(font_).inFont(QChar(0x4E2D))) {
cjkBaseFont_ = font_;
cjkBaseFont_.setBold(false);
} else {
cjkBaseFont_.setPointSizeF(font_.pointSizeF());
}
updateCellMetrics();
clearGlyphCache();
recalcSize();
update();
}
void TerminalWidget::setFontPointSize(qreal pointSize) {
QFont font = font_;
font.setPointSizeF(pointSize);
setTerminalFont(font);
}
void TerminalWidget::setColorScheme(const QColor &foreground,
const QColor &background) {
defaultFg_ = foreground;
defaultBg_ = background;
applyPaletteAndColors();
clearGlyphCache();
update();
}
void TerminalWidget::setScrollbackLimit(int lines) {
scrollbackLimit_ = qBound(0, lines, 100000);
const int overflow = int(scrollback_.size()) - scrollbackLimit_;
if (overflow > 0) {
scrollback_.erase(scrollback_.begin(), scrollback_.begin() + overflow);
clearSelection();
}
updateScrollBar();
update();
}
// ---------------------------------------------------------------------------
// data in
// ---------------------------------------------------------------------------
void TerminalWidget::feed(const QByteArray &bytes) {
if (!vt_ || bytes.isEmpty()) {
return;
}
utf8Pending_.append(bytes);
const int completeLength = completeUtf8Prefix(utf8Pending_);
if (completeLength <= 0) {
if (utf8Pending_.size() > 4) { // give up on malformed input
vterm_input_write(vt_, utf8Pending_.constData(), size_t(utf8Pending_.size()));
utf8Pending_.clear();
vterm_screen_flush_damage(screen_);
scheduleRepaint();
}
return;
}
vterm_input_write(vt_, utf8Pending_.constData(), size_t(completeLength));
if (completeLength < utf8Pending_.size()) {
utf8Pending_.remove(0, completeLength);
} else {
utf8Pending_.clear();
}
vterm_screen_flush_damage(screen_);
scheduleRepaint();
}
// ---------------------------------------------------------------------------
// geometry
// ---------------------------------------------------------------------------
void TerminalWidget::resizeEvent(QResizeEvent *event) {
QWidget::resizeEvent(event);
recalcSize();
}
void TerminalWidget::recalcSize() {
if (!vt_) {
return;
}
const int scrollBarWidth = scrollBar_ ? scrollBar_->sizeHint().width() : 0;
if (scrollBar_) {
scrollBar_->setGeometry(width() - scrollBarWidth, 0, scrollBarWidth, height());
}
const int availableWidth = qMax(1, width() - scrollBarWidth);
const int availableHeight = qMax(1, height());
const int newCols = qMax(1, int(availableWidth / cellWidth_));
const int newRows = qMax(1, int(availableHeight / cellHeight_));
if (newCols == cols_ && newRows == rows_) {
updateScrollBar();
return;
}
cols_ = newCols;
rows_ = newRows;
vterm_set_size(vt_, rows_, cols_);
updateScrollBar();
update();
emit sizeChanged(cols_, rows_);
}
int TerminalWidget::globalLineForViewportRow(int viewportRow) const {
return int(scrollback_.size()) + viewportRow - scrollOffset_;
}
bool TerminalWidget::cellAtGlobal(int globalLine, int column,
VTermScreenCell *cell) const {
if (!cell || column < 0 || column >= cols_ || globalLine < 0) {
return false;
}
const int scrollbackCount = int(scrollback_.size());
if (globalLine < scrollbackCount) {
const QVector<VTermScreenCell> &line = scrollback_.at(size_t(globalLine));
if (column >= line.size()) {
return false;
}
*cell = line.at(column);
return true;
}
const int screenRow = globalLine - scrollbackCount;
if (screenRow >= rows_) {
return false;
}
VTermPos pos;
pos.row = screenRow;
pos.col = column;
return vterm_screen_get_cell(screen_, pos, cell) != 0;
}
bool TerminalWidget::cellAtViewport(int viewportRow, int column,
VTermScreenCell *cell) const {
return cellAtGlobal(globalLineForViewportRow(viewportRow), column, cell);
}
QPoint TerminalWidget::cellAtPosition(const QPoint &position) const {
const int column = qBound(0, int(position.x() / cellWidth_), cols_ - 1);
const int row = qBound(0, int(position.y() / cellHeight_), rows_ - 1);
return QPoint(column, row);
}
QRect TerminalWidget::cursorRect() const {
if (!vt_ || scrollOffset_ != 0) {
return QRect();
}
VTermPos pos;
vterm_state_get_cursorpos(state_, &pos);
if (pos.row < 0 || pos.row >= rows_ || pos.col < 0 || pos.col >= cols_) {
return QRect();
}
return QRect(qRound(pos.col * cellWidth_), qRound(pos.row * cellHeight_),
int(std::ceil(cellWidth_)), int(std::ceil(cellHeight_)));
}
QSize TerminalWidget::sizeHint() const {
return QSize(int(std::ceil(cols_ * cellWidth_)),
int(std::ceil(rows_ * cellHeight_)));
}
QSize TerminalWidget::minimumSizeHint() const {
return QSize(int(std::ceil(20 * cellWidth_)),
int(std::ceil(5 * cellHeight_)));
}
// ---------------------------------------------------------------------------
// painting
// ---------------------------------------------------------------------------
QColor TerminalWidget::colorFor(const VTermColor &color, bool background) const {
return terminalColor(color, defaultFg_, defaultBg_);
}
void TerminalWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.fillRect(event->rect(), defaultBg_);
const qreal devicePixelRatio = devicePixelRatioF();
if (devicePixelRatio != glyphCacheDpr_) {
glyphCache_.clear();
glyphCacheDpr_ = devicePixelRatio;
}
painter.setRenderHint(QPainter::TextAntialiasing, true);
const int scrollbackCount = int(scrollback_.size());
const int totalLines = scrollbackCount + rows_;
const QRect clip = event->rect();
for (int viewportRow = 0; viewportRow < rows_; ++viewportRow) {
const qreal y = viewportRow * cellHeight_;
if (y + cellHeight_ < clip.top() || y > clip.bottom()) {
continue;
}
const int globalLine = globalLineForViewportRow(viewportRow);
if (globalLine < 0 || globalLine >= totalLines) {
continue;
}
drawLine(&painter, viewportRow, globalLine);
}
drawSelection(&painter);
drawCursor(&painter);
drawPreedit(&painter);
}
void TerminalWidget::drawLine(QPainter *painter, int viewportRow,
int globalLine) {
const qreal y = viewportRow * cellHeight_;
const qreal baseline = y + fontAscent_;
for (int column = 0; column < cols_;) {
VTermScreenCell cell;
if (!cellAtGlobal(globalLine, column, &cell)) {
break;
}
if (isWideContinuation(cell)) {
++column;
continue;
}
const int width = (cell.width == 2 && column + 1 < cols_) ? 2 : 1;
const QRectF cellRect(column * cellWidth_, y, width * cellWidth_, cellHeight_);
QColor fg = colorFor(cell.fg, false);
QColor bg = colorFor(cell.bg, true);
if (cell.attrs.reverse) {
qSwap(fg, bg);
}
if (cell.attrs.conceal) {
fg = bg;
}
if (bg != defaultBg_) {
painter->fillRect(cellRect, bg);
}
if (cell.chars[0] != 0) {
const QString text = cellText(cell);
if (glyphCacheEnabled_) {
const QPixmap &glyph = glyphPixmap(text, width, cell.attrs.bold, fg,
devicePixelRatioF());
painter->drawPixmap(QPointF(cellRect.left(), cellRect.top()), glyph);
} else {
painter->setPen(fg);
if (width == 2) {
painter->setFont(cjkFont_);
painter->drawText(cellRect, Qt::AlignHCenter | Qt::AlignVCenter, text);
} else {
painter->setFont(cell.attrs.bold ? boldFont_ : font_);
painter->drawText(QPointF(cellRect.left(), baseline), text);
}
}
if (cell.attrs.underline) {
const qreal underlineY = baseline + qMax<qreal>(1.0, cellHeight_ / 12);
painter->drawLine(QPointF(cellRect.left(), underlineY),
QPointF(cellRect.right(), underlineY));
}
if (cell.attrs.strike) {
const qreal strikeY = y + cellHeight_ / 2;
painter->drawLine(QPointF(cellRect.left(), strikeY),
QPointF(cellRect.right(), strikeY));
}
}
column += width;
}
}
void TerminalWidget::drawSelection(QPainter *painter) {
if (!hasSelection_) {
return;
}
painter->setPen(Qt::NoPen);
painter->setBrush(selectionColor_);
for (int viewportRow = 0; viewportRow < rows_; ++viewportRow) {
const int line = globalLineForViewportRow(viewportRow);
if (line < selectionStartLine_ || line > selectionEndLine_) {
continue;
}
const int startColumn = (line == selectionStartLine_) ? selectionStartColumn_ : 0;
const int endColumn = (line == selectionEndLine_) ? selectionEndColumn_ : cols_ - 1;
if (endColumn < startColumn) {
continue;
}
painter->drawRect(QRectF(startColumn * cellWidth_, viewportRow * cellHeight_,
(endColumn - startColumn + 1) * cellWidth_,
cellHeight_));
}
}
void TerminalWidget::drawCursor(QPainter *painter) {
if (scrollOffset_ != 0 || !cursorVisible_ || !cursorOn_ || !hasFocus() ||
!preeditString_.isEmpty()) { // the preedit overlay owns the caret
return;
}
VTermPos pos;
vterm_state_get_cursorpos(state_, &pos);
if (pos.row < 0 || pos.row >= rows_ || pos.col < 0 || pos.col >= cols_) {
return;
}
const QRectF rect(pos.col * cellWidth_, pos.row * cellHeight_, cellWidth_,
cellHeight_);
const QColor color = cursorColor_.isValid() ? cursorColor_ : defaultFg_;
switch (cursorShape_) {
case VTERM_PROP_CURSORSHAPE_UNDERLINE: {
const qreal thickness = qMax<qreal>(1.0, cellHeight_ / 12);
painter->fillRect(QRectF(rect.left(), rect.bottom() - thickness,
rect.width(), thickness),
color);
break;
}
case VTERM_PROP_CURSORSHAPE_BAR_LEFT: {
const qreal thickness = qMax<qreal>(1.0, cellWidth_ / 8);
painter->fillRect(QRectF(rect.left(), rect.top(), thickness, rect.height()),
color);
break;
}
default: {
painter->fillRect(rect, color);
VTermScreenCell cell;
if (cellAtViewport(pos.row, pos.col, &cell) && cell.chars[0] != 0 &&
!isWideContinuation(cell)) {
painter->setFont(cell.width == 2 ? cjkFont_ : font_);
painter->setPen(defaultBg_);
painter->drawText(QPointF(rect.left(), pos.row * cellHeight_ + fontAscent_),
cellText(cell));
}
break;
}
}
}
void TerminalWidget::clearGlyphCache() { glyphCache_.clear(); }
QPixmap TerminalWidget::glyphPixmap(const QString &text, int cells, bool bold,
const QColor &color,
qreal devicePixelRatio) {
const quint64 meta = (quint64(color.rgba()) << 16) |
(quint64(cells & 0x3) << 3) | (bold ? 2u : 0u) |
(devicePixelRatio >= 2.0 ? 1u : 0u);
const QPair<QString, quint64> key(text, meta);
const auto cached = glyphCache_.constFind(key);
if (cached != glyphCache_.constEnd()) {
return cached.value();
}
const qreal scale = devicePixelRatio >= 1.0 ? devicePixelRatio : 1.0;
const int pixelWidth = qMax(1, int(std::ceil(cells * cellWidth_ * scale)));
const int pixelHeight = qMax(1, int(std::ceil(cellHeight_ * scale)));
QPixmap pixmap(pixelWidth, pixelHeight);
pixmap.setDevicePixelRatio(scale);
pixmap.fill(Qt::transparent);
{
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::TextAntialiasing, true);
painter.setPen(color);
if (cells > 1) {
painter.setFont(cjkFont_);
painter.drawText(QRectF(0, 0, cells * cellWidth_, cellHeight_),
Qt::AlignHCenter | Qt::AlignVCenter, text);
} else {
painter.setFont(bold ? boldFont_ : font_);
painter.drawText(QPointF(0, fontAscent_), text);
}
}
if (glyphCache_.size() >= 4096) {
glyphCache_.clear(); // crude but keeps the cache bounded
}
glyphCache_.insert(key, pixmap);
return pixmap;
}
void TerminalWidget::drawPreedit(QPainter *painter) {
if (preeditString_.isEmpty() || scrollOffset_ != 0 || !vt_) {
return;
}
VTermPos pos;
vterm_state_get_cursorpos(state_, &pos);
if (pos.row < 0 || pos.row >= rows_ || pos.col < 0 || pos.col >= cols_) {
return;
}
const QVector<uint> codePoints = preeditString_.toUcs4();
int totalCells = 0;
for (uint codePoint : codePoints) {
totalCells += codePointWidth(codePoint);
}
const int cells = qMin(totalCells, cols_ - pos.col);
if (cells <= 0) {
return;
}
const QRectF background(pos.col * cellWidth_, pos.row * cellHeight_,
cells * cellWidth_, cellHeight_);
painter->fillRect(background, defaultBg_);
painter->setFont(font_);
painter->setPen(defaultFg_);
qreal x = background.left();
int drawnCells = 0;
for (uint codePoint : codePoints) {
const int width = codePointWidth(codePoint);
if (drawnCells + width > cells) {
break;
}
if (width > 0) {
uint unit = codePoint;
const QString glyph = QString::fromUcs4(&unit, 1);
if (width == 2) {
painter->setFont(cjkFont_);
painter->drawText(QRectF(x, background.top(), width * cellWidth_,
cellHeight_),
Qt::AlignHCenter | Qt::AlignVCenter, glyph);
painter->setFont(font_);
} else {
painter->drawText(QPointF(x, background.top() + fontAscent_), glyph);
}
const qreal underlineY = background.bottom() - 1;
painter->drawLine(QPointF(x, underlineY),
QPointF(x + width * cellWidth_ - 1, underlineY));
}
x += width * cellWidth_;
drawnCells += width;
}
if (preeditCursorVisible_) {
int caretCells = 0;
int utf16Position = 0;
for (uint codePoint : codePoints) {
if (utf16Position >= preeditCursorPosition_) {
break;
}
caretCells += codePointWidth(codePoint);
utf16Position += (codePoint >= 0x10000) ? 2 : 1;
}
painter->fillRect(QRectF(background.left() + caretCells * cellWidth_,
background.top(),
qMax<qreal>(1.0, cellWidth_ / 8), cellHeight_),
defaultFg_);
}
}
void TerminalWidget::clearPreedit() {
if (preeditString_.isEmpty() && preeditAttributes_.isEmpty()) {
return;
}
preeditString_.clear();
preeditAttributes_.clear();
preeditCursorVisible_ = false;
preeditCursorPosition_ = 0;
update();
}
// ---------------------------------------------------------------------------
// damage tracking
// ---------------------------------------------------------------------------
void TerminalWidget::addDamage(const VTermRect &rect) {
if (rect.end_row <= rect.start_row || rect.end_col <= rect.start_col) {
return;
}
const QRect cells(rect.start_col, rect.start_row, rect.end_col - rect.start_col,
rect.end_row - rect.start_row);
dirtyCells_ = dirtyCells_.isNull() ? cells : dirtyCells_.united(cells);
scheduleRepaint();
}
void TerminalWidget::addCellDamage(int row, int column) {
VTermRect rect;
rect.start_row = row;
rect.end_row = row + 1;
rect.start_col = column;
rect.end_col = column + 1;
addDamage(rect);
}
void TerminalWidget::scheduleRepaint() {
if (!repaintTimer_.isActive()) {
repaintTimer_.start();
}
}
void TerminalWidget::flushRepaint() {
if (!preeditString_.isEmpty()) {
dirtyCells_ = QRect();
update();
return;
}
if (dirtyCells_.isNull()) {
update();
return;
}
const QRectF pixelRect(
dirtyCells_.left() * cellWidth_,
(dirtyCells_.top() + scrollOffset_) * cellHeight_,
dirtyCells_.width() * cellWidth_, dirtyCells_.height() * cellHeight_);
const QRect aligned = pixelRect.toAlignedRect().intersected(rect());
dirtyCells_ = QRect();
if (aligned.isEmpty()) {
update();
} else {
update(aligned);
}
}
void TerminalWidget::onCursorMoved(const VTermPos &oldPos, const VTermPos &pos) {
if (oldPos.row >= 0 && oldPos.row < rows_ && oldPos.col >= 0 && oldPos.col < cols_) {
addCellDamage(oldPos.row, oldPos.col);
}
if (pos.row >= 0 && pos.row < rows_ && pos.col >= 0 && pos.col < cols_) {
addCellDamage(pos.row, pos.col);
}
cursorOn_ = true;
scheduleRepaint();
}
// ---------------------------------------------------------------------------
// scrolling
// ---------------------------------------------------------------------------
void TerminalWidget::updateScrollBar() {
if (!scrollBar_) {
return;
}
const int maximum = qMax(0, int(scrollback_.size()));
QSignalBlocker blocker(scrollBar_);
scrollBar_->setRange(0, maximum);
scrollBar_->setPageStep(qMax(1, rows_));
if (scrollOffset_ > maximum) {
scrollOffset_ = maximum;
}
scrollBar_->setValue(maximum - scrollOffset_);
}
void TerminalWidget::scrollBy(int lines) {
const int maximum = int(scrollback_.size());
const int target = qBound(0, scrollOffset_ + lines, maximum);
if (target == scrollOffset_) {
return;
}
scrollOffset_ = target;
updateScrollBar();
update();
}
void TerminalWidget::scrollToBottom() {
if (scrollOffset_ == 0) {
return;
}
scrollOffset_ = 0;
updateScrollBar();
update();
}
void TerminalWidget::clearScrollback() {
scrollback_.clear();
scrollOffset_ = 0;
clearSelection();
updateScrollBar();
update();
}
// ---------------------------------------------------------------------------
// input
// ---------------------------------------------------------------------------
VTermModifier TerminalWidget::toVTermModifier(Qt::KeyboardModifiers modifiers) {
int result = VTERM_MOD_NONE;
if (modifiers & Qt::ShiftModifier) {
result |= VTERM_MOD_SHIFT;
}
if (modifiers & Qt::AltModifier) {
result |= VTERM_MOD_ALT;
}
if (modifiers & Qt::ControlModifier) {
result |= VTERM_MOD_CTRL;
}
return VTermModifier(result);
}
void TerminalWidget::sendKey(VTermKey key, Qt::KeyboardModifiers modifiers) {
scrollToBottom(); // typing always brings the live prompt back into view
vterm_keyboard_key(vt_, key, toVTermModifier(modifiers));
}
void TerminalWidget::sendText(const QString &text,
Qt::KeyboardModifiers modifiers) {
if (text.isEmpty()) {
return;
}
scrollToBottom();
const QVector<uint> codePoints = text.toUcs4();
const VTermModifier modifier = toVTermModifier(modifiers);
for (int i = 0; i < codePoints.size(); ++i) {
vterm_keyboard_unichar(vt_, codePoints.at(i), modifier);
}
}
void TerminalWidget::keyPressEvent(QKeyEvent *event) {
const Qt::KeyboardModifiers modifiers = event->modifiers();
const bool control = modifiers.testFlag(Qt::ControlModifier);
const bool shift = modifiers.testFlag(Qt::ShiftModifier);
// Clipboard / selection shortcuts take precedence over terminal input.
if (control && shift) {
switch (event->key()) {
case Qt::Key_C:
copySelection();
return;
case Qt::Key_V:
paste();
return;
case Qt::Key_A:
selectAll();
return;
case Qt::Key_Home:
scrollBy(int(scrollback_.size())); // newest page of history
return;
case Qt::Key_End:
scrollToBottom();
return;
default:
break;
}
}
// Shift+PageUp/PageDown browse the scrollback instead of being sent to the
// application (same convention as xterm).
if (shift && !control && !modifiers.testFlag(Qt::AltModifier)) {
if (event->key() == Qt::Key_PageUp) {
scrollBy(qMax(1, rows_ - 1));
return;
}
if (event->key() == Qt::Key_PageDown) {
scrollBy(-qMax(1, rows_ - 1));
return;
}
}
switch (event->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
sendKey(VTERM_KEY_ENTER, modifiers);
return;
case Qt::Key_Tab:
sendKey(VTERM_KEY_TAB, modifiers);
return;
case Qt::Key_Backtab:
sendText(QStringLiteral("\x1b[Z"), Qt::NoModifier);
return;
case Qt::Key_Backspace:
sendKey(VTERM_KEY_BACKSPACE, modifiers);
return;
case Qt::Key_Escape:
sendKey(VTERM_KEY_ESCAPE, modifiers);
return;
case Qt::Key_Insert:
sendKey(VTERM_KEY_INS, modifiers);
return;
case Qt::Key_Delete:
sendKey(VTERM_KEY_DEL, modifiers);
return;
case Qt::Key_Home:
sendKey(VTERM_KEY_HOME, modifiers);
return;
case Qt::Key_End:
sendKey(VTERM_KEY_END, modifiers);
return;
case Qt::Key_PageUp:
sendKey(VTERM_KEY_PAGEUP, modifiers);
return;
case Qt::Key_PageDown:
sendKey(VTERM_KEY_PAGEDOWN, modifiers);
return;
case Qt::Key_Up:
sendKey(VTERM_KEY_UP, modifiers);