Debian Codegraph @

lib/TerminalDisplay.cpp

raw symbols ◀ ▶ SCIP
4 Debian patches touch this file
1 /*
2 This file is part of Konsole, a terminal emulator for KDE.
3
4 Copyright 2006-2008 by Robert Knight <[email protected]>
5 Copyright 1997,1998 by Lars Doelle <[email protected]>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
21 */
22
23 // Own
24 #include "TerminalDisplay.h"
25
26 // C++
27 #include <cmath>
28
29 // Qt
30 #include <QAbstractButton>
31 #include <QApplication>
32 #include <QBoxLayout>
33 #include <QClipboard>
34 #include <QKeyEvent>
35 #include <QEvent>
36 #include <QTime>
37 #include <QFile>
38 #include <QGridLayout>
39 #include <QLabel>
40 #include <QLayout>
41 #include <QMessageBox>
42 #include <QPainter>
43 #include <QPixmap>
44 #include <QRegularExpression>
45 #include <QScrollBar>
46 #include <QStyle>
47 #include <QTimer>
48 #include <QtDebug>
49 #include <QUrl>
50 #include <QMimeData>
51 #include <QDrag>
52
53 // KDE
54 //#include <kshell.h>
55 //#include <KColorScheme>
56 //#include <KCursor>
57 //#include <kdebug.h>
58 //#include <KLocale>
59 //#include <KMenu>
60 //#include <KNotification>
61 //#include <KGlobalSettings>
62 //#include <KShortcut>
63 //#include <KIO/NetAccess>
64
65 // Konsole
66 //#include <config-apps.h>
67 #include "Filter.h"
68 #include "konsole_wcwidth.h"
69 #include "ScreenWindow.h"
70 #include "TerminalCharacterDecoder.h"
71
72 using namespace Konsole;
73
74 #ifndef loc
75 #define loc(X,Y) ((Y)*_columns+(X))
76 #endif
77
78 #define yMouseScroll 1
79
80 #define REPCHAR "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
81 "abcdefgjijklmnopqrstuvwxyz" \
82 "0123456789./+@"
83
84 const ColorEntry Konsole::base_color_table[TABLE_COLORS] =
85 // The following are almost IBM standard color codes, with some slight
86 // gamma correction for the dim colors to compensate for bright X screens.
87 // It contains the 8 ansiterm/xterm colors in 2 intensities.
88 {
89 // Fixme: could add faint colors here, also.
90 // normal
91 ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0xB2,0xB2), true), // Dfore, Dback
92 ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0x18,0x18), false), // Black, Red
93 ColorEntry(QColor(0x18,0xB2,0x18), false), ColorEntry( QColor(0xB2,0x68,0x18), false), // Green, Yellow
94 ColorEntry(QColor(0x18,0x18,0xB2), false), ColorEntry( QColor(0xB2,0x18,0xB2), false), // Blue, Magenta
95 ColorEntry(QColor(0x18,0xB2,0xB2), false), ColorEntry( QColor(0xB2,0xB2,0xB2), false), // Cyan, White
96 // intensiv
97 ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true),
98 ColorEntry(QColor(0x68,0x68,0x68), false), ColorEntry( QColor(0xFF,0x54,0x54), false),
99 ColorEntry(QColor(0x54,0xFF,0x54), false), ColorEntry( QColor(0xFF,0xFF,0x54), false),
100 ColorEntry(QColor(0x54,0x54,0xFF), false), ColorEntry( QColor(0xFF,0x54,0xFF), false),
101 ColorEntry(QColor(0x54,0xFF,0xFF), false), ColorEntry( QColor(0xFF,0xFF,0xFF), false)
102 };
103
104 // scroll increment used when dragging selection at top/bottom of window.
105
106 // static
107 bool TerminalDisplay::_antialiasText = true;
108 bool TerminalDisplay::HAVE_TRANSPARENCY = false;
109
110 // we use this to force QPainter to display text in LTR mode
111 // more information can be found in: http://unicode.org/reports/tr9/
112 const QChar LTR_OVERRIDE_CHAR( 0x202D );
113
114 /* ------------------------------------------------------------------------- */
115 /* */
116 /* Colors */
117 /* */
118 /* ------------------------------------------------------------------------- */
119
120 /* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb)
121
122 Code 0 1 2 3 4 5 6 7
123 ----------- ------- ------- ------- ------- ------- ------- ------- -------
124 ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White
125 IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White
126 */
127
128 ScreenWindow* TerminalDisplay::screenWindow() const
129 {
130 return _screenWindow;
131 }
132 void TerminalDisplay::setScreenWindow(ScreenWindow* window)
133 {
134 // disconnect existing screen window if any
135 if ( _screenWindow )
136 {
137 disconnect( _screenWindow , nullptr , this , nullptr );
138 }
139
140 _screenWindow = window;
141
142 if ( window )
143 {
144 connect(_screenWindow, &ScreenWindow::outputChanged, this, &TerminalDisplay::updateLineProperties);
145 connect(_screenWindow, &ScreenWindow::outputChanged, this, &TerminalDisplay::updateImage);
146 connect(_screenWindow, &ScreenWindow::scrollToEnd, this, &TerminalDisplay::scrollToEnd);
147 window->setWindowLines(_lines);
148 }
149 }
150
151 const ColorEntry* TerminalDisplay::colorTable() const
152 {
153 return _colorTable;
154 }
155 void TerminalDisplay::setBackgroundColor(const QColor& color)
156 {
157 _colorTable[DEFAULT_BACK_COLOR].color = color;
158 QPalette p = palette();
159 p.setColor( backgroundRole(), color );
160 setPalette( p );
161
162 // Avoid propagating the palette change to the scroll bar
163 _scrollBar->setPalette( QApplication::palette() );
164
•165 emit backgroundColorChanged();
166 update();
167 }
168 void TerminalDisplay::setForegroundColor(const QColor& color)
169 {
170 _colorTable[DEFAULT_FORE_COLOR].color = color;
•171 emit foregroundColorChanged();
172 update();
173 }
•174 QColor TerminalDisplay::backgroundColor() const
175 {
176 return _colorTable[DEFAULT_BACK_COLOR].color;
177 }
178 QColor TerminalDisplay::foregroundColor() const
179 {
180 return _colorTable[DEFAULT_FORE_COLOR].color;
181 }
182 void TerminalDisplay::setColorTable(const ColorEntry table[])
183 {
184 for (int i = 0; i < TABLE_COLORS; i++)
185 _colorTable[i] = table[i];
186
187 setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color);
•188 setForegroundColor(_colorTable[DEFAULT_FORE_COLOR].color);
189 }
190
191 /* ------------------------------------------------------------------------- */
192 /* */
193 /* Font */
194 /* */
195 /* ------------------------------------------------------------------------- */
196
197 /*
198 The VT100 has 32 special graphical characters. The usual vt100 extended
199 xterm fonts have these at 0x00..0x1f.
200
201 QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals
202 come in here as proper unicode characters.
203
204 We treat non-iso10646 fonts as VT100 extended and do the requiered mapping
205 from unicode to 0x00..0x1f. The remaining translation is then left to the
206 QCodec.
207 */
208
209 bool TerminalDisplay::isLineChar(wchar_t c) const {
210 return _drawLineChars && ((c & 0xFF80) == 0x2500);
211 }
212
213 bool TerminalDisplay::isLineCharString(const std::wstring& string) const {
214 return (string.length() > 0) && (isLineChar(string[0]));
215 }
216
217
218 // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i.
219
220 unsigned short Konsole::vt100_graphics[32] =
221 { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15
222 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
223 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
224 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
225 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
226 };
227
228 void TerminalDisplay::fontChange(const QFont&)
229 {
230 QFontMetrics fm(font());
231 _fontHeight = fm.height() + _lineSpacing;
232
233 // waba TerminalDisplay 1.123:
234 // "Base character width on widest ASCII character. This prevents too wide
235 // characters in the presence of double wide (e.g. Japanese) characters."
236 // Get the width from representative normal width characters
237 _fontWidth = qRound((double)fm.width(QLatin1String(REPCHAR))/(double)qstrlen(REPCHAR));
238
239 _fixedFont = true;
240
241 int fw = fm.width(QLatin1Char(REPCHAR[0]));
242 for(unsigned int i=1; i< qstrlen(REPCHAR); i++)
243 {
244 if (fw != fm.width(QLatin1Char(REPCHAR[i])))
245 {
246 _fixedFont = false;
247 break;
248 }
249 }
250
251 if (_fontWidth < 1)
252 _fontWidth=1;
253
254 _fontAscent = fm.ascent();
255
256 emit changedFontMetricSignal( _fontHeight, _fontWidth );
257 propagateSize();
258 update();
259 }
260
261 //void TerminalDisplay::calDrawTextAdditionHeight(QPainter& painter)
262 //{
263 // QRect test_rect, feedback_rect;
264 // test_rect.setRect(1, 1, _fontWidth * 4, _fontHeight);
265 // painter.drawText(test_rect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QLatin1String("Mq"), &feedback_rect);
266
267 // //qDebug() << "test_rect:" << test_rect << "feeback_rect:" << feedback_rect;
268
269 // _drawTextAdditionHeight = (feedback_rect.height() - _fontHeight) / 2;
270 // if(_drawTextAdditionHeight < 0) {
271 // _drawTextAdditionHeight = 0;
272 // }
273
274 // _drawTextTestFlag = false;
275 //}
276
277 void TerminalDisplay::setVTFont(const QFont& f)
278 {
279 QFont font = f;
280
281 // This was originally set for OS X only:
282 // mac uses floats for font width specification.
283 // this ensures the same handling for all platforms
284 // but then there was revealed that various Linux distros
285 // have this problem too...
286 font.setStyleStrategy(QFont::ForceIntegerMetrics);
287
288 QFontMetrics metrics(font);
289
290 if ( !QFontInfo(font).fixedPitch() )
291 {
292 qDebug() << "Using a variable-width font in the terminal. This may cause performance degradation and display/alignment errors.";
293 }
294
295 // hint that text should be drawn without anti-aliasing.
296 // depending on the user's font configuration, this may not be respected
297 if (!_antialiasText)
298 font.setStyleStrategy( QFont::NoAntialias );
299
300 // experimental optimization. Konsole assumes that the terminal is using a
301 // mono-spaced font, in which case kerning information should have an effect.
302 // Disabling kerning saves some computation when rendering text.
303 font.setKerning(false);
304
305 m_font = font;
306 fontChange(font);
307 emit vtFontChanged();
308 }
309
310 void TerminalDisplay::setBoldIntense(bool value)
311 {
312 if ( _boldIntense != value ) {
313 _boldIntense = value;
314 emit boldIntenseChanged();
315 }
316 }
317
318 void TerminalDisplay::setFont(const QFont &f)
319 {
320 Q_UNUSED(f);
321 // ignore font change request if not coming from konsole itself
322 }
323
324 /* ------------------------------------------------------------------------- */
325 /* */
326 /* Constructor / Destructor */
327 /* */
328 /* ------------------------------------------------------------------------- */
329
330 TerminalDisplay::TerminalDisplay(QQuickItem *parent)
331 :QQuickPaintedItem(parent)
332 ,_screenWindow(nullptr)
333 ,_allowBell(true)
334 ,_gridLayout(nullptr)
335 ,_fontHeight(1)
336 ,_fontWidth(1)
337 ,_fontAscent(1)
338 ,_boldIntense(true)
339 ,_lines(1)
340 ,_columns(1)
341 ,_usedLines(1)
342 ,_usedColumns(1)
343 ,_contentHeight(1)
344 ,_contentWidth(1)
345 ,_image(nullptr)
346 ,_randomSeed(0)
347 ,_resizing(false)
348 ,_terminalSizeHint(false)
349 ,_terminalSizeStartup(true)
350 ,_bidiEnabled(false)
351 ,_mouseMarks(false)
352 ,_disabledBracketedPasteMode(false)
353 ,_actSel(0)
354 ,_wordSelectionMode(false)
355 ,_lineSelectionMode(false)
356 ,_preserveLineBreaks(false)
357 ,_columnSelectionMode(false)
358 ,_scrollbarLocation(QTermWidget::NoScrollBar)
359 ,_wordCharacters(QLatin1String(":@-./_~"))
360 ,_bellMode(SystemBeepBell)
361 ,_blinking(false)
362 ,_hasBlinker(false)
363 ,_cursorBlinking(false)
364 ,_hasBlinkingCursor(false)
365 ,_allowBlinkingText(true)
366 ,_ctrlDrag(false)
367 ,_tripleClickMode(SelectWholeLine)
368 ,_isFixedSize(false)
369 ,_possibleTripleClick(false)
370 ,_resizeWidget(nullptr)
371 ,_resizeTimer(nullptr)
372 ,_flowControlWarningEnabled(false)
373 ,_outputSuspendedLabel(nullptr)
374 ,_lineSpacing(0)
•375 ,_colorSchemeRef(0)
376 ,_colorsInverted(false)
377 ,_opacity(static_cast<qreal>(1))
378 ,_backgroundMode(None)
379 ,_filterChain(new TerminalImageFilterChain())
380 ,_cursorShape(Emulation::KeyboardCursorShape::BlockCursor)
381 ,mMotionAfterPasting(NoMoveScreenWindow)
382 ,m_font("Monospace", 12)
383 ,m_color_role(QPalette::Background)
384 ,m_full_cursor_height(false)
385 ,_leftBaseMargin(1)
386 ,_topBaseMargin(1)
387 ,_drawLineChars(true)
388 {
389 // terminal applications are not designed with Right-To-Left in mind,
390 // so the layout is forced to Left-To-Right
391 //setLayoutDirection(Qt::LeftToRight);
392
393 // The offsets are not yet calculated.
394 // Do not calculate these too often to be more smoothly when resizing
395 // konsole in opaque mode.
396 _topMargin = _topBaseMargin;
397 _leftMargin = _leftBaseMargin;
398
399 m_palette = qApp->palette();
400
401 setVTFont(m_font);
402
403 // create scroll bar for scrolling output up and down
404 // set the scroll bar's slider to occupy the whole area of the scroll bar initially
405
406 _scrollBar = new QScrollBar();
407 setScroll(0,0);
408
409 _scrollBar->setCursor( Qt::ArrowCursor );
410 connect(_scrollBar, SIGNAL(valueChanged(int)), this,
411 SLOT(scrollBarPositionChanged(int)));
412 // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar
413 // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position)
414 _scrollBar->hide();
415
416 // setup timers for blinking cursor and text
417 _blinkTimer = new QTimer(this);
418 connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent()));
419 _blinkCursorTimer = new QTimer(this);
420 connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent()));
421
422 // KCursor::setAutoHideCursor( this, true );
423
424 setUsesMouse(true);
425 setBracketedPasteMode(false);
426 setColorTable(base_color_table);
427 //setMouseTracking(true);
428
429 setAcceptedMouseButtons(Qt::LeftButton);
430
431 setFlags(ItemHasContents | ItemAcceptsInputMethod);
432
433 //Setup scrollbar. Be sure it is not darw on screen.
434 _scrollBar->setAttribute(Qt::WA_DontShowOnScreen);
435 _scrollBar->setVisible(false);
436 connect(_scrollBar, SIGNAL(valueChanged(int)), this, SIGNAL(scrollbarParamsChanged(int)));
437
438 // TODO Forcing rendering to Framebuffer. We need to determine if this is ok
439 // always or if we need to make this customizable.
440 setRenderTarget(QQuickPaintedItem::FramebufferObject);
441
442 // setFocusPolicy( Qt::WheelFocus );
443
444 // enable input method support
445 // setAttribute(Qt::WA_InputMethodEnabled, true);
446
447 // this is an important optimization, it tells Qt
448 // that TerminalDisplay will handle repainting its entire area.
449 // setAttribute(Qt::WA_OpaquePaintEvent);
450
451 // _gridLayout = new QGridLayout(this);
452 // _gridLayout->setContentsMargins(0, 0, 0, 0);
453
454 // new AutoScrollHandler(this);
455 }
456
457 TerminalDisplay::~TerminalDisplay()
458 {
459 disconnect(_blinkTimer);
460 disconnect(_blinkCursorTimer);
461 qApp->removeEventFilter( this );
462
463 delete[] _image;
464
465 delete _gridLayout;
466 delete _outputSuspendedLabel;
467 delete _filterChain;
468 }
469
470 /* ------------------------------------------------------------------------- */
471 /* */
472 /* Display Operations */
473 /* */
474 /* ------------------------------------------------------------------------- */
475
476 /**
477 A table for emulating the simple (single width) unicode drawing chars.
478 It represents the 250x - 257x glyphs. If it's zero, we can't use it.
479 if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered
480 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit.
481
482 Then, the pixels basically have the following interpretation:
483 _|||_
484 -...-
485 -...-
486 -...-
487 _|||_
488
489 where _ = none
490 | = vertical line.
491 - = horizontal line.
492 */
493
494
495 enum LineEncode
496 {
497 TopL = (1<<1),
498 TopC = (1<<2),
499 TopR = (1<<3),
500
501 LeftT = (1<<5),
502 Int11 = (1<<6),
503 Int12 = (1<<7),
504 Int13 = (1<<8),
505 RightT = (1<<9),
506
507 LeftC = (1<<10),
508 Int21 = (1<<11),
509 Int22 = (1<<12),
510 Int23 = (1<<13),
511 RightC = (1<<14),
512
513 LeftB = (1<<15),
514 Int31 = (1<<16),
515 Int32 = (1<<17),
516 Int33 = (1<<18),
517 RightB = (1<<19),
518
519 BotL = (1<<21),
520 BotC = (1<<22),
521 BotR = (1<<23)
522 };
523
524 #include "LineFont.h"
525
526 static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uint8_t code)
527 {
528 //Calculate cell midpoints, end points.
529 int cx = x + w/2;
530 int cy = y + h/2;
531 int ex = x + w - 1;
532 int ey = y + h - 1;
533
534 quint32 toDraw = LineChars[code];
535
536 //Top _lines:
537 if (toDraw & TopL)
538 paint.drawLine(cx-1, y, cx-1, cy-2);
539 if (toDraw & TopC)
540 paint.drawLine(cx, y, cx, cy-2);
541 if (toDraw & TopR)
542 paint.drawLine(cx+1, y, cx+1, cy-2);
543
544 //Bot _lines:
545 if (toDraw & BotL)
546 paint.drawLine(cx-1, cy+2, cx-1, ey);
547 if (toDraw & BotC)
548 paint.drawLine(cx, cy+2, cx, ey);
549 if (toDraw & BotR)
550 paint.drawLine(cx+1, cy+2, cx+1, ey);
551
552 //Left _lines:
553 if (toDraw & LeftT)
554 paint.drawLine(x, cy-1, cx-2, cy-1);
555 if (toDraw & LeftC)
556 paint.drawLine(x, cy, cx-2, cy);
557 if (toDraw & LeftB)
558 paint.drawLine(x, cy+1, cx-2, cy+1);
559
560 //Right _lines:
561 if (toDraw & RightT)
562 paint.drawLine(cx+2, cy-1, ex, cy-1);
563 if (toDraw & RightC)
564 paint.drawLine(cx+2, cy, ex, cy);
565 if (toDraw & RightB)
566 paint.drawLine(cx+2, cy+1, ex, cy+1);
567
568 //Intersection points.
569 if (toDraw & Int11)
570 paint.drawPoint(cx-1, cy-1);
571 if (toDraw & Int12)
572 paint.drawPoint(cx, cy-1);
573 if (toDraw & Int13)
574 paint.drawPoint(cx+1, cy-1);
575
576 if (toDraw & Int21)
577 paint.drawPoint(cx-1, cy);
578 if (toDraw & Int22)
579 paint.drawPoint(cx, cy);
580 if (toDraw & Int23)
581 paint.drawPoint(cx+1, cy);
582
583 if (toDraw & Int31)
584 paint.drawPoint(cx-1, cy+1);
585 if (toDraw & Int32)
586 paint.drawPoint(cx, cy+1);
587 if (toDraw & Int33)
588 paint.drawPoint(cx+1, cy+1);
589
590 }
591
592 static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar code)
593 {
594 //Calculate cell midpoints, end points.
595 const int cx = x + w / 2;
596 const int cy = y + h / 2;
597 const int ex = x + w - 1;
598 const int ey = y + h - 1;
599
600 // Double dashes
601 if (0x4C <= code && code <= 0x4F) {
602 const int xHalfGap = qMax(w / 15, 1);
603 const int yHalfGap = qMax(h / 15, 1);
604 switch (code) {
605 case 0x4D: // BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL
606 paint.drawLine(x, cy - 1, cx - xHalfGap - 1, cy - 1);
607 paint.drawLine(x, cy + 1, cx - xHalfGap - 1, cy + 1);
608 paint.drawLine(cx + xHalfGap, cy - 1, ex, cy - 1);
609 paint.drawLine(cx + xHalfGap, cy + 1, ex, cy + 1);
610 /* Falls through. */
611 case 0x4C: // BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL
612 paint.drawLine(x, cy, cx - xHalfGap - 1, cy);
613 paint.drawLine(cx + xHalfGap, cy, ex, cy);
614 break;
615 case 0x4F: // BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL
616 paint.drawLine(cx - 1, y, cx - 1, cy - yHalfGap - 1);
617 paint.drawLine(cx + 1, y, cx + 1, cy - yHalfGap - 1);
618 paint.drawLine(cx - 1, cy + yHalfGap, cx - 1, ey);
619 paint.drawLine(cx + 1, cy + yHalfGap, cx + 1, ey);
620 /* Falls through. */
621 case 0x4E: // BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL
622 paint.drawLine(cx, y, cx, cy - yHalfGap - 1);
623 paint.drawLine(cx, cy + yHalfGap, cx, ey);
624 break;
625 }
626 }
627
628 // Rounded corner characters
629 else if (0x6D <= code && code <= 0x70) {
630 const int r = w * 3 / 8;
631 const int d = 2 * r;
632 switch (code) {
633 case 0x6D: // BOX DRAWINGS LIGHT ARC DOWN AND RIGHT
634 paint.drawLine(cx, cy + r, cx, ey);
635 paint.drawLine(cx + r, cy, ex, cy);
636 paint.drawArc(cx, cy, d, d, 90 * 16, 90 * 16);
637 break;
638 case 0x6E: // BOX DRAWINGS LIGHT ARC DOWN AND LEFT
639 paint.drawLine(cx, cy + r, cx, ey);
640 paint.drawLine(x, cy, cx - r, cy);
641 paint.drawArc(cx - d, cy, d, d, 0 * 16, 90 * 16);
642 break;
643 case 0x6F: // BOX DRAWINGS LIGHT ARC UP AND LEFT
644 paint.drawLine(cx, y, cx, cy - r);
645 paint.drawLine(x, cy, cx - r, cy);
646 paint.drawArc(cx - d, cy - d, d, d, 270 * 16, 90 * 16);
647 break;
648 case 0x70: // BOX DRAWINGS LIGHT ARC UP AND RIGHT
649 paint.drawLine(cx, y, cx, cy - r);
650 paint.drawLine(cx + r, cy, ex, cy);
651 paint.drawArc(cx, cy - d, d, d, 180 * 16, 90 * 16);
652 break;
653 }
654 }
655
656 // Diagonals
657 else if (0x71 <= code && code <= 0x73) {
658 switch (code) {
659 case 0x71: // BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT
660 paint.drawLine(ex, y, x, ey);
661 break;
662 case 0x72: // BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT
663 paint.drawLine(x, y, ex, ey);
664 break;
665 case 0x73: // BOX DRAWINGS LIGHT DIAGONAL CROSS
666 paint.drawLine(ex, y, x, ey);
667 paint.drawLine(x, y, ex, ey);
668 break;
669 }
670 }
671 }
672
673 void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const std::wstring& str,
674 const Character* attributes) const
675 {
676 const QPen& currentPen = painter.pen();
677
678 if ( (attributes->rendition & RE_BOLD) && _boldIntense )
679 {
680 QPen boldPen(currentPen);
681 boldPen.setWidth(3);
682 painter.setPen( boldPen );
683 }
684
685 for (size_t i=0 ; i < str.length(); i++)
686 {
687 uint8_t code = static_cast<uint8_t>(str[i] & 0xffU);
688 if (LineChars[code])
689 drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code);
690 else
691 drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code);
692 }
693
694 painter.setPen( currentPen );
695 }
696
697 void TerminalDisplay::setKeyboardCursorShape(QTermWidget::KeyboardCursorShape shape)
698 {
699 _cursorShape = shape;
700
701 updateCursor();
702 }
703 QTermWidget::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const
704 {
705 return _cursorShape;
706 }
707 void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color)
708 {
709 if (useForegroundColor)
710 _cursorColor = QColor(); // an invalid color means that
711 // the foreground color of the
712 // current character should
713 // be used
714
715 else
716 _cursorColor = color;
717 }
718 QColor TerminalDisplay::keyboardCursorColor() const
719 {
720 return _cursorColor;
721 }
722
723 void TerminalDisplay::setOpacity(qreal opacity)
724 {
725 _opacity = qBound(static_cast<qreal>(0), opacity, static_cast<qreal>(1));
726 }
727
728 void TerminalDisplay::setBackgroundImage(const QString& backgroundImage)
729 {
730 if (!backgroundImage.isEmpty())
731 {
732 _backgroundImage.load(backgroundImage);
733 //setAttribute(Qt::WA_OpaquePaintEvent, false);
734 }
735 else
736 {
737 _backgroundImage = QPixmap();
738 //setAttribute(Qt::WA_OpaquePaintEvent, true);
739 }
740 }
741
742 void TerminalDisplay::setBackgroundMode(BackgroundMode mode)
743 {
744 _backgroundMode = mode;
745 }
746
747 void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting )
748 {
749 // The whole widget rectangle is filled by the background color from
750 // the color scheme set in setColorTable(), while the scrollbar is
751 // left to the widget style for a consistent look.
752 if ( useOpacitySetting )
753 {
754 if (_backgroundImage.isNull()) {
755 QColor color(backgroundColor);
756 color.setAlphaF(_opacity);
757
758 painter.save();
759 painter.setCompositionMode(QPainter::CompositionMode_Source);
760 painter.fillRect(rect, color);
761 painter.restore();
762 }
763 }
764 else
765 painter.fillRect(rect, backgroundColor);
766 }
767
768 void TerminalDisplay::drawCursor(QPainter& painter,
769 const QRect& rect,
770 const QColor& foregroundColor,
771 const QColor& /*backgroundColor*/,
772 bool& invertCharacterColor)
773 {
774 QRect cursorRect = rect;
775
776 cursorRect.setHeight(_fontHeight - ((m_full_cursor_height) ? 0 : _lineSpacing - 1));
777
778 if (!_cursorBlinking)
779 {
780 if ( _cursorColor.isValid() )
781 painter.setPen(_cursorColor);
782 else
783 painter.setPen(foregroundColor);
784
785 if ( _cursorShape == Emulation::KeyboardCursorShape::BlockCursor )
786 {
787 // draw the cursor outline, adjusting the area so that
788 // it is draw entirely inside 'rect'
789 float penWidth = qMax(1,painter.pen().width());
790
791 //
792 painter.drawRect(
793 cursorRect.adjusted(
794 + penWidth/2 + fmod(penWidth, 2),
795 + penWidth/2 + fmod(penWidth, 2),
796 - penWidth/2 - fmod(penWidth, 2),
797 - penWidth/2 - fmod(penWidth, 2)
798 )
799 );
800
801 //if ( hasFocus() )
802 if ( true ) //QMLTermWidget: Always fill the cursor. Even when not in focus.
803 {
804 painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor);
805
806 if ( !_cursorColor.isValid() )
807 {
808 // invert the colour used to draw the text to ensure that the character at
809 // the cursor position is readable
810 invertCharacterColor = true;
811 }
812 }
813 }
814 else if ( _cursorShape == Emulation::KeyboardCursorShape::UnderlineCursor )
815 painter.drawLine(cursorRect.left(),
816 cursorRect.bottom(),
817 cursorRect.right(),
818 cursorRect.bottom());
819 else if ( _cursorShape == Emulation::KeyboardCursorShape::IBeamCursor )
820 painter.drawLine(cursorRect.left(),
821 cursorRect.top(),
822 cursorRect.left(),
823 cursorRect.bottom());
824
825 }
826 }
827
828 void TerminalDisplay::drawCharacters(QPainter& painter,
829 const QRect& rect,
830 const std::wstring& text,
831 const Character* style,
832 bool invertCharacterColor)
833 {
834 // don't draw text which is currently blinking
835 if ( _blinking && (style->rendition & RE_BLINK) )
836 return;
837
838 // don't draw concealed characters
839 if (style->rendition & RE_CONCEAL)
840 return;
841
842 // setup bold and underline
843 bool useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold();
844 const bool useUnderline = style->rendition & RE_UNDERLINE || font().underline();
845 const bool useItalic = style->rendition & RE_ITALIC || font().italic();
846 const bool useStrikeOut = style->rendition & RE_STRIKEOUT || font().strikeOut();
847 const bool useOverline = style->rendition & RE_OVERLINE || font().overline();
848
849 painter.setFont(font());
850
851 QFont font = painter.font();
852 if ( font.bold() != useBold
853 || font.underline() != useUnderline
854 || font.italic() != useItalic
855 || font.strikeOut() != useStrikeOut
856 || font.overline() != useOverline) {
857 font.setBold(useBold);
858 font.setUnderline(useUnderline);
859 font.setItalic(useItalic);
860 font.setStrikeOut(useStrikeOut);
861 font.setOverline(useOverline);
862 painter.setFont(font);
863 }
864
865 // setup pen
866 const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor );
867 const QColor color = textColor.color(_colorTable);
868 QPen pen = painter.pen();
869 if ( pen.color() != color )
870 {
871 pen.setColor(color);
872 painter.setPen(color);
873 }
874
875 // draw text
876 if ( isLineCharString(text) )
877 drawLineCharString(painter,rect.x(),rect.y(),text,style);
878 else
879 {
880 // Force using LTR as the document layout for the terminal area, because
881 // there is no use cases for RTL emulator and RTL terminal application.
882 //
883 // This still allows RTL characters to be rendered in the RTL way.
884 painter.setLayoutDirection(Qt::LeftToRight);
885
886 if (_bidiEnabled) {
887 painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, QString::fromStdWString(text));
888 } else {
889 painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, LTR_OVERRIDE_CHAR + QString::fromStdWString(text));
890 }
891 }
892 }
893
894 void TerminalDisplay::drawTextFragment(QPainter& painter ,
895 const QRect& rect,
896 const std::wstring& text,
897 const Character* style)
898 {
899 painter.save();
900
901 // setup painter
902 const QColor foregroundColor = style->foregroundColor.color(_colorTable);
903 const QColor backgroundColor = style->backgroundColor.color(_colorTable);
904
905 // draw background if different from the display's background color
906 if ( backgroundColor != palette().background().color() )
907 drawBackground(painter,rect,backgroundColor,
908 false /* do not use transparency */);
909
910 // draw cursor shape if the current character is the cursor
911 // this may alter the foreground and background colors
912 bool invertCharacterColor = false;
913 if ( style->rendition & RE_CURSOR )
914 drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor);
915
916 // draw text
917 drawCharacters(painter,rect,text,style,invertCharacterColor);
918
919 painter.restore();
920 }
921
922 void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; }
923 uint TerminalDisplay::randomSeed() const { return _randomSeed; }
924
925 #if 0
926 /*!
927 Set XIM Position
928 */
929 void TerminalDisplay::setCursorPos(const int curx, const int cury)
930 {
931 QPoint tL = contentsRect().topLeft();
932 int tLx = tL.x();
933 int tLy = tL.y();
934
935 int xpos, ypos;
936 ypos = _topMargin + tLy + _fontHeight*(cury-1) + _fontAscent;
937 xpos = _leftMargin + tLx + _fontWidth*curx;
938 //setMicroFocusHint(xpos, ypos, 0, _fontHeight); //### ???
939 // fprintf(stderr, "x/y = %d/%d\txpos/ypos = %d/%d\n", curx, cury, xpos, ypos);
940 _cursorLine = cury;
941 _cursorCol = curx;
942 }
943 #endif
944
945 // scrolls the image by 'lines', down if lines > 0 or up otherwise.
946 //
947 // the terminal emulation keeps track of the scrolling of the character
948 // image as it receives input, and when the view is updated, it calls scrollImage()
949 // with the final scroll amount. this improves performance because scrolling the
950 // display is much cheaper than re-rendering all the text for the
951 // part of the image which has moved up or down.
952 // Instead only new lines have to be drawn
953 void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion)
954 {
955 // if the flow control warning is enabled this will interfere with the
956 // scrolling optimizations and cause artifacts. the simple solution here
957 // is to just disable the optimization whilst it is visible
958 if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() )
959 return;
960
961 // constrain the region to the display
962 // the bottom of the region is capped to the number of lines in the display's
963 // internal image - 2, so that the height of 'region' is strictly less
964 // than the height of the internal image.
965 QRect region = screenWindowRegion;
966 region.setBottom( qMin(region.bottom(),this->_lines-2) );
967
968 // return if there is nothing to do
969 if ( lines == 0
970 || _image == nullptr
971 || !region.isValid()
972 || (region.top() + abs(lines)) >= region.bottom()
973 || this->_lines <= region.height() ) return;
974
975 // hide terminal size label to prevent it being scrolled
976 if (_resizeWidget && _resizeWidget->isVisible())
977 _resizeWidget->hide();
978
979 // Note: With Qt 4.4 the left edge of the scrolled area must be at 0
980 // to get the correct (newly exposed) part of the widget repainted.
981 //
982 // The right edge must be before the left edge of the scroll bar to
983 // avoid triggering a repaint of the entire widget, the distance is
984 // given by SCROLLBAR_CONTENT_GAP
985 //
986 // Set the QT_FLUSH_PAINT environment variable to '1' before starting the
987 // application to monitor repainting.
988 //
989 int scrollBarWidth = _scrollBar->isHidden() ? 0 :
990 _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) ?
991 0 : _scrollBar->width();
992 const int SCROLLBAR_CONTENT_GAP = scrollBarWidth == 0 ? 0 : 1;
993 QRect scrollRect;
994 if ( _scrollbarLocation == QTermWidget::ScrollBarLeft )
995 {
996 scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP);
997 scrollRect.setRight(width());
998 }
999 else
1000 {
1001 scrollRect.setLeft(0);
1002 scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP);
1003 }
1004 void* firstCharPos = &_image[ region.top() * this->_columns ];
1005 void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ];
1006
1007 int top = _topMargin + (region.top() * _fontHeight);
1008 int linesToMove = region.height() - abs(lines);
1009 int bytesToMove = linesToMove *
1010 this->_columns *
1011 sizeof(Character);
1012
1013 Q_ASSERT( linesToMove > 0 );
1014 Q_ASSERT( bytesToMove > 0 );
1015
1016 //scroll internal image
1017 if ( lines > 0 )
1018 {
1019 // check that the memory areas that we are going to move are valid
1020 Q_ASSERT( (char*)lastCharPos + bytesToMove <
1021 (char*)(_image + (this->_lines * this->_columns)) );
1022
1023 Q_ASSERT( (lines*this->_columns) < _imageSize );
1024
1025 //scroll internal image down
1026 memmove( firstCharPos , lastCharPos , bytesToMove );
1027
1028 //set region of display to scroll
1029 scrollRect.setTop(top);
1030 }
1031 else
1032 {
1033 // check that the memory areas that we are going to move are valid
1034 Q_ASSERT( (char*)firstCharPos + bytesToMove <
1035 (char*)(_image + (this->_lines * this->_columns)) );
1036
1037 //scroll internal image up
1038 memmove( lastCharPos , firstCharPos , bytesToMove );
1039
1040 //set region of the display to scroll
1041 scrollRect.setTop(top + abs(lines) * _fontHeight);
1042 }
1043 scrollRect.setHeight(linesToMove * _fontHeight );
1044
1045 Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty());
1046
1047 //scroll the display vertically to match internal _image
1048 //scroll( 0 , _fontHeight * (-lines) , scrollRect );
1049 }
1050
1051 QRegion TerminalDisplay::hotSpotRegion() const
1052 {
1053 QRegion region;
1054 const auto hotSpots = _filterChain->hotSpots();
1055 for( Filter::HotSpot* const hotSpot : hotSpots )
1056 {
1057 QRect r;
1058 if (hotSpot->startLine()==hotSpot->endLine()) {
1059 r.setLeft(hotSpot->startColumn());
1060 r.setTop(hotSpot->startLine());
1061 r.setRight(hotSpot->endColumn());
1062 r.setBottom(hotSpot->endLine());
1063 region |= imageToWidget(r);;
1064 } else {
1065 r.setLeft(hotSpot->startColumn());
1066 r.setTop(hotSpot->startLine());
1067 r.setRight(_columns);
1068 r.setBottom(hotSpot->startLine());
1069 region |= imageToWidget(r);;
1070 for ( int line = hotSpot->startLine()+1 ; line < hotSpot->endLine() ; line++ ) {
1071 r.setLeft(0);
1072 r.setTop(line);
1073 r.setRight(_columns);
1074 r.setBottom(line);
1075 region |= imageToWidget(r);;
1076 }
1077 r.setLeft(0);
1078 r.setTop(hotSpot->endLine());
1079 r.setRight(hotSpot->endColumn());
1080 r.setBottom(hotSpot->endLine());
1081 region |= imageToWidget(r);;
1082 }
1083 }
1084 return region;
1085 }
1086
1087 void TerminalDisplay::processFilters()
1088 {
1089 if (!_screenWindow)
1090 return;
1091
1092 QRegion preUpdateHotSpots = hotSpotRegion();
1093
1094 // use _screenWindow->getImage() here rather than _image because
1095 // other classes may call processFilters() when this display's
1096 // ScreenWindow emits a scrolled() signal - which will happen before
1097 // updateImage() is called on the display and therefore _image is
1098 // out of date at this point
1099 _filterChain->setImage( _screenWindow->getImage(),
1100 _screenWindow->windowLines(),
1101 _screenWindow->windowColumns(),
1102 _screenWindow->getLineProperties() );
1103 _filterChain->process();
1104
1105 QRegion postUpdateHotSpots = hotSpotRegion();
1106
1107 update( preUpdateHotSpots | postUpdateHotSpots );
1108 }
1109
1110 void TerminalDisplay::updateImage()
1111 {
1112 if ( !_screenWindow )
1113 return;
1114
1115 // TODO QMLTermWidget at the moment I'm disabling this.
1116 // Since this can't be scrolled we need to determine if this
1117 // is useful or not.
1118
1119 // optimization - scroll the existing image where possible and
1120 // avoid expensive text drawing for parts of the image that
1121 // can simply be moved up or down
1122 // scrollImage( _screenWindow->scrollCount() ,
1123 // _screenWindow->scrollRegion() );
1124 // _screenWindow->resetScrollCount();
1125
1126 if (!_image) {
1127 // Create _image.
1128 // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first.
1129 updateImageSize();
1130 }
1131
1132 Character* const newimg = _screenWindow->getImage();
1133 int lines = _screenWindow->windowLines();
1134 int columns = _screenWindow->windowColumns();
1135
1136 setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() );
1137
1138 Q_ASSERT( this->_usedLines <= this->_lines );
1139 Q_ASSERT( this->_usedColumns <= this->_columns );
1140
1141 int y,x,len;
1142
1143 QPoint tL = contentsRect().topLeft();
1144 int tLx = tL.x();
1145 int tLy = tL.y();
1146 _hasBlinker = false;
1147
1148 CharacterColor cf; // undefined
1149 CharacterColor _clipboard; // undefined
1150 int cr = -1; // undefined
1151
1152 const int linesToUpdate = qMin(this->_lines, qMax(0,lines ));
1153 const int columnsToUpdate = qMin(this->_columns,qMax(0,columns));
1154
1155 wchar_t *disstrU = new wchar_t[columnsToUpdate];
1156 char *dirtyMask = new char[columnsToUpdate+2];
1157 QRegion dirtyRegion;
1158
1159 // debugging variable, this records the number of lines that are found to
1160 // be 'dirty' ( ie. have changed from the old _image to the new _image ) and
1161 // which therefore need to be repainted
1162 int dirtyLineCount = 0;
1163
1164 for (y = 0; y < linesToUpdate; ++y)
1165 {
1166 const Character* currentLine = &_image[y*this->_columns];
1167 const Character* const newLine = &newimg[y*columns];
1168
1169 bool updateLine = false;
1170
1171 // The dirty mask indicates which characters need repainting. We also
1172 // mark surrounding neighbours dirty, in case the character exceeds
1173 // its cell boundaries
1174 memset(dirtyMask, 0, columnsToUpdate+2);
1175
1176 for( x = 0 ; x < columnsToUpdate ; ++x)
1177 {
1178 if ( newLine[x] != currentLine[x] )
1179 {
1180 dirtyMask[x] = true;
1181 }
1182 }
1183
1184 if (!_resizing) // not while _resizing, we're expecting a paintEvent
1185 for (x = 0; x < columnsToUpdate; ++x)
1186 {
1187 _hasBlinker |= (newLine[x].rendition & RE_BLINK);
1188
1189 // Start drawing if this character or the next one differs.
1190 // We also take the next one into account to handle the situation
1191 // where characters exceed their cell width.
1192 if (dirtyMask[x])
1193 {
1194 wchar_t c = newLine[x+0].character;
1195 if ( !c )
1196 continue;
1197 int p = 0;
1198 disstrU[p++] = c; //fontMap(c);
1199 bool lineDraw = isLineChar(c);
1200 bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0);
1201 cr = newLine[x].rendition;
1202 _clipboard = newLine[x].backgroundColor;
1203 if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor;
1204 int lln = columnsToUpdate - x;
1205 for (len = 1; len < lln; ++len)
1206 {
1207 const Character& ch = newLine[x+len];
1208
1209 if (!ch.character)
1210 continue; // Skip trailing part of multi-col chars.
1211
1212 bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0);
1213
1214 if ( ch.foregroundColor != cf ||
1215 ch.backgroundColor != _clipboard ||
1216 ch.rendition != cr ||
1217 !dirtyMask[x+len] ||
1218 isLineChar(c) != lineDraw ||
1219 nextIsDoubleWidth != doubleWidth )
1220 break;
1221
1222 disstrU[p++] = c; //fontMap(c);
1223 }
1224
1225 std::wstring unistr(disstrU, p);
1226
1227 bool saveFixedFont = _fixedFont;
1228 if (lineDraw)
1229 _fixedFont = false;
1230 if (doubleWidth)
1231 _fixedFont = false;
1232
1233 updateLine = true;
1234
1235 _fixedFont = saveFixedFont;
1236 x += len - 1;
1237 }
1238
1239 }
1240
1241 //both the top and bottom halves of double height _lines must always be redrawn
1242 //although both top and bottom halves contain the same characters, only
1243 //the top one is actually
1244 //drawn.
1245 if (_lineProperties.count() > y)
1246 updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT);
1247
1248 // if the characters on the line are different in the old and the new _image
1249 // then this line must be repainted.
1250 if (updateLine)
1251 {
1252 dirtyLineCount++;
1253
1254 // add the area occupied by this line to the region which needs to be
1255 // repainted
1256 QRect dirtyRect = QRect( _leftMargin+tLx ,
1257 _topMargin+tLy+_fontHeight*y ,
1258 _fontWidth * columnsToUpdate ,
1259 _fontHeight );
1260
1261 dirtyRegion |= dirtyRect;
1262 }
1263
1264 // replace the line of characters in the old _image with the
1265 // current line of the new _image
1266 memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character));
1267 }
1268
1269 // if the new _image is smaller than the previous _image, then ensure that the area
1270 // outside the new _image is cleared
1271 if ( linesToUpdate < _usedLines )
1272 {
1273 dirtyRegion |= QRect( _leftMargin+tLx ,
1274 _topMargin+tLy+_fontHeight*linesToUpdate ,
1275 _fontWidth * this->_columns ,
1276 _fontHeight * (_usedLines-linesToUpdate) );
1277 }
1278 _usedLines = linesToUpdate;
1279
1280 if ( columnsToUpdate < _usedColumns )
1281 {
1282 dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth ,
1283 _topMargin+tLy ,
1284 _fontWidth * (_usedColumns-columnsToUpdate) ,
1285 _fontHeight * this->_lines );
1286 }
1287 _usedColumns = columnsToUpdate;
1288
1289 dirtyRegion |= _inputMethodData.previousPreeditRect;
1290
1291 // update the parts of the display which have changed
1292 update(dirtyRegion);
1293
1294 if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY );
1295 if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; }
1296 delete[] dirtyMask;
1297 delete[] disstrU;
1298
1299 }
1300
1301 void TerminalDisplay::showResizeNotification()
1302 {
1303 // if (_terminalSizeHint && isVisible())
1304 // {
1305 // if (_terminalSizeStartup) {
1306 // _terminalSizeStartup=false;
1307 // return;
1308 // }
1309 // if (!_resizeWidget)
1310 // {
1311 // _resizeWidget = new QLabel("Size: XXX x XXX", this);
1312 // _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width("Size: XXX x XXX"));
1313 // _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height());
1314 // _resizeWidget->setAlignment(Qt::AlignCenter);
1315
1316 // _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)");
1317
1318 // _resizeTimer = new QTimer(this);
1319 // _resizeTimer->setSingleShot(true);
1320 // connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide()));
1321 // }
1322 // QString sizeStr = QString("Size: %1 x %2").arg(_columns).arg(_lines);
1323 // _resizeWidget->setText(sizeStr);
1324 // _resizeWidget->move((width()-_resizeWidget->width())/2,
1325 // (height()-_resizeWidget->height())/2+20);
1326 // _resizeWidget->show();
1327 // _resizeTimer->start(1000);
1328 // }
1329 }
1330
1331 void TerminalDisplay::setBlinkingCursor(bool blink)
1332 {
1333 if (_hasBlinkingCursor != blink)
1334 emit blinkingCursorStateChanged();
1335
1336 _hasBlinkingCursor=blink;
1337
1338 if (blink && !_blinkCursorTimer->isActive())
1339 _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2);
1340
1341 if (!blink && _blinkCursorTimer->isActive())
1342 {
1343 _blinkCursorTimer->stop();
1344 if (_cursorBlinking)
1345 blinkCursorEvent();
1346 else
1347 _cursorBlinking = false;
1348 }
1349 }
1350
1351 void TerminalDisplay::setBlinkingTextEnabled(bool blink)
1352 {
1353 _allowBlinkingText = blink;
1354
1355 if (blink && !_blinkTimer->isActive())
1356 _blinkTimer->start(TEXT_BLINK_DELAY);
1357
1358 if (!blink && _blinkTimer->isActive())
1359 {
1360 _blinkTimer->stop();
1361 _blinking = false;
1362 }
1363 }
1364
1365 void TerminalDisplay::focusOutEvent(QFocusEvent*)
1366 {
1367 emit termLostFocus();
1368 // trigger a repaint of the cursor so that it is both visible (in case
1369 // it was hidden during blinking)
1370 // and drawn in a focused out state
1371 _cursorBlinking = false;
1372 updateCursor();
1373
1374 _blinkCursorTimer->stop();
1375 if (_blinking)
1376 blinkEvent();
1377
1378 _blinkTimer->stop();
1379 }
1380 void TerminalDisplay::focusInEvent(QFocusEvent*)
1381 {
1382 emit termGetFocus();
1383 if (_hasBlinkingCursor)
1384 {
1385 _blinkCursorTimer->start();
1386 }
1387 updateCursor();
1388
1389 if (_hasBlinker)
1390 _blinkTimer->start();
1391 }
1392
1393 // QMLTermWidget version. See the upstream commented version for reference.
1394 void TerminalDisplay::paint(QPainter *painter)
1395 {
1396 QRect clipRect = painter->clipBoundingRect().toAlignedRect();
1397 QRect dirtyRect = clipRect.isValid() ? clipRect : contentsRect();
1398 drawContents(*painter, dirtyRect);
1399 }
1400
1401 // qtermwidget upstream version, might be useful for reference.
1402 //void TerminalDisplay::paintEvent( QPaintEvent* pe )
1403 //{
1404 // QPainter paint(this);
1405 // QRect cr = contentsRect();
1406
1407 // if ( !_backgroundImage.isNull() )
1408 // {
1409 // QColor background = _colorTable[DEFAULT_BACK_COLOR].color;
1410 // if (_opacity < static_cast<qreal>(1))
1411 // {
1412 // background.setAlphaF(_opacity);
1413 // paint.save();
1414 // paint.setCompositionMode(QPainter::CompositionMode_Source);
1415 // paint.fillRect(cr, background);
1416 // paint.restore();
1417 // }
1418 // else
1419 // {
1420 // paint.fillRect(cr, background);
1421 // }
1422
1423 // paint.save();
1424 // paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
1425
1426 // if (_backgroundMode == Stretch)
1427 // { // scale the image without keeping its proportions to fill the screen
1428 // paint.drawPixmap(cr, _backgroundImage, _backgroundImage.rect());
1429 // }
1430 // else if (_backgroundMode == Zoom)
1431 // { // zoom in/out the image to fit it
1432 // QRect r = _backgroundImage.rect();
1433 // qreal wRatio = static_cast<qreal>(cr.width()) / r.width();
1434 // qreal hRatio = static_cast<qreal>(cr.height()) / r.height();
1435 // if (wRatio > hRatio)
1436 // {
1437 // r.setWidth(qRound(r.width() * hRatio));
1438 // r.setHeight(cr.height());
1439 // }
1440 // else
1441 // {
1442 // r.setHeight(qRound(r.height() * wRatio));
1443 // r.setWidth(cr.width());
1444 // }
1445 // r.moveCenter(cr.center());
1446 // paint.drawPixmap(r, _backgroundImage, _backgroundImage.rect());
1447 // }
1448 // else if (_backgroundMode == Fit)
1449 // { // if the image is bigger than the terminal, zoom it out to fit it
1450 // QRect r = _backgroundImage.rect();
1451 // qreal wRatio = static_cast<qreal>(cr.width()) / r.width();
1452 // qreal hRatio = static_cast<qreal>(cr.height()) / r.height();
1453 // if (r.width() > cr.width())
1454 // {
1455 // if (wRatio <= hRatio)
1456 // {
1457 // r.setHeight(qRound(r.height() * wRatio));
1458 // r.setWidth(cr.width());
1459 // }
1460 // else
1461 // {
1462 // r.setWidth(qRound(r.width() * hRatio));
1463 // r.setHeight(cr.height());
1464 // }
1465 // }
1466 // else if (r.height() > cr.height())
1467 // {
1468 // r.setWidth(qRound(r.width() * hRatio));
1469 // r.setHeight(cr.height());
1470 // }
1471 // r.moveCenter(cr.center());
1472 // paint.drawPixmap(r, _backgroundImage, _backgroundImage.rect());
1473 // }
1474 // else if (_backgroundMode == Center)
1475 // { // center the image without scaling/zooming
1476 // QRect r = _backgroundImage.rect();
1477 // r.moveCenter(cr.center());
1478 // paint.drawPixmap(r.topLeft(), _backgroundImage);
1479 // }
1480 // else //if (_backgroundMode == None)
1481 // {
1482 // paint.drawPixmap(0, 0, _backgroundImage);
1483 // }
1484
1485 // paint.restore();
1486 // }
1487
1488 // if(_drawTextTestFlag)
1489 // {
1490 // calDrawTextAdditionHeight(paint);
1491 // }
1492
1493 // const auto rects = (pe->region() & cr).rects();
1494 // for (const QRect &rect : rects)
1495 // {
1496 // drawBackground(paint,rect,palette().background().color(),
1497 // true /* use opacity setting */);
1498 // drawContents(paint, rect);
1499 // }
1500 // drawInputMethodPreeditString(paint,preeditRect());
1501 // paintFilters(paint);
1502
1503 QPoint TerminalDisplay::cursorPosition() const
1504 {
1505 if (_screenWindow)
1506 return _screenWindow->cursorPosition();
1507 else
1508 return {0,0};
1509 }
1510
1511 QRect TerminalDisplay::preeditRect() const
1512 {
1513 const int preeditLength = string_width(_inputMethodData.preeditString);
1514
1515 if ( preeditLength == 0 )
1516 return {};
1517
1518 return QRect(_leftMargin + _fontWidth*cursorPosition().x(),
1519 _topMargin + _fontHeight*cursorPosition().y(),
1520 _fontWidth*preeditLength,
1521 _fontHeight);
1522 }
1523
1524 void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect)
1525 {
1526 if ( _inputMethodData.preeditString.empty() )
1527 return;
1528
1529 const QPoint cursorPos = cursorPosition();
1530
1531 bool invertColors = false;
1532 const QColor background = _colorTable[DEFAULT_BACK_COLOR].color;
1533 const QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color;
1534 const Character* style = &_image[loc(cursorPos.x(),cursorPos.y())];
1535
1536 drawBackground(painter,rect,background,true);
1537 drawCursor(painter,rect,foreground,background,invertColors);
1538 drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors);
1539
1540 _inputMethodData.previousPreeditRect = rect;
1541 }
1542
1543 FilterChain* TerminalDisplay::filterChain() const
1544 {
1545 return _filterChain;
1546 }
1547
1548 void TerminalDisplay::paintFilters(QPainter& painter)
1549 {
1550 // get color of character under mouse and use it to draw
1551 // lines for filters
1552 QPoint cursorPos = mapFromScene(QCursor::pos()).toPoint();
1553 int cursorLine;
1554 int cursorColumn;
1555 int leftMargin = _leftBaseMargin
1556 + ((_scrollbarLocation == QTermWidget::ScrollBarLeft
1557 && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar))
1558 ? _scrollBar->width() : 0);
1559
1560 getCharacterPosition( cursorPos , cursorLine , cursorColumn );
1561 Character cursorCharacter = _image[loc(cursorColumn,cursorLine)];
1562
1563 painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) );
1564
1565 // iterate over hotspots identified by the display's currently active filters
1566 // and draw appropriate visuals to indicate the presence of the hotspot
1567
1568 QList<Filter::HotSpot*> spots = _filterChain->hotSpots();
1569 QListIterator<Filter::HotSpot*> iter(spots);
1570 while (iter.hasNext())
1571 {
1572 Filter::HotSpot* spot = iter.next();
1573
1574 QRegion region;
1575 if ( spot->type() == Filter::HotSpot::Link ) {
1576 QRect r;
1577 if (spot->startLine()==spot->endLine()) {
1578 r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin,
1579 spot->startLine()*_fontHeight + 1 + _topBaseMargin,
1580 spot->endColumn()*_fontWidth - 1 + leftMargin,
1581 (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin );
1582 region |= r;
1583 } else {
1584 r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin,
1585 spot->startLine()*_fontHeight + 1 + _topBaseMargin,
1586 _columns*_fontWidth - 1 + leftMargin,
1587 (spot->startLine()+1)*_fontHeight - 1 + _topBaseMargin );
1588 region |= r;
1589 for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) {
1590 r.setCoords( 0*_fontWidth + 1 + leftMargin,
1591 line*_fontHeight + 1 + _topBaseMargin,
1592 _columns*_fontWidth - 1 + leftMargin,
1593 (line+1)*_fontHeight - 1 + _topBaseMargin );
1594 region |= r;
1595 }
1596 r.setCoords( 0*_fontWidth + 1 + leftMargin,
1597 spot->endLine()*_fontHeight + 1 + _topBaseMargin,
1598 spot->endColumn()*_fontWidth - 1 + leftMargin,
1599 (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin );
1600 region |= r;
1601 }
1602 }
1603
1604 for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ )
1605 {
1606 int startColumn = 0;
1607 int endColumn = _columns-1; // TODO use number of _columns which are actually
1608 // occupied on this line rather than the width of the
1609 // display in _columns
1610
1611 // ignore whitespace at the end of the lines
1612 while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 )
1613 endColumn--;
1614
1615 // increment here because the column which we want to set 'endColumn' to
1616 // is the first whitespace character at the end of the line
1617 endColumn++;
1618
1619 if ( line == spot->startLine() )
1620 startColumn = spot->startColumn();
1621 if ( line == spot->endLine() )
1622 endColumn = spot->endColumn();
1623
1624 // subtract one pixel from
1625 // the right and bottom so that
1626 // we do not overdraw adjacent
1627 // hotspots
1628 //
1629 // subtracting one pixel from all sides also prevents an edge case where
1630 // moving the mouse outside a link could still leave it underlined
1631 // because the check below for the position of the cursor
1632 // finds it on the border of the target area
1633 QRect r;
1634 r.setCoords( startColumn*_fontWidth + 1 + leftMargin,
1635 line*_fontHeight + 1 + _topBaseMargin,
1636 endColumn*_fontWidth - 1 + leftMargin,
1637 (line+1)*_fontHeight - 1 + _topBaseMargin );
1638 // Underline link hotspots
1639 if ( spot->type() == Filter::HotSpot::Link )
1640 {
1641 QFontMetrics metrics(font());
1642
1643 // find the baseline (which is the invisible line that the characters in the font sit on,
1644 // with some having tails dangling below)
1645 int baseline = r.bottom() - metrics.descent();
1646 // find the position of the underline below that
1647 int underlinePos = baseline + metrics.underlinePos();
1648
1649 if ( region.contains( mapFromScene(QCursor::pos()).toPoint() ) ){
1650 painter.drawLine( r.left() , underlinePos , r.right() , underlinePos );
1651 }
1652 }
1653 // Marker hotspots simply have a transparent rectanglular shape
1654 // drawn on top of them
1655 else if ( spot->type() == Filter::HotSpot::Marker )
1656 {
1657 //TODO - Do not use a hardcoded colour for this
1658 painter.fillRect(r,QBrush(QColor(255,0,0,120)));
1659 }
1660 }
1661 }
1662 }
1663
1664 int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const
1665 {
1666 QFontMetrics fm(font());
1667 int result = 0;
1668 for (int column = 0; column < length; column++) {
1669 result += fm.width(_image[loc(startColumn + column, line)].character);
1670 }
1671 return result;
1672 }
1673
1674 QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length) {
1675 int left = _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line);
1676 int top = _fontHeight * line;
1677 int width = _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line);
1678 return {_leftMargin + topLeftX + left,
1679 _topMargin + topLeftY + top,
1680 width,
1681 _fontHeight};
1682 }
1683
1684 void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect)
1685 {
1686 QPoint tL = contentsRect().topLeft();
1687 int tLx = tL.x();
1688 int tLy = tL.y();
1689
1690 int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth));
1691 int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight));
1692 int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth));
1693 int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight));
1694
1695 if(!_image)
1696 return;
1697
1698 const int bufferSize = _usedColumns;
1699 std::wstring unistr;
1700 unistr.reserve(bufferSize);
1701 for (int y = luy; y <= rly; y++)
1702 {
1703 quint32 c = _image[loc(lux,y)].character;
1704 int x = lux;
1705 if(!c && x)
1706 x--; // Search for start of multi-column character
1707 for (; x <= rlx; x++)
1708 {
1709 int len = 1;
1710 int p = 0;
1711
1712 // reset our buffer to the maximal size
1713 unistr.resize(bufferSize);
1714
1715 // is this a single character or a sequence of characters ?
1716 if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR )
1717 {
1718 // sequence of characters
1719 ushort extendedCharLength = 0;
1720 ushort* chars = ExtendedCharTable::instance
1721 .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength);
1722 for ( int index = 0 ; index < extendedCharLength ; index++ )
1723 {
1724 Q_ASSERT( p < bufferSize );
1725 unistr[p++] = chars[index];
1726 }
1727 }
1728 else
1729 {
1730 // single character
1731 c = _image[loc(x,y)].character;
1732 if (c)
1733 {
1734 Q_ASSERT( p < bufferSize );
1735 unistr[p++] = c; //fontMap(c);
1736 }
1737 }
1738
1739 bool lineDraw = isLineChar(c);
1740 bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0);
1741 CharacterColor currentForeground = _image[loc(x,y)].foregroundColor;
1742 CharacterColor currentBackground = _image[loc(x,y)].backgroundColor;
1743 quint8 currentRendition = _image[loc(x,y)].rendition;
1744
1745 while (x+len <= rlx &&
1746 _image[loc(x+len,y)].foregroundColor == currentForeground &&
1747 _image[loc(x+len,y)].backgroundColor == currentBackground &&
1748 _image[loc(x+len,y)].rendition == currentRendition &&
1749 (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth &&
1750 isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment!
1751 {
1752 if (c)
1753 unistr[p++] = c; //fontMap(c);
1754 if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition
1755 len++; // Skip trailing part of multi-column character
1756 len++;
1757 }
1758 if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character))
1759 len++; // Adjust for trailing part of multi-column character
1760
1761 bool save__fixedFont = _fixedFont;
1762 if (lineDraw)
1763 _fixedFont = false;
1764 unistr.resize(p);
1765
1766 // Create a text scaling matrix for double width and double height lines.
1767 QTransform textScale;
1768
1769 if (y < _lineProperties.size())
1770 {
1771 if (_lineProperties[y] & LINE_DOUBLEWIDTH)
1772 textScale.scale(2,1);
1773
1774 if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
1775 textScale.scale(1,2);
1776 }
1777
1778 //Apply text scaling matrix.
1779 paint.setWorldTransform(textScale, true);
1780
1781 //calculate the area in which the text will be drawn
1782 QRect textArea = calculateTextArea(tLx, tLy, x, y, len);
1783
1784 //move the calculated area to take account of scaling applied to the painter.
1785 //the position of the area from the origin (0,0) is scaled
1786 //by the opposite of whatever
1787 //transformation has been applied to the painter. this ensures that
1788 //painting does actually start from textArea.topLeft()
1789 //(instead of textArea.topLeft() * painter-scale)
1790 textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) );
1791
1792 //paint text fragment
1793 drawTextFragment( paint,
1794 textArea,
1795 unistr,
1796 &_image[loc(x,y)] ); //,
1797 //0,
1798 //!_isPrinting );
1799
1800 _fixedFont = save__fixedFont;
1801
1802 //reset back to single-width, single-height _lines
1803 paint.setWorldTransform(textScale.inverted(), true);
1804
1805 if (y < _lineProperties.size()-1)
1806 {
1807 //double-height _lines are represented by two adjacent _lines
1808 //containing the same characters
1809 //both _lines will have the LINE_DOUBLEHEIGHT attribute.
1810 //If the current line has the LINE_DOUBLEHEIGHT attribute,
1811 //we can therefore skip the next line
1812 if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
1813 y++;
1814 }
1815
1816 x += len - 1;
1817 }
1818 }
1819 }
1820
1821 void TerminalDisplay::blinkEvent()
1822 {
1823 if (!_allowBlinkingText) return;
1824
1825 _blinking = !_blinking;
1826
1827 //TODO: Optimize to only repaint the areas of the widget
1828 // where there is blinking text
1829 // rather than repainting the whole widget.
1830 update();
1831 }
1832
1833 QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const
1834 {
1835 QRect result;
1836 result.setLeft( _leftMargin + _fontWidth * imageArea.left() );
1837 result.setTop( _topMargin + _fontHeight * imageArea.top() );
1838 result.setWidth( _fontWidth * imageArea.width() );
1839 result.setHeight( _fontHeight * imageArea.height() );
1840
1841 return result;
1842 }
1843
1844 void TerminalDisplay::updateCursor()
1845 {
1846 QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) );
1847 update(cursorRect);
1848 }
1849
1850 void TerminalDisplay::blinkCursorEvent()
1851 {
1852 _cursorBlinking = !_cursorBlinking;
1853 updateCursor();
1854 }
1855
1856 /* ------------------------------------------------------------------------- */
1857 /* */
1858 /* Resizing */
1859 /* */
1860 /* ------------------------------------------------------------------------- */
1861
1862 void TerminalDisplay::resizeEvent(QResizeEvent*)
1863 {
1864 updateImageSize();
1865 processFilters();
1866 }
1867
1868 void TerminalDisplay::propagateSize()
1869 {
1870 if (_isFixedSize)
1871 {
1872 setSize(_columns, _lines);
1873 //QWidget::setFixedSize(sizeHint());
1874 //parentWidget()->adjustSize();
1875 //parentWidget()->setFixedSize(parentWidget()->sizeHint());
1876 return;
1877 }
1878 if (_image)
1879 updateImageSize();
1880 }
1881
1882 void TerminalDisplay::updateImageSize()
1883 {
1884 Character* oldimg = _image;
1885 int oldlin = _lines;
1886 int oldcol = _columns;
1887
1888 makeImage();
1889
1890 // copy the old image to reduce flicker
1891 int lines = qMin(oldlin,_lines);
1892 int columns = qMin(oldcol,_columns);
1893
1894 if (oldimg)
1895 {
1896 for (int line = 0; line < lines; line++)
1897 {
1898 memcpy((void*)&_image[_columns*line],
1899 (void*)&oldimg[oldcol*line],columns*sizeof(Character));
1900 }
1901 delete[] oldimg;
1902 }
1903
1904 if (_screenWindow)
1905 _screenWindow->setWindowLines(_lines);
1906
1907 _resizing = (oldlin!=_lines) || (oldcol!=_columns);
1908
1909 if ( _resizing )
1910 {
1911 showResizeNotification();
1912 emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent
1913 }
1914
1915 _resizing = false;
1916 }
1917
1918 //showEvent and hideEvent are reimplemented here so that it appears to other classes that the
1919 //display has been resized when the display is hidden or shown.
1920 //
1921 //TODO: Perhaps it would be better to have separate signals for show and hide instead of using
1922 //the same signal as the one for a content size change
1923 void TerminalDisplay::showEvent(QShowEvent*)
1924 {
1925 emit changedContentSizeSignal(_contentHeight,_contentWidth);
1926 }
1927 void TerminalDisplay::hideEvent(QHideEvent*)
1928 {
1929 emit changedContentSizeSignal(_contentHeight,_contentWidth);
1930 }
1931
1932 /* ------------------------------------------------------------------------- */
1933 /* */
1934 /* Scrollbar */
1935 /* */
1936 /* ------------------------------------------------------------------------- */
1937
1938 void TerminalDisplay::scrollBarPositionChanged(int)
1939 {
1940 if ( !_screenWindow )
1941 return;
1942
1943 _screenWindow->scrollTo( _scrollBar->value() );
1944
1945 // if the thumb has been moved to the bottom of the _scrollBar then set
1946 // the display to automatically track new output,
1947 // that is, scroll down automatically
1948 // to how new _lines as they are added
1949 const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum());
1950 _screenWindow->setTrackOutput( atEndOfOutput );
1951
1952 updateImage();
1953
1954 // QMLTermWidget: notify qml side of the change only when needed.
1955 emit scrollbarValueChanged();
1956 }
1957
1958 void TerminalDisplay::setScroll(int cursor, int slines)
1959 {
1960 // update _scrollBar if the range or value has changed,
1961 // otherwise return
1962 //
1963 // setting the range or value of a _scrollBar will always trigger
1964 // a repaint, so it should be avoided if it is not necessary
1965 if ( _scrollBar->minimum() == 0 &&
1966 _scrollBar->maximum() == (slines - _lines) &&
1967 _scrollBar->value() == cursor )
1968 {
1969 return;
1970 }
1971
1972 disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
1973 _scrollBar->setRange(0,slines - _lines);
1974 _scrollBar->setSingleStep(1);
1975 _scrollBar->setPageStep(_lines);
1976 _scrollBar->setValue(cursor);
1977 connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
1978 }
1979
1980 void TerminalDisplay::scrollToEnd()
1981 {
1982 disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
1983 _scrollBar->setValue( _scrollBar->maximum() );
1984 connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
1985
1986 _screenWindow->scrollTo( _scrollBar->value() + 1 );
1987 _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() );
1988 }
1989
1990 void TerminalDisplay::setScrollBarPosition(QTermWidget::ScrollBarPosition position)
1991 {
1992 if (_scrollbarLocation == position)
1993 return;
1994
1995 if ( position == QTermWidget::NoScrollBar )
1996 _scrollBar->hide();
1997 else
1998 _scrollBar->show();
1999
2000 _topMargin = _leftMargin = 1;
2001 _scrollbarLocation = position;
2002
2003 propagateSize();
2004 update();
2005 }
2006
2007 void TerminalDisplay::mousePressEvent(QMouseEvent* ev)
2008 {
2009 if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) {
2010 mouseTripleClickEvent(ev);
2011 return;
2012 }
2013
2014 if ( !contentsRect().contains(ev->pos()) ) return;
2015
2016 if ( !_screenWindow ) return;
2017
2018 int charLine;
2019 int charColumn;
2020 getCharacterPosition(ev->pos(),charLine,charColumn);
2021 QPoint pos = QPoint(charColumn,charLine);
2022
2023 if ( ev->button() == Qt::LeftButton)
2024 {
2025 _lineSelectionMode = false;
2026 _wordSelectionMode = false;
2027
2028 emit isBusySelecting(true); // Keep it steady...
2029 // Drag only when the Control key is hold
2030 bool selected = false;
2031
2032 // The receiver of the testIsSelected() signal will adjust
2033 // 'selected' accordingly.
2034 //emit testIsSelected(pos.x(), pos.y(), selected);
2035
2036 selected = _screenWindow->isSelected(pos.x(),pos.y());
2037
2038 if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) {
2039 // The user clicked inside selected text
2040 dragInfo.state = diPending;
2041 dragInfo.start = ev->pos();
2042 }
2043 else {
2044 // No reason to ever start a drag event
2045 dragInfo.state = diNone;
2046
2047 _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) );
2048 _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier);
2049
2050 if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier))
2051 {
2052 _screenWindow->clearSelection();
2053
2054 //emit clearSelectionSignal();
2055 pos.ry() += _scrollBar->value();
2056 _iPntSel = _pntSel = pos;
2057 _actSel = 1; // left mouse button pressed but nothing selected yet.
2058
2059 }
2060 else
2061 {
2062 emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0);
2063 }
2064
2065 Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn);
2066 if (spot && spot->type() == Filter::HotSpot::Link)
2067 spot->activate(QLatin1String("click-action"));
2068 }
2069 }
2070 else if ( ev->button() == Qt::MidButton )
2071 {
2072 if ( _mouseMarks || (ev->modifiers() & Qt::ShiftModifier) )
2073 emitSelection(true,ev->modifiers() & Qt::ControlModifier);
2074 else
2075 emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
2076 }
2077 else if ( ev->button() == Qt::RightButton )
2078 {
2079 if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier))
2080 emit configureRequest(ev->pos());
2081 else
2082 emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
2083 }
2084 }
2085
2086 QList<QAction*> TerminalDisplay::filterActions(const QPoint& position)
2087 {
2088 int charLine, charColumn;
2089 getCharacterPosition(position,charLine,charColumn);
2090
2091 Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn);
2092
2093 return spot ? spot->actions() : QList<QAction*>();
2094 }
2095
2096 void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev)
2097 {
2098 int charLine = 0;
2099 int charColumn = 0;
2100 int leftMargin = _leftBaseMargin
2101 + ((_scrollbarLocation == QTermWidget::ScrollBarLeft
2102 && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar))
2103 ? _scrollBar->width() : 0);
2104
2105 getCharacterPosition(ev->pos(),charLine,charColumn);
2106
2107 // handle filters
2108 // change link hot-spot appearance on mouse-over
2109 Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn);
2110 if ( spot && spot->type() == Filter::HotSpot::Link)
2111 {
2112 QRegion previousHotspotArea = _mouseOverHotspotArea;
2113 _mouseOverHotspotArea = QRegion();
2114 QRect r;
2115 if (spot->startLine()==spot->endLine()) {
2116 r.setCoords( spot->startColumn()*_fontWidth + leftMargin,
2117 spot->startLine()*_fontHeight + _topBaseMargin,
2118 spot->endColumn()*_fontWidth + leftMargin,
2119 (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin );
2120 _mouseOverHotspotArea |= r;
2121 } else {
2122 r.setCoords( spot->startColumn()*_fontWidth + leftMargin,
2123 spot->startLine()*_fontHeight + _topBaseMargin,
2124 _columns*_fontWidth - 1 + leftMargin,
2125 (spot->startLine()+1)*_fontHeight + _topBaseMargin );
2126 _mouseOverHotspotArea |= r;
2127 for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) {
2128 r.setCoords( 0*_fontWidth + leftMargin,
2129 line*_fontHeight + _topBaseMargin,
2130 _columns*_fontWidth + leftMargin,
2131 (line+1)*_fontHeight + _topBaseMargin );
2132 _mouseOverHotspotArea |= r;
2133 }
2134 r.setCoords( 0*_fontWidth + leftMargin,
2135 spot->endLine()*_fontHeight + _topBaseMargin,
2136 spot->endColumn()*_fontWidth + leftMargin,
2137 (spot->endLine()+1)*_fontHeight + _topBaseMargin );
2138 _mouseOverHotspotArea |= r;
2139 }
2140 update( _mouseOverHotspotArea | previousHotspotArea );
2141 }
2142 else if ( !_mouseOverHotspotArea.isEmpty() )
2143 {
2144 update( _mouseOverHotspotArea );
2145 // set hotspot area to an invalid rectangle
2146 _mouseOverHotspotArea = QRegion();
2147 }
2148
2149 // for auto-hiding the cursor, we need mouseTracking
2150 if (ev->buttons() == Qt::NoButton ) return;
2151
2152 // if the terminal is interested in mouse movements
2153 // then emit a mouse movement signal, unless the shift
2154 // key is being held down, which overrides this.
2155 if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
2156 {
2157 int button = 3;
2158 if (ev->buttons() & Qt::LeftButton)
2159 button = 0;
2160 if (ev->buttons() & Qt::MidButton)
2161 button = 1;
2162 if (ev->buttons() & Qt::RightButton)
2163 button = 2;
2164
2165
2166 emit mouseSignal( button,
2167 charColumn + 1,
2168 charLine + 1 +_scrollBar->value() -_scrollBar->maximum(),
2169 1 );
2170
2171 return;
2172 }
2173
2174 if (dragInfo.state == diPending)
2175 {
2176 // we had a mouse down, but haven't confirmed a drag yet
2177 // if the mouse has moved sufficiently, we will confirm
2178
2179 // int distance = KGlobalSettings::dndEventDelay();
2180 int distance = QApplication::startDragDistance();
2181 if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance ||
2182 ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance)
2183 {
2184 // we've left the drag square, we can start a real drag operation now
2185 emit isBusySelecting(false); // Ok.. we can breath again.
2186
2187 _screenWindow->clearSelection();
2188 doDrag();
2189 }
2190 return;
2191 }
2192 else if (dragInfo.state == diDragging)
2193 {
2194 // this isn't technically needed because mouseMoveEvent is suppressed during
2195 // Qt drag operations, replaced by dragMoveEvent
2196 return;
2197 }
2198
2199 if (_actSel == 0) return;
2200
2201 // don't extend selection while pasting
2202 if (ev->buttons() & Qt::MidButton) return;
2203
2204 extendSelection( ev->pos() );
2205 }
2206
2207 void TerminalDisplay::extendSelection( const QPoint& position )
2208 {
2209 QPoint pos = position;
2210
2211 if ( !_screenWindow )
2212 return;
2213
2214 //if ( !contentsRect().contains(ev->pos()) ) return;
2215 QPoint tL = contentsRect().topLeft();
2216 int tLx = tL.x();
2217 int tLy = tL.y();
2218 int scroll = _scrollBar->value();
2219
2220 // we're in the process of moving the mouse with the left button pressed
2221 // the mouse cursor will kept caught within the bounds of the text in
2222 // this widget.
2223
2224 int linesBeyondWidget = 0;
2225
2226 QRect textBounds(tLx + _leftMargin,
2227 tLy + _topMargin,
2228 _usedColumns*_fontWidth-1,
2229 _usedLines*_fontHeight-1);
2230
2231 // Adjust position within text area bounds.
2232 QPoint oldpos = pos;
2233
2234 pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) );
2235 pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) );
2236
2237 if ( oldpos.y() > textBounds.bottom() )
2238 {
2239 linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight;
2240 _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward
2241 }
2242 if ( oldpos.y() < textBounds.top() )
2243 {
2244 linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight;
2245 _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history
2246 }
2247
2248 int charColumn = 0;
2249 int charLine = 0;
2250 getCharacterPosition(pos,charLine,charColumn);
2251
2252 QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight);
2253 QPoint ohere;
2254 QPoint _iPntSelCorr = _iPntSel;
2255 _iPntSelCorr.ry() -= _scrollBar->value();
2256 QPoint _pntSelCorr = _pntSel;
2257 _pntSelCorr.ry() -= _scrollBar->value();
2258 bool swapping = false;
2259
2260 if ( _wordSelectionMode )
2261 {
2262 // Extend to word boundaries
2263 int i;
2264 QChar selClass;
2265
2266 bool left_not_right = ( here.y() < _iPntSelCorr.y() ||
2267 ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) );
2268 bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() ||
2269 ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) );
2270 swapping = left_not_right != old_left_not_right;
2271
2272 // Find left (left_not_right ? from here : from start)
2273 QPoint left = left_not_right ? here : _iPntSelCorr;
2274 i = loc(left.x(),left.y());
2275 if (i>=0 && i<=_imageSize) {
2276 selClass = charClass(_image[i].character);
2277 while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) ))
2278 && charClass(_image[i-1].character) == selClass )
2279 { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} }
2280 }
2281
2282 // Find left (left_not_right ? from start : from here)
2283 QPoint right = left_not_right ? _iPntSelCorr : here;
2284 i = loc(right.x(),right.y());
2285 if (i>=0 && i<=_imageSize) {
2286 selClass = charClass(_image[i].character);
2287 while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) ))
2288 && charClass(_image[i+1].character) == selClass )
2289 { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } }
2290 }
2291
2292 // Pick which is start (ohere) and which is extension (here)
2293 if ( left_not_right )
2294 {
2295 here = left; ohere = right;
2296 }
2297 else
2298 {
2299 here = right; ohere = left;
2300 }
2301 ohere.rx()++;
2302 }
2303
2304 if ( _lineSelectionMode )
2305 {
2306 // Extend to complete line
2307 bool above_not_below = ( here.y() < _iPntSelCorr.y() );
2308
2309 QPoint above = above_not_below ? here : _iPntSelCorr;
2310 QPoint below = above_not_below ? _iPntSelCorr : here;
2311
2312 while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) )
2313 above.ry()--;
2314 while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) )
2315 below.ry()++;
2316
2317 above.setX(0);
2318 below.setX(_usedColumns-1);
2319
2320 // Pick which is start (ohere) and which is extension (here)
2321 if ( above_not_below )
2322 {
2323 here = above; ohere = below;
2324 }
2325 else
2326 {
2327 here = below; ohere = above;
2328 }
2329
2330 QPoint newSelBegin = QPoint( ohere.x(), ohere.y() );
2331 swapping = !(_tripleSelBegin==newSelBegin);
2332 _tripleSelBegin = newSelBegin;
2333
2334 ohere.rx()++;
2335 }
2336
2337 int offset = 0;
2338 if ( !_wordSelectionMode && !_lineSelectionMode )
2339 {
2340 int i;
2341 QChar selClass;
2342
2343 bool left_not_right = ( here.y() < _iPntSelCorr.y() ||
2344 ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) );
2345 bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() ||
2346 ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) );
2347 swapping = left_not_right != old_left_not_right;
2348
2349 // Find left (left_not_right ? from here : from start)
2350 QPoint left = left_not_right ? here : _iPntSelCorr;
2351
2352 // Find left (left_not_right ? from start : from here)
2353 QPoint right = left_not_right ? _iPntSelCorr : here;
2354 if ( right.x() > 0 && !_columnSelectionMode )
2355 {
2356 i = loc(right.x(),right.y());
2357 if (i>=0 && i<=_imageSize) {
2358 selClass = charClass(_image[i-1].character);
2359 /* if (selClass == ' ')
2360 {
2361 while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) &&
2362 !(_lineProperties[right.y()] & LINE_WRAPPED))
2363 { i++; right.rx()++; }
2364 if (right.x() < _usedColumns-1)
2365 right = left_not_right ? _iPntSelCorr : here;
2366 else
2367 right.rx()++; // will be balanced later because of offset=-1;
2368 }*/
2369 }
2370 }
2371
2372 // Pick which is start (ohere) and which is extension (here)
2373 if ( left_not_right )
2374 {
2375 here = left; ohere = right; offset = 0;
2376 }
2377 else
2378 {
2379 here = right; ohere = left; offset = -1;
2380 }
2381 }
2382
2383 if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved
2384
2385 if (here == ohere) return; // It's not left, it's not right.
2386
2387 if ( _actSel < 2 || swapping )
2388 {
2389 if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode )
2390 {
2391 _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true );
2392 }
2393 else
2394 {
2395 _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false );
2396 }
2397
2398 }
2399
2400 _actSel = 2; // within selection
2401 _pntSel = here;
2402 _pntSel.ry() += _scrollBar->value();
2403
2404 if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode )
2405 {
2406 _screenWindow->setSelectionEnd( here.x() , here.y() );
2407 }
2408 else
2409 {
2410 _screenWindow->setSelectionEnd( here.x()+offset , here.y() );
2411 }
2412
2413 }
2414
2415 void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev)
2416 {
2417 if ( !_screenWindow )
2418 return;
2419
2420 int charLine;
2421 int charColumn;
2422 getCharacterPosition(ev->pos(),charLine,charColumn);
2423
2424 if ( ev->button() == Qt::LeftButton)
2425 {
2426 emit isBusySelecting(false);
2427 if(dragInfo.state == diPending)
2428 {
2429 // We had a drag event pending but never confirmed. Kill selection
2430 _screenWindow->clearSelection();
2431 //emit clearSelectionSignal();
2432 }
2433 else
2434 {
2435 if ( _actSel > 1 )
2436 {
2437 setSelection( _screenWindow->selectedText(_preserveLineBreaks) );
2438 }
2439
2440 _actSel = 0;
2441
2442 //FIXME: emits a release event even if the mouse is
2443 // outside the range. The procedure used in `mouseMoveEvent'
2444 // applies here, too.
2445
2446 if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
2447 emit mouseSignal( 0,
2448 charColumn + 1,
2449 charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 2);
2450 }
2451 dragInfo.state = diNone;
2452 }
2453
2454
2455 if ( !_mouseMarks &&
2456 ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier))
2457 || ev->button() == Qt::MidButton) )
2458 {
2459 emit mouseSignal( ev->button() == Qt::MidButton ? 1 : 2,
2460 charColumn + 1,
2461 charLine + 1 +_scrollBar->value() -_scrollBar->maximum() ,
2462 2);
2463 }
2464 }
2465
2466 void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const
2467 {
2468 line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight;
2469 if (line < 0)
2470 line = 0;
2471 if (line >= _usedLines)
2472 line = _usedLines - 1;
2473
2474 int x = widgetPoint.x() + _fontWidth / 2 - contentsRect().left() - _leftMargin;
2475 if ( _fixedFont )
2476 column = x / _fontWidth;
2477 else
2478 {
2479 column = 0;
2480 while(column + 1 < _usedColumns && x > textWidth(0, column + 1, line))
2481 column++;
2482 }
2483
2484 if ( column < 0 )
2485 column = 0;
2486
2487 // the column value returned can be equal to _usedColumns, which
2488 // is the position just after the last character displayed in a line.
2489 //
2490 // this is required so that the user can select characters in the right-most
2491 // column (or left-most for right-to-left input)
2492 if ( column > _usedColumns )
2493 column = _usedColumns;
2494 }
2495
2496 void TerminalDisplay::updateFilters()
2497 {
2498 if ( !_screenWindow )
2499 return;
2500
2501 processFilters();
2502 }
2503
2504 void TerminalDisplay::updateLineProperties()
2505 {
2506 if ( !_screenWindow )
2507 return;
2508
2509 _lineProperties = _screenWindow->getLineProperties();
2510 }
2511
2512 void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev)
2513 {
2514 if ( ev->button() != Qt::LeftButton) return;
2515 if ( !_screenWindow ) return;
2516
2517 int charLine = 0;
2518 int charColumn = 0;
2519
2520 getCharacterPosition(ev->pos(),charLine,charColumn);
2521
2522 QPoint pos(charColumn,charLine);
2523
2524 // pass on double click as two clicks.
2525 if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier))
2526 {
2527 // Send just _ONE_ click event, since the first click of the double click
2528 // was already sent by the click handler
2529 emit mouseSignal( 0,
2530 pos.x()+1,
2531 pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(),
2532 0 ); // left button
2533 return;
2534 }
2535
2536 _screenWindow->clearSelection();
2537 QPoint bgnSel = pos;
2538 QPoint endSel = pos;
2539 int i = loc(bgnSel.x(),bgnSel.y());
2540 _iPntSel = bgnSel;
2541 _iPntSel.ry() += _scrollBar->value();
2542
2543 _wordSelectionMode = true;
2544
2545 // find word boundaries...
2546 QChar selClass = charClass(_image[i].character);
2547 {
2548 // find the start of the word
2549 int x = bgnSel.x();
2550 while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) ))
2551 && charClass(_image[i-1].character) == selClass )
2552 {
2553 i--;
2554 if (x>0)
2555 x--;
2556 else
2557 {
2558 x=_usedColumns-1;
2559 bgnSel.ry()--;
2560 }
2561 }
2562
2563 bgnSel.setX(x);
2564 _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false );
2565
2566 // find the end of the word
2567 i = loc( endSel.x(), endSel.y() );
2568 x = endSel.x();
2569 while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) ))
2570 && charClass(_image[i+1].character) == selClass )
2571 {
2572 i++;
2573 if (x<_usedColumns-1)
2574 x++;
2575 else
2576 {
2577 x=0;
2578 endSel.ry()++;
2579 }
2580 }
2581
2582 endSel.setX(x);
2583
2584 // In word selection mode don't select @ (64) if at end of word.
2585 if ( ( QChar( _image[i].character ) == QLatin1Char('@') ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) )
2586 endSel.setX( x - 1 );
2587
2588
2589 _actSel = 2; // within selection
2590
2591 _screenWindow->setSelectionEnd( endSel.x() , endSel.y() );
2592
2593 setSelection( _screenWindow->selectedText(_preserveLineBreaks) );
2594 }
2595
2596 _possibleTripleClick=true;
2597
2598 QTimer::singleShot(QApplication::doubleClickInterval(),this,
2599 SLOT(tripleClickTimeout()));
2600 }
2601
2602 void TerminalDisplay::wheelEvent( QWheelEvent* ev )
2603 {
2604 if (ev->orientation() != Qt::Vertical)
2605 return;
2606
2607 // if the terminal program is not interested mouse events
2608 // then send the event to the scrollbar if the slider has room to move
2609 // or otherwise send simulated up / down key presses to the terminal program
2610 // for the benefit of programs such as 'less'
2611 if ( _mouseMarks )
2612 {
2613 bool canScroll = _scrollBar->maximum() > 0;
2614 if (canScroll)
2615 _scrollBar->event(ev);
2616 else
2617 {
2618 // assume that each Up / Down key event will cause the terminal application
2619 // to scroll by one line.
2620 //
2621 // to get a reasonable scrolling speed, scroll by one line for every 5 degrees
2622 // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees,
2623 // giving a scroll of 3 lines
2624 int key = ev->delta() > 0 ? Qt::Key_Up : Qt::Key_Down;
2625
2626 // QWheelEvent::delta() gives rotation in eighths of a degree
2627 int wheelDegrees = ev->delta() / 8;
2628 int linesToScroll = abs(wheelDegrees) / 5;
2629
2630 QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier);
2631
2632 for (int i=0;i<linesToScroll;i++)
2633 emit keyPressedSignal(&keyScrollEvent, false);
2634 }
2635 }
2636 else
2637 {
2638 // terminal program wants notification of mouse activity
2639
2640 int charLine;
2641 int charColumn;
2642 getCharacterPosition( ev->pos() , charLine , charColumn );
2643
2644 emit mouseSignal( ev->delta() > 0 ? 4 : 5,
2645 charColumn + 1,
2646 charLine + 1 +_scrollBar->value() -_scrollBar->maximum() ,
2647 0);
2648 }
2649 }
2650
2651 void TerminalDisplay::tripleClickTimeout()
2652 {
2653 _possibleTripleClick=false;
2654 }
2655
2656 void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev)
2657 {
2658 if ( !_screenWindow ) return;
2659
2660 int charLine;
2661 int charColumn;
2662 getCharacterPosition(ev->pos(),charLine,charColumn);
2663 _iPntSel = QPoint(charColumn,charLine);
2664
2665 _screenWindow->clearSelection();
2666
2667 _lineSelectionMode = true;
2668 _wordSelectionMode = false;
2669
2670 _actSel = 2; // within selection
2671 emit isBusySelecting(true); // Keep it steady...
2672
2673 while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) )
2674 _iPntSel.ry()--;
2675
2676 if (_tripleClickMode == SelectForwardsFromCursor) {
2677 // find word boundary start
2678 int i = loc(_iPntSel.x(),_iPntSel.y());
2679 QChar selClass = charClass(_image[i].character);
2680 int x = _iPntSel.x();
2681
2682 while ( ((x>0) ||
2683 (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) )
2684 )
2685 && charClass(_image[i-1].character) == selClass )
2686 {
2687 i--;
2688 if (x>0)
2689 x--;
2690 else
2691 {
2692 x=_columns-1;
2693 _iPntSel.ry()--;
2694 }
2695 }
2696
2697 _screenWindow->setSelectionStart( x , _iPntSel.y() , false );
2698 _tripleSelBegin = QPoint( x, _iPntSel.y() );
2699 }
2700 else if (_tripleClickMode == SelectWholeLine) {
2701 _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false );
2702 _tripleSelBegin = QPoint( 0, _iPntSel.y() );
2703 }
2704
2705 while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) )
2706 _iPntSel.ry()++;
2707
2708 _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() );
2709
2710 setSelection(_screenWindow->selectedText(_preserveLineBreaks));
2711
2712 _iPntSel.ry() += _scrollBar->value();
2713 }
2714
2715
2716 bool TerminalDisplay::focusNextPrevChild( bool next )
2717 {
2718 if (next)
2719 return false; // This disables changing the active part in konqueror
2720 // when pressing Tab
2721 return false;
2722 //return QWidget::focusNextPrevChild( next );
2723 }
2724
2725
2726 QChar TerminalDisplay::charClass(QChar qch) const
2727 {
2728 if ( qch.isSpace() ) return QLatin1Char(' ');
2729
2730 if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) )
2731 return QLatin1Char('a');
2732
2733 return qch;
2734 }
2735
2736 void TerminalDisplay::setWordCharacters(const QString& wc)
2737 {
2738 _wordCharacters = wc;
2739 }
2740
2741 void TerminalDisplay::setUsesMouse(bool on)
2742 {
2743 if (_mouseMarks != on) {
2744 _mouseMarks = on;
2745 setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor );
2746 emit usesMouseChanged();
2747 }
2748 }
2749 bool TerminalDisplay::usesMouse() const
2750 {
2751 return _mouseMarks;
2752 }
2753
2754 void TerminalDisplay::setBracketedPasteMode(bool on)
2755 {
2756 _bracketedPasteMode = on;
2757 }
2758 bool TerminalDisplay::bracketedPasteMode() const
2759 {
2760 return _bracketedPasteMode;
2761 }
2762
2763 /* ------------------------------------------------------------------------- */
2764 /* */
2765 /* Clipboard */
2766 /* */
2767 /* ------------------------------------------------------------------------- */
2768
2769 #undef KeyPress
2770
2771 void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn)
2772 {
2773 if ( !_screenWindow )
2774 return;
2775
2776 // Paste Clipboard by simulating keypress events
2777 QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection :
2778 QClipboard::Clipboard);
2779 if ( ! text.isEmpty() )
2780 {
2781 text.replace(QLatin1String("\r\n"), QLatin1String("\n"));
2782 text.replace(QLatin1Char('\n'), QLatin1Char('\r'));
2783
2784 if (_trimPastedTrailingNewlines) {
2785 text.replace(QRegularExpression(QStringLiteral("\\r+$")), QString());
2786 }
2787
2788 // TODO QMLTERMWIDGET We should expose this as a signal.
2789 // if (_confirmMultilinePaste && text.contains(QLatin1Char('\r'))) {
2790 // QMessageBox confirmation(this);
2791 // confirmation.setWindowTitle(tr("Paste multiline text"));
2792 // confirmation.setText(tr("Are you sure you want to paste this text?"));
2793 // confirmation.setDetailedText(text);
2794 // confirmation.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
2795 // // Click "Show details..." to show those by default
2796 // const auto buttons = confirmation.buttons();
2797 // for( QAbstractButton * btn : buttons ) {
2798 // if (confirmation.buttonRole(btn) == QMessageBox::ActionRole && btn->text() == QMessageBox::tr("Show Details...")) {
2799 // Q_EMIT btn->clicked();
2800 // break;
2801 // }
2802 // }
2803 // confirmation.setDefaultButton(QMessageBox::Yes);
2804 // confirmation.exec();
2805 // if (confirmation.standardButton(confirmation.clickedButton()) != QMessageBox::Yes) {
2806 // return;
2807 // }
2808 // }
2809
2810 bracketText(text);
2811
2812 // appendReturn is intentionally handled _after_ enclosing texts with brackets as
2813 // that feature is used to allow execution of commands immediately after paste.
2814 // Ref: https://bugs.kde.org/show_bug.cgi?id=16179
2815 // Ref: https://github.com/KDE/konsole/commit/83d365f2ebfe2e659c1e857a2f5f247c556ab571
2816 if(appendReturn) {
2817 text.append(QLatin1Char('\r'));
2818 }
2819
2820 QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text);
2821 emit keyPressedSignal(&e, true); // expose as a big fat keypress event
2822
2823 _screenWindow->clearSelection();
2824
2825 switch(mMotionAfterPasting)
2826 {
2827 case MoveStartScreenWindow:
2828 // Temporarily stop tracking output, or pasting contents triggers
2829 // ScreenWindow::notifyOutputChanged() and the latter scrolls the
2830 // terminal to the last line. It will be re-enabled when needed
2831 // (e.g., scrolling to the last line).
2832 _screenWindow->setTrackOutput(false);
2833 _screenWindow->scrollTo(0);
2834 break;
2835 case MoveEndScreenWindow:
2836 scrollToEnd();
2837 break;
2838 case NoMoveScreenWindow:
2839 break;
2840 }
2841 }
2842 }
2843
2844 void TerminalDisplay::bracketText(QString& text) const
2845 {
2846 if (bracketedPasteMode() && !_disabledBracketedPasteMode)
2847 {
2848 text.prepend(QLatin1String("\033[200~"));
2849 text.append(QLatin1String("\033[201~"));
2850 }
2851 }
2852
2853 void TerminalDisplay::setSelection(const QString& t)
2854 {
2855 if (QApplication::clipboard()->supportsSelection())
2856 {
2857 QApplication::clipboard()->setText(t, QClipboard::Selection);
2858 }
2859 }
2860
2861 void TerminalDisplay::copyClipboard()
2862 {
2863 if ( !_screenWindow )
2864 return;
2865
2866 QString text = _screenWindow->selectedText(_preserveLineBreaks);
2867 if (!text.isEmpty())
2868 QApplication::clipboard()->setText(text);
2869 }
2870
2871 void TerminalDisplay::pasteClipboard()
2872 {
2873 emitSelection(false,false);
2874 }
2875
2876 void TerminalDisplay::pasteSelection()
2877 {
2878 emitSelection(true,false);
2879 }
2880
•2881 bool TerminalDisplay::isClipboardEmpty()
2882 {
2883 return QApplication::clipboard()->text().isEmpty();
2884 }
2885
2886 bool TerminalDisplay::isSelectionEmpty()
2887 {
2888 return _screenWindow->selectedText(_preserveLineBreaks).isEmpty();
2889 }
2890
2891 void TerminalDisplay::setConfirmMultilinePaste(bool confirmMultilinePaste) {
2892 _confirmMultilinePaste = confirmMultilinePaste;
2893 }
2894
2895 void TerminalDisplay::setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) {
2896 _trimPastedTrailingNewlines = trimPastedTrailingNewlines;
2897 }
2898
2899 /* ------------------------------------------------------------------------- */
2900 /* */
2901 /* Keyboard */
2902 /* */
2903 /* ------------------------------------------------------------------------- */
2904
2905 void TerminalDisplay::setFlowControlWarningEnabled( bool enable )
2906 {
2907 _flowControlWarningEnabled = enable;
2908
2909 // if the dialog is currently visible and the flow control warning has
2910 // been disabled then hide the dialog
2911 if (!enable)
2912 outputSuspended(false);
2913 }
2914
2915 void TerminalDisplay::setMotionAfterPasting(MotionAfterPasting action)
2916 {
2917 mMotionAfterPasting = action;
2918 }
2919
2920 int TerminalDisplay::motionAfterPasting()
2921 {
2922 return mMotionAfterPasting;
2923 }
2924
2925 void TerminalDisplay::keyPressEvent( QKeyEvent* event )
2926 {
2927 _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't
2928 // know where the current selection is.
2929
2930 if (_hasBlinkingCursor)
2931 {
2932 _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2);
2933 if (_cursorBlinking)
2934 blinkCursorEvent();
2935 else
2936 _cursorBlinking = false;
2937 }
2938
2939 emit keyPressedSignal(event, false);
2940
2941 event->accept();
2942 }
2943
2944 void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event )
2945 {
2946 QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString());
2947 emit keyPressedSignal(&keyEvent, false);
2948
2949 _inputMethodData.preeditString = event->preeditString().toStdWString();
2950 update(preeditRect() | _inputMethodData.previousPreeditRect);
2951
2952 event->accept();
2953 }
2954
2955 void TerminalDisplay::inputMethodQuery(QInputMethodQueryEvent *event)
2956 {
2957 event->setValue(Qt::ImEnabled, true);
2958 event->setValue(Qt::ImHints, QVariant(Qt::ImhNoPredictiveText | Qt::ImhNoAutoUppercase));
2959 event->accept();
2960 }
2961
2962 QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const
2963 {
2964 const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0);
2965 switch ( query )
2966 {
2967 case Qt::ImMicroFocus:
2968 return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1));
2969 break;
2970 case Qt::ImFont:
2971 return font();
2972 break;
2973 case Qt::ImCursorPosition:
2974 // return the cursor position within the current line
2975 return cursorPos.x();
2976 break;
2977 case Qt::ImSurroundingText:
2978 {
2979 // return the text from the current line
2980 QString lineText;
2981 QTextStream stream(&lineText);
2982 PlainTextDecoder decoder;
2983 decoder.begin(&stream);
2984 decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]);
2985 decoder.end();
2986 return lineText;
2987 }
2988 break;
2989 case Qt::ImCurrentSelection:
2990 return QString();
2991 break;
2992 default:
2993 break;
2994 }
2995
2996 return QVariant();
2997 }
2998
2999 bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent)
3000 {
3001 int modifiers = keyEvent->modifiers();
3002
3003 // When a possible shortcut combination is pressed,
3004 // emit the overrideShortcutCheck() signal to allow the host
3005 // to decide whether the terminal should override it or not.
3006 if (modifiers != Qt::NoModifier)
3007 {
3008 int modifierCount = 0;
3009 unsigned int currentModifier = Qt::ShiftModifier;
3010
3011 while (currentModifier <= Qt::KeypadModifier)
3012 {
3013 if (modifiers & currentModifier)
3014 modifierCount++;
3015 currentModifier <<= 1;
3016 }
3017 if (modifierCount < 2)
3018 {
3019 bool override = false;
3020 emit overrideShortcutCheck(keyEvent,override);
3021 if (override)
3022 {
3023 keyEvent->accept();
3024 return true;
3025 }
3026 }
3027 }
3028
3029 // Override any of the following shortcuts because
3030 // they are needed by the terminal
3031 int keyCode = keyEvent->key() | modifiers;
3032 switch ( keyCode )
3033 {
3034 // list is taken from the QLineEdit::event() code
3035 case Qt::Key_Tab:
3036 case Qt::Key_Delete:
3037 case Qt::Key_Home:
3038 case Qt::Key_End:
3039 case Qt::Key_Backspace:
3040 case Qt::Key_Left:
3041 case Qt::Key_Right:
3042 case Qt::Key_Escape:
3043 keyEvent->accept();
3044 return true;
3045 }
3046 return false;
3047 }
3048
3049 bool TerminalDisplay::event(QEvent* event)
3050 {
3051 bool eventHandled = false;
3052 switch (event->type())
3053 {
3054 case QEvent::ShortcutOverride:
3055 eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event);
3056 break;
3057 case QEvent::PaletteChange:
3058 case QEvent::ApplicationPaletteChange:
3059 _scrollBar->setPalette( QApplication::palette() );
3060 case QEvent::InputMethodQuery:
3061 inputMethodQuery(static_cast<QInputMethodQueryEvent *>(event));
3062 eventHandled = true;
3063 break;
3064 default:
3065 break;
3066 }
3067 return eventHandled ? true : QQuickItem::event(event);
3068 }
3069
3070 void TerminalDisplay::setBellMode(int mode)
3071 {
3072 _bellMode=mode;
3073 }
3074
3075 void TerminalDisplay::enableBell()
3076 {
3077 _allowBell = true;
3078 }
3079
3080 void TerminalDisplay::bell(const QString& message)
3081 {
3082 if (_bellMode==NoBell) return;
3083
3084 //limit the rate at which bells can occur
3085 //...mainly for sound effects where rapid bells in sequence
3086 //produce a horrible noise
3087 if ( _allowBell )
3088 {
3089 _allowBell = false;
3090 QTimer::singleShot(500,this,SLOT(enableBell()));
3091
3092 if (_bellMode==SystemBeepBell)
3093 {
3094 QApplication::beep();
3095 }
3096 else if (_bellMode==NotifyBell)
3097 {
3098 emit notifyBell(message);
3099 }
3100 else if (_bellMode==VisualBell)
3101 {
3102 swapColorTable();
3103 QTimer::singleShot(200,this,SLOT(swapColorTable()));
3104 }
3105 }
3106 }
3107
3108 void TerminalDisplay::selectionChanged()
3109 {
3110 emit copyAvailable(_screenWindow->selectedText(false).isEmpty() == false);
3111 }
3112
3113 void TerminalDisplay::swapColorTable()
3114 {
3115 ColorEntry color = _colorTable[1];
3116 _colorTable[1]=_colorTable[0];
3117 _colorTable[0]= color;
3118 _colorsInverted = !_colorsInverted;
3119 update();
3120 }
3121
3122 void TerminalDisplay::clearImage()
3123 {
3124 // We initialize _image[_imageSize] too. See makeImage()
3125 for (int i = 0; i <= _imageSize; i++)
3126 {
3127 _image[i].character = ' ';
3128 _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT,
3129 DEFAULT_FORE_COLOR);
3130 _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT,
3131 DEFAULT_BACK_COLOR);
3132 _image[i].rendition = DEFAULT_RENDITION;
3133 }
3134 }
3135
3136 void TerminalDisplay::calcGeometry()
3137 {
3138 _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height());
3139 int scrollBarWidth = _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)
3140 ? 0 : _scrollBar->width();
3141 switch(_scrollbarLocation)
3142 {
3143 case QTermWidget::NoScrollBar :
3144 _leftMargin = _leftBaseMargin;
3145 _contentWidth = contentsRect().width() - 2 * _leftBaseMargin;
3146 break;
3147 case QTermWidget::ScrollBarLeft :
3148 _leftMargin = _leftBaseMargin + scrollBarWidth;
3149 _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth;
3150 _scrollBar->move(contentsRect().topLeft());
3151 break;
3152 case QTermWidget::ScrollBarRight:
3153 _leftMargin = _leftBaseMargin;
3154 _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth;
3155 _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1, 0));
3156 break;
3157 }
3158
3159 _topMargin = _topBaseMargin;
3160 _contentHeight = contentsRect().height() - 2 * _topBaseMargin + /* mysterious */ 1;
3161
3162 if (!_isFixedSize)
3163 {
3164 // ensure that display is always at least one column wide
3165 _columns = qMax(1,_contentWidth / _fontWidth);
3166 _usedColumns = qMin(_usedColumns,_columns);
3167
3168 // ensure that display is always at least one line high
3169 _lines = qMax(1,_contentHeight / _fontHeight);
3170 _usedLines = qMin(_usedLines,_lines);
3171 }
3172 }
3173
3174 void TerminalDisplay::makeImage()
3175 {
3176 calcGeometry();
3177
3178 // confirm that array will be of non-zero size, since the painting code
3179 // assumes a non-zero array length
3180 Q_ASSERT( _lines > 0 && _columns > 0 );
3181 Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns );
3182
3183 _imageSize=_lines*_columns;
3184
3185 // We over-commit one character so that we can be more relaxed in dealing with
3186 // certain boundary conditions: _image[_imageSize] is a valid but unused position
3187 _image = new Character[_imageSize+1];
3188
3189 clearImage();
3190 }
3191
3192 // calculate the needed size, this must be synced with calcGeometry()
3193 void TerminalDisplay::setSize(int columns, int lines)
3194 {
3195 int scrollBarWidth = (_scrollBar->isHidden()
3196 || _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar))
3197 ? 0 : _scrollBar->sizeHint().width();
3198 int horizontalMargin = 2 * _leftBaseMargin;
3199 int verticalMargin = 2 * _topBaseMargin;
3200
3201 QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) ,
3202 verticalMargin + (lines * _fontHeight) );
3203
3204 if ( newSize != size() )
3205 {
3206 _size = newSize;
3207 //updateGeometry();
3208 //TODO Manage geometry change
3209
3210 }
3211 }
3212
3213 void TerminalDisplay::setFixedSize(int cols, int lins)
3214 {
3215 _isFixedSize = true;
3216
3217 //ensure that display is at least one line by one column in size
3218 _columns = qMax(1,cols);
3219 _lines = qMax(1,lins);
3220 _usedColumns = qMin(_usedColumns,_columns);
3221 _usedLines = qMin(_usedLines,_lines);
3222
3223 if (_image)
3224 {
3225 delete[] _image;
3226 makeImage();
3227 }
3228 setSize(cols, lins);
3229 //QWidget::setFixedSize(_size);
3230 }
3231
3232 QSize TerminalDisplay::sizeHint() const
3233 {
3234 return _size;
3235 }
3236
3237
3238 /* --------------------------------------------------------------------- */
3239 /* */
3240 /* Drag & Drop */
3241 /* */
3242 /* --------------------------------------------------------------------- */
3243
3244 void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event)
3245 {
3246 if (event->mimeData()->hasFormat(QLatin1String("text/plain")))
3247 event->acceptProposedAction();
3248 if (event->mimeData()->urls().count())
3249 event->acceptProposedAction();
3250 }
3251
3252 void TerminalDisplay::dropEvent(QDropEvent* event)
3253 {
3254 //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
3255 QList<QUrl> urls = event->mimeData()->urls();
3256
3257 QString dropText;
3258 if (!urls.isEmpty())
3259 {
3260 // TODO/FIXME: escape or quote pasted things if neccessary...
3261 qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please";
3262 for ( int i = 0 ; i < urls.count() ; i++ )
3263 {
3264 //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 );
3265 QUrl url = urls[i];
3266
3267 QString urlText;
3268
3269 if (url.isLocalFile())
3270 urlText = url.path();
3271 else
3272 urlText = url.toString();
3273
3274 // in future it may be useful to be able to insert file names with drag-and-drop
3275 // without quoting them (this only affects paths with spaces in)
3276 //urlText = KShell::quoteArg(urlText);
3277
3278 dropText += urlText;
3279
3280 if ( i != urls.count()-1 )
3281 dropText += QLatin1Char(' ');
3282 }
3283 }
3284 else
3285 {
3286 dropText = event->mimeData()->text();
3287 }
3288
3289 emit sendStringToEmu(dropText.toLocal8Bit().constData());
3290 }
3291
3292 void TerminalDisplay::doDrag()
3293 {
3294 dragInfo.state = diDragging;
3295 dragInfo.dragObject = new QDrag(this);
3296 QMimeData *mimeData = new QMimeData;
3297 mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection));
3298 dragInfo.dragObject->setMimeData(mimeData);
3299 dragInfo.dragObject->start(Qt::CopyAction);
3300 // Don't delete the QTextDrag object. Qt will delete it when it's done with it.
3301 }
3302
3303 void TerminalDisplay::outputSuspended(bool suspended)
3304 {
3305 //create the label when this function is first called
3306
3307 // if (!_outputSuspendedLabel)
3308 // {
3309 // //This label includes a link to an English language website
3310 // //describing the 'flow control' (Xon/Xoff) feature found in almost
3311 // //all terminal emulators.
3312 // //If there isn't a suitable article available in the target language the link
3313 // //can simply be removed.
3314 // _outputSuspendedLabel = new QLabel( tr("<qt>Output has been "
3315 // "<a href=\"http://en.wikipedia.org/wiki/Flow_control\">suspended</a>"
3316 // " by pressing Ctrl+S."
3317 // " Press <b>Ctrl+Q</b> to resume.</qt>"),
3318 // this );
3319
3320 // QPalette palette(_outputSuspendedLabel->palette());
3321 // //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground);
3322 // _outputSuspendedLabel->setPalette(palette);
3323 // _outputSuspendedLabel->setAutoFillBackground(true);
3324 // _outputSuspendedLabel->setBackgroundRole(QPalette::Base);
3325 // _outputSuspendedLabel->setFont(QApplication::font());
3326 // _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5);
3327
3328 // //enable activation of "Xon/Xoff" link in label
3329 // _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse |
3330 // Qt::LinksAccessibleByKeyboard);
3331 // _outputSuspendedLabel->setOpenExternalLinks(true);
3332 // _outputSuspendedLabel->setVisible(false);
3333
3334 // _gridLayout->addWidget(_outputSuspendedLabel);
3335 // _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding,
3336 // QSizePolicy::Expanding),
3337 // 1,0);
3338
3339 // }
3340
3341 _outputSuspendedLabel->setVisible(suspended);
3342 }
3343
3344 uint TerminalDisplay::lineSpacing() const
3345 {
3346 return _lineSpacing;
3347 }
3348
3349 void TerminalDisplay::setLineSpacing(uint i)
3350 {
3351 if ( i != _lineSpacing ) {
3352 _lineSpacing = i;
3353 setVTFont(font()); // Trigger an update.
3354 emit lineSpacingChanged();
3355 }
3356 }
3357
3358 int TerminalDisplay::margin() const
3359 {
3360 return _topBaseMargin;
3361 }
3362
3363 void TerminalDisplay::setMargin(int i)
3364 {
3365 _topBaseMargin = i;
3366 _leftBaseMargin = i;
3367 }
3368
3369 AutoScrollHandler::AutoScrollHandler(QWidget* parent)
3370 : QObject(parent)
3371 , _timerId(0)
3372 {
3373 parent->installEventFilter(this);
3374 }
3375 void AutoScrollHandler::timerEvent(QTimerEvent* event)
3376 {
3377 if (event->timerId() != _timerId)
3378 return;
3379
3380 QMouseEvent mouseEvent( QEvent::MouseMove,
3381 widget()->mapFromGlobal(QCursor::pos()),
3382 Qt::NoButton,
3383 Qt::LeftButton,
3384 Qt::NoModifier);
3385
3386 QApplication::sendEvent(widget(),&mouseEvent);
3387 }
3388 bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event)
3389 {
3390 Q_ASSERT( watched == parent() );
3391 Q_UNUSED( watched );
3392
3393 QMouseEvent* mouseEvent = (QMouseEvent*)event;
3394 switch (event->type())
3395 {
3396 case QEvent::MouseMove:
3397 {
3398 bool mouseInWidget = widget()->rect().contains(mouseEvent->pos());
3399
3400 if (mouseInWidget)
3401 {
3402 if (_timerId)
3403 killTimer(_timerId);
3404 _timerId = 0;
3405 }
3406 else
3407 {
3408 if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton))
3409 _timerId = startTimer(100);
3410 }
3411 break;
3412 }
3413 case QEvent::MouseButtonRelease:
3414 if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton))
3415 {
3416 killTimer(_timerId);
3417 _timerId = 0;
3418 }
3419 break;
3420 default:
3421 break;
3422 };
3423
3424 return false;
3425 }
3426
3427 // QMLTermWidget specific functions ///////////////////////////////////////////
3428
3429 void TerminalDisplay::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
3430 {
3431 if (newGeometry != oldGeometry) {
3432 resizeEvent(NULL);
3433 update();
3434 }
3435
3436 QQuickPaintedItem::geometryChanged(newGeometry,oldGeometry);
3437 }
3438
3439 void TerminalDisplay::update(const QRegion &region)
3440 {
3441 Q_UNUSED(region);
3442 // TODO this function might be optimized
3443 // foreach (QRect rect, region.rects()) {
3444 // QQuickPaintedItem::update(rect.adjusted(-1, -1, +1, +1));
3445 // }
3446 QQuickPaintedItem::update(region.boundingRect().adjusted(-1, -1, +1, +1));
3447
3448 emit imagePainted();
3449 }
3450
3451 void TerminalDisplay::update()
3452 {
3453 QQuickPaintedItem::update(contentsRect());
3454 }
3455
3456 QRect TerminalDisplay::contentsRect() const
3457 {
3458 return QRect(0, 0, this->width(), this->height());
3459 }
3460
3461 QSize TerminalDisplay::size() const
3462 {
3463 return QSize(this->width(), this->height());
3464 }
3465
3466 void TerminalDisplay::setSession(KSession * session)
3467 {
3468 if (m_session != session) {
3469 // qDebug() << "SetSession called";
3470 // if (m_session)
3471 // m_session->removeView(this);
3472
3473 m_session = session;
3474
3475 connect(this, SIGNAL(copyAvailable(bool)),
3476 m_session, SLOT(selectionChanged(bool)));
3477 connect(this, SIGNAL(termGetFocus()),
3478 m_session, SIGNAL(termGetFocus()));
3479 connect(this, SIGNAL(termLostFocus()),
3480 m_session, SIGNAL(termLostFocus()));
3481 connect(this, SIGNAL(keyPressedSignal(QKeyEvent *, bool)),
3482 m_session, SIGNAL(termKeyPressed(QKeyEvent *, bool)));
3483
3484 m_session->addView(this);
3485
3486 setRandomSeed(m_session->getRandomSeed());
3487 update();
3488 emit sessionChanged();
3489 }
3490 }
3491
3492
3493 KSession* TerminalDisplay::getSession()
3494 {
3495 return m_session;
3496 }
3497
3498 QStringList TerminalDisplay::availableColorSchemes()
3499 {
3500 QStringList ret;
3501 foreach (const ColorScheme* cs, ColorSchemeManager::instance()->allColorSchemes())
3502 ret.append(cs->name());
3503 return ret;
3504 }
3505
3506 void TerminalDisplay::setColorScheme(const QString &name)
3507 {
3508 if ( name != _colorScheme ) {
•3509 if (_colorSchemeRef) {
3510 disconnect(_colorSchemeRef, 0, this, 0);
3511 }
3512 // avoid legacy (int) solution
3513 if (!availableColorSchemes().contains(name))
•3514 _colorSchemeRef = ColorSchemeManager::instance()->defaultColorScheme();
3515 else
•3516 _colorSchemeRef = ColorSchemeManager::instance()->findColorScheme(name);
3517
•3518 if (! _colorSchemeRef)
3519 {
3520 qDebug() << "Cannot load color scheme: " << name;
3521 return;
3522 }
3523
•3524 connect(_colorSchemeRef, SIGNAL(colorChanged(int)), this, SLOT(applyColorScheme()));
3525 connect(_colorSchemeRef, SIGNAL(opacityChanged()), this, SLOT(applyColorScheme()));
3526 applyColorScheme();
3527 _colorScheme = name;
3528 emit colorSchemeChanged();
3529 }
3530 }
3531
3532 QString TerminalDisplay::colorScheme() const
3533 {
3534 return _colorScheme;
3535 }
3536
•3537 void TerminalDisplay::applyColorScheme()
3538 {
3539 ColorEntry table[TABLE_COLORS];
3540 _colorSchemeRef->getColorTable(table);
3541 setColorTable(table);
3542 QColor backgroundColor = _colorTable[DEFAULT_BACK_COLOR].color;
3543 backgroundColor.setAlphaF(_colorSchemeRef->opacity());
3544 setBackgroundColor(backgroundColor);
3545 setFillColor(backgroundColor);
3546 }
3547
3548 void TerminalDisplay::simulateKeyPress(int key, int modifiers, bool pressed, quint32 nativeScanCode, const QString &text)
3549 {
3550 Q_UNUSED(nativeScanCode);
3551 QEvent::Type type = pressed ? QEvent::KeyPress : QEvent::KeyRelease;
3552 QKeyEvent event = QKeyEvent(type, key, (Qt::KeyboardModifier) modifiers, text);
3553 keyPressedSignal(&event, false);
3554 }
3555
3556 void TerminalDisplay::simulateKeySequence(const QKeySequence &keySequence)
3557 {
3558 for (int i = 0; i < keySequence.count(); ++i) {
3559 const Qt::Key key = Qt::Key(keySequence[i] & ~Qt::KeyboardModifierMask);
3560 const Qt::KeyboardModifiers modifiers = Qt::KeyboardModifiers(keySequence[i] & Qt::KeyboardModifierMask);
3561 QKeyEvent eventPress = QKeyEvent(QEvent::KeyPress, key, modifiers, "");
3562 keyPressedSignal(&eventPress, false);
3563 }
3564 }
3565
3566 void TerminalDisplay::simulateWheel(int x, int y, int buttons, int modifiers, QPointF angleDelta){
3567 QWheelEvent event(QPointF(x,y), angleDelta.y(), (Qt::MouseButton) buttons, (Qt::KeyboardModifier) modifiers);
3568 wheelEvent(&event);
3569 }
3570
3571 void TerminalDisplay::simulateMouseMove(int x, int y, int button, int buttons, int modifiers){
3572 QMouseEvent event(QEvent::MouseMove, QPointF(x, y),(Qt::MouseButton) button, (Qt::MouseButtons) buttons, (Qt::KeyboardModifiers) modifiers);
3573 mouseMoveEvent(&event);
3574 }
3575
3576 void TerminalDisplay::simulateMousePress(int x, int y, int button, int buttons, int modifiers){
3577 QMouseEvent event(QEvent::MouseButtonPress, QPointF(x, y),(Qt::MouseButton) button, (Qt::MouseButtons) buttons, (Qt::KeyboardModifiers) modifiers);
3578 mousePressEvent(&event);
3579 }
3580
3581 void TerminalDisplay::simulateMouseRelease(int x, int y, int button, int buttons, int modifiers){
3582 QMouseEvent event(QEvent::MouseButtonRelease, QPointF(x, y),(Qt::MouseButton) button, (Qt::MouseButtons) buttons, (Qt::KeyboardModifiers) modifiers);
3583 mouseReleaseEvent(&event);
3584 }
3585
3586 void TerminalDisplay::simulateMouseDoubleClick(int x, int y, int button, int buttons, int modifiers){
3587 QMouseEvent event(QEvent::MouseButtonDblClick, QPointF(x, y),(Qt::MouseButton) button, (Qt::MouseButtons) buttons, (Qt::KeyboardModifiers) modifiers);
3588 mouseDoubleClickEvent(&event);
3589 }
3590
3591 QSize TerminalDisplay::getTerminalSize()
3592 {
3593 return QSize(_lines, _columns);
3594 }
3595
3596 bool TerminalDisplay::getUsesMouse()
3597 {
3598 return !usesMouse();
3599 }
3600
3601 int TerminalDisplay::getScrollbarValue()
3602 {
3603 return _scrollBar->value();
3604 }
3605
•3606 void TerminalDisplay::setScrollbarValue(int value)
3607 {
3608 if (value != _scrollBar->value()) {
3609 _scrollBar->setValue(value);
3610 }
3611 }
3612
3613 int TerminalDisplay::getScrollbarMaximum()
3614 {
3615 return _scrollBar->maximum();
3616 }
3617
3618 int TerminalDisplay::getScrollbarMinimum()
3619 {
3620 return _scrollBar->minimum();
3621 }
3622
3623 QSize TerminalDisplay::getFontMetrics()
3624 {
3625 return QSize(_fontWidth, _fontHeight);
3626 }
3627
3628 void TerminalDisplay::setFullCursorHeight(bool val)
3629 {
3630 if ( m_full_cursor_height != val ) {
3631 m_full_cursor_height = val;
3632 emit fullCursorHeightChanged();
3633 }
3634 }
3635
3636 bool TerminalDisplay::fullCursorHeight() const
3637 {
3638 return m_full_cursor_height;
3639 }
3640
3641 void TerminalDisplay::itemChange(ItemChange change, const ItemChangeData & value)
3642 {
3643 switch (change) {
3644 case QQuickItem::ItemVisibleHasChanged:
3645 if (value.boolValue && _screenWindow) {
3646 if (this->columns() != _screenWindow->columnCount() ||
3647 this->lines() != _screenWindow->lineCount()) {
3648
3649 emit changedContentSizeSignal(_contentHeight, _contentWidth);
3650 }
3651 }
3652 break;
3653 default:
3654 break;
3655 }
3656
3657 QQuickPaintedItem::itemChange(change, value);
3658 }
3659
3660 //#include "TerminalDisplay.moc"