Debian Codegraph @

lib/TerminalDisplay.cpp

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