Debian Codegraph @

lib/TerminalDisplay.cpp

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