TerminalDisplay.cpp 80.5 KB
Newer Older
1
/*
2
    This file is part of Konsole, a terminal emulator for KDE.
3
    
4
    Copyright (C) 2006-7 by Robert Knight <robertknight@gmail.com>
5
    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
6
    
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301  USA.
*/
22

23
24
25
// Own
#include "TerminalDisplay.h"

Robert Knight's avatar
Robert Knight committed
26
// Qt
Dirk Mueller's avatar
Dirk Mueller committed
27
28
29
30
31
32
33
34
35
36
37
#include <QtGui/QApplication>
#include <QtGui/QBoxLayout>
#include <QtGui/QClipboard>
#include <QtGui/QKeyEvent>
#include <QtCore/QEvent>
#include <QtCore/QFile>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
38
#include <QtGui/QScrollBar>
Dirk Mueller's avatar
Dirk Mueller committed
39
40
41
#include <QtGui/QStyle>
#include <QtCore/QTimer>
#include <QtGui/QToolTip>
42

Robert Knight's avatar
Robert Knight committed
43
// KDE
44
#include <kshell.h>
Robert Knight's avatar
Robert Knight committed
45
#include <KCursor>
46
#include <kdebug.h>
Robert Knight's avatar
Robert Knight committed
47
#include <KLocale>
48
#include <KMenu>
Robert Knight's avatar
Robert Knight committed
49
50
51
52
53
54
#include <KNotification>
#include <KGlobalSettings>
#include <KShortcut>
#include <KIO/NetAccess>

// Konsole
Dirk Mueller's avatar
Dirk Mueller committed
55
#include <config-apps.h>
56
#include "Filter.h"
Robert Knight's avatar
Robert Knight committed
57
#include "konsole_wcwidth.h"
58
#include "ScreenWindow.h"
59
#include "TerminalCharacterDecoder.h"
60

61
62
using namespace Konsole;

63
#ifndef loc
64
#define loc(X,Y) ((Y)*_columns+(X))
65
66
67
#endif

#define yMouseScroll 1
Waldo Bastian's avatar
Waldo Bastian committed
68
69
70
71

#define REPCHAR   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                  "abcdefgjijklmnopqrstuvwxyz" \
                  "0123456789./+@"
72

73
74
// scroll increment used when dragging selection at top/bottom of window.

75
// static
76
bool TerminalDisplay::_antialiasText = true;
77
bool TerminalDisplay::HAVE_TRANSPARENCY = false;
78

79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* ------------------------------------------------------------------------- */
/*                                                                           */
/*                                Colors                                     */
/*                                                                           */
/* ------------------------------------------------------------------------- */

/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb)

   Code        0       1       2       3       4       5       6       7
   ----------- ------- ------- ------- ------- ------- ------- ------- -------
   ANSI  (bgr) Black   Red     Green   Yellow  Blue    Magenta Cyan    White
   IBMPC (rgb) Black   Blue    Green   Cyan    Red     Magenta Yellow  White
*/

93
ScreenWindow* TerminalDisplay::screenWindow() const
94
95
96
{
    return _screenWindow;
}
97
void TerminalDisplay::setScreenWindow(ScreenWindow* window)
98
{
99
100
101
102
103
104
    // disconnect existing screen window if any
    if ( _screenWindow )
    {
        disconnect( _screenWindow , 0 , this , 0 );
    }

105
    _screenWindow = window;
106

107
108
    if ( window )
    {
109
#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?"
110
111
112
        connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) );
        connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) );
    }
113
114
}

115
const ColorEntry* TerminalDisplay::colorTable() const
116
{
117
  return _colorTable;
118
119
}

120
void TerminalDisplay::setColorTable(const ColorEntry table[])
121
{
Robert Knight's avatar
   
Robert Knight committed
122
123
  for (int i = 0; i < TABLE_COLORS; i++)
      _colorTable[i] = table[i];
124

125
  QPalette p = palette();
126
  p.setColor( backgroundRole(), _colorTable[DEFAULT_BACK_COLOR].color );
127
  setPalette( p );
128

129
  // Avoid propagating the palette change to the scroll bar 
130
131
  _scrollBar->setPalette( QApplication::palette() );  

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
  update();
}

/* ------------------------------------------------------------------------- */
/*                                                                           */
/*                                   Font                                    */
/*                                                                           */
/* ------------------------------------------------------------------------- */

/*
   The VT100 has 32 special graphical characters. The usual vt100 extended
   xterm fonts have these at 0x00..0x1f.

   QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals
   come in here as proper unicode characters.

   We treat non-iso10646 fonts as VT100 extended and do the requiered mapping
   from unicode to 0x00..0x1f. The remaining translation is then left to the
   QCodec.
*/

153
static inline bool isLineChar(quint16 c) { return ((c & 0xFF80) == 0x2500);}
154
155
156
157
158
static inline bool isLineCharString(const QString& string)
{
		return (string.length() > 0) && (isLineChar(string.at(0).unicode()));
}
						
159

160
161
// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i.

162
unsigned short Konsole::vt100_graphics[32] =
163
164
165
166
167
168
169
{ // 0/8     1/9    2/10    3/11    4/12    5/13    6/14    7/15
  0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0,
  0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c,
  0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534,
  0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7
};

170
void TerminalDisplay::fontChange(const QFont&)
171
172
{
  QFontMetrics fm(font());
173
  _fontHeight = fm.height() + _lineSpacing;
174

175
  // waba TerminalDisplay 1.123:
176
177
  // "Base character width on widest ASCII character. This prevents too wide
  //  characters in the presence of double wide (e.g. Japanese) characters."
Waldo Bastian's avatar
Waldo Bastian committed
178
  // Get the width from representative normal width characters
179
  _fontWidth = qRound((double)fm.width(REPCHAR)/(double)strlen(REPCHAR));
Waldo Bastian's avatar
Waldo Bastian committed
180

181
  _fixedFont = true;
182

183
  int fw = fm.width(REPCHAR[0]);
184
185
186
187
  for(unsigned int i=1; i< strlen(REPCHAR); i++)
  {
    if (fw != fm.width(REPCHAR[i]))
    {
188
      _fixedFont = false;
Waldo Bastian's avatar
Waldo Bastian committed
189
      break;
190
    }
191
  }
Stephan Kulow's avatar
Stephan Kulow committed
192

193
  if (_fontWidth < 1)
194
    _fontWidth=1;
195

196
  _fontAscent = fm.ascent();
197

198
  emit changedFontMetricSignal( _fontHeight, _fontWidth );
199
200
201
202
  propagateSize();
  update();
}

203
void TerminalDisplay::setVTFont(const QFont& f)
204
{
205
  QFont font = f;
Robert Knight's avatar
Robert Knight committed
206
207
208
209
210

  QFontMetrics metrics(font);

  if ( metrics.height() < height() && metrics.maxWidth() < width() )
  {
211
212
213
    // hint that text should be drawn without anti-aliasing.  
    // depending on the user's font configuration, this may not be respected
    if (!_antialiasText)
Robert Knight's avatar
Robert Knight committed
214
        font.setStyleStrategy( QFont::NoAntialias );
Robert Knight's avatar
   
Robert Knight committed
215
216
217
218
219
220
 
    // experimental optimization.  Konsole assumes that the terminal is using a 
    // mono-spaced font, in which case kerning information should have an effect.
    // Disabling kerning saves some computation when rendering text. 
    font.setKerning(false);

Robert Knight's avatar
Robert Knight committed
221
222
223
    QFrame::setFont(font);
    fontChange(font);
  }
224
225
}

226
void TerminalDisplay::setFont(const QFont &)
227
228
229
230
231
232
233
234
235
236
{
  // ignore font change request if not coming from konsole itself
}

/* ------------------------------------------------------------------------- */
/*                                                                           */
/*                         Constructor / Destructor                          */
/*                                                                           */
/* ------------------------------------------------------------------------- */

237
TerminalDisplay::TerminalDisplay(QWidget *parent)
238
:QFrame(parent)
239
,_screenWindow(0)
240
241
242
243
244
245
246
247
248
249
250
251
,_allowBell(true)
,_gridLayout(0)
,_fontHeight(1)
,_fontWidth(1)
,_fontAscent(1)
,_lines(1)
,_columns(1)
,_usedLines(1)
,_usedColumns(1)
,_contentHeight(1)
,_contentWidth(1)
,_image(0)
252
,_randomSeed(0)
253
254
255
256
257
258
259
260
261
,_resizing(false)
,_terminalSizeHint(false)
,_terminalSizeStartup(true)
,_bidiEnabled(false)
,_actSel(0)
,_wordSelectionMode(false)
,_lineSelectionMode(false)
,_preserveLineBreaks(true)
,_columnSelectionMode(false)
262
,_scrollbarLocation(NoScrollBar)
263
,_wordCharacters(":@-./_~")
264
,_bellMode(BELL_SYSTEM)
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
,_blinking(false)
,_cursorBlinking(false)
,_hasBlinkingCursor(false)
,_ctrlDrag(false)
,_cutToBeginningOfLine(false)
,_isFixedSize(false)
,_possibleTripleClick(false)
,_resizeWidget(0)
,_resizeLabel(0)
,_resizeTimer(0)
,_outputSuspendedLabel(0)
,_lineSpacing(0)
,_colorsInverted(false)
,_rimX(1)
,_rimY(1)
,_blendColor(qRgba(0,0,0,0xff))
281
,_filterChain(new TerminalImageFilterChain())
282
,_cursorShape(BlockCursor)
283
{
284

285
  // The offsets are not yet calculated.
286
  // Do not calculate these too often to be more smoothly when resizing
287
  // konsole in opaque mode.
288
  _bY = _bX = 1;
289

290
291
  // create scroll bar for scrolling output up and down
  // set the scroll bar's slider to occupy the whole area of the scroll bar initially
292
  _scrollBar = new QScrollBar(this);
293
  setScroll(0,0); 
294
  _scrollBar->setCursor( Qt::ArrowCursor );
295
  connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int)));
296

297
298
299
300
  _blinkTimer   = new QTimer(this);
  connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent()));
  _blinkCursorTimer   = new QTimer(this);
  connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent()));
301

Robert Knight's avatar
   
Robert Knight committed
302
  setUsesMouse(true);
303
  setColorTable(base_color_table); 
304
305
306

  KCursor::setAutoHideCursor( this, true );

307
308
  setMouseTracking(true);

Robert Knight's avatar
   
Robert Knight committed
309
  // Init DnD 
310
  setAcceptDrops(true); // attempt
311
  dragInfo.state = diNone;
312

313
  setFocusPolicy( Qt::WheelFocus );
314
315

  // enable input method support
316
  setAttribute(Qt::WA_InputMethodEnabled, true);
Stephan Kulow's avatar
Stephan Kulow committed
317

Robert Knight's avatar
Robert Knight committed
318
  // this is an important optimization, it tells Qt
319
320
  // that TerminalDisplay will handle repainting its entire area.
  setAttribute(Qt::WA_OpaquePaintEvent);
321

322
323
  _gridLayout = new QGridLayout(this);
  _gridLayout->setMargin(0);
324

325
  setLayout( _gridLayout ); 
326
  setLineWidth(0);
327
328
329

  //set up a warning message when the user presses Ctrl+S to avoid confusion
  connect( this,SIGNAL(flowControlKeyPressed(bool)),this,SLOT(outputSuspended(bool)) );
330
331
}

332
TerminalDisplay::~TerminalDisplay()
333
334
{
  qApp->removeEventFilter( this );
335
  
336
  delete[] _image;
337

338
339
  delete _gridLayout;
  delete _outputSuspendedLabel;
340
  delete _filterChain;
341
342
343
344
345
346
347
348
}

/* ------------------------------------------------------------------------- */
/*                                                                           */
/*                             Display Operations                            */
/*                                                                           */
/* ------------------------------------------------------------------------- */

349
350
351
352
353
/**
 A table for emulating the simple (single width) unicode drawing chars.
 It represents the 250x - 257x glyphs. If it's zero, we can't use it.
 if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered
 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit.
Stephan Kulow's avatar
Stephan Kulow committed
354

355
356
357
358
359
360
361
362
363
364
365
 Then, the pixels basically have the following interpretation:
 _|||_
 -...-
 -...-
 -...-
 _|||_

where _ = none
      | = vertical line.
      - = horizontal line.
 */
Stephan Kulow's avatar
Stephan Kulow committed
366

367
368
369
370
371
372

enum LineEncode
{
    TopL  = (1<<1),
    TopC  = (1<<2),
    TopR  = (1<<3),
Stephan Kulow's avatar
Stephan Kulow committed
373

374
375
376
377
378
    LeftT = (1<<5),
    Int11 = (1<<6),
    Int12 = (1<<7),
    Int13 = (1<<8),
    RightT = (1<<9),
Stephan Kulow's avatar
Stephan Kulow committed
379

380
381
382
383
384
    LeftC = (1<<10),
    Int21 = (1<<11),
    Int22 = (1<<12),
    Int23 = (1<<13),
    RightC = (1<<14),
Stephan Kulow's avatar
Stephan Kulow committed
385

386
387
388
389
390
    LeftB = (1<<15),
    Int31 = (1<<16),
    Int32 = (1<<17),
    Int33 = (1<<18),
    RightB = (1<<19),
Stephan Kulow's avatar
Stephan Kulow committed
391

392
393
    BotL  = (1<<21),
    BotC  = (1<<22),
Dirk Mueller's avatar
Dirk Mueller committed
394
    BotR  = (1<<23)
395
396
};

397
#include "LineFont.h"
398
399
400
401
402
403
404
405
406

static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code)
{
    //Calculate cell midpoints, end points.
    int cx = x + w/2;
    int cy = y + h/2;
    int ex = x + w - 1;
    int ey = y + h - 1;

407
    quint32 toDraw = LineChars[code];
Stephan Kulow's avatar
Stephan Kulow committed
408

409
    //Top _lines:
410
411
412
413
414
415
416
    if (toDraw & TopL)
        paint.drawLine(cx-1, y, cx-1, cy-2);
    if (toDraw & TopC)
        paint.drawLine(cx, y, cx, cy-2);
    if (toDraw & TopR)
        paint.drawLine(cx+1, y, cx+1, cy-2);

417
    //Bot _lines:
418
419
420
421
422
423
424
    if (toDraw & BotL)
        paint.drawLine(cx-1, cy+2, cx-1, ey);
    if (toDraw & BotC)
        paint.drawLine(cx, cy+2, cx, ey);
    if (toDraw & BotR)
        paint.drawLine(cx+1, cy+2, cx+1, ey);

425
    //Left _lines:
426
427
428
429
430
431
432
    if (toDraw & LeftT)
        paint.drawLine(x, cy-1, cx-2, cy-1);
    if (toDraw & LeftC)
        paint.drawLine(x, cy, cx-2, cy);
    if (toDraw & LeftB)
        paint.drawLine(x, cy+1, cx-2, cy+1);

433
    //Right _lines:
434
435
436
437
438
439
    if (toDraw & RightT)
        paint.drawLine(cx+2, cy-1, ex, cy-1);
    if (toDraw & RightC)
        paint.drawLine(cx+2, cy, ex, cy);
    if (toDraw & RightB)
        paint.drawLine(cx+2, cy+1, ex, cy+1);
Stephan Kulow's avatar
Stephan Kulow committed
440

441
442
443
444
445
446
447
    //Intersection points.
    if (toDraw & Int11)
        paint.drawPoint(cx-1, cy-1);
    if (toDraw & Int12)
        paint.drawPoint(cx, cy-1);
    if (toDraw & Int13)
        paint.drawPoint(cx+1, cy-1);
Stephan Kulow's avatar
Stephan Kulow committed
448

449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
    if (toDraw & Int21)
        paint.drawPoint(cx-1, cy);
    if (toDraw & Int22)
        paint.drawPoint(cx, cy);
    if (toDraw & Int23)
        paint.drawPoint(cx+1, cy);

    if (toDraw & Int31)
        paint.drawPoint(cx-1, cy+1);
    if (toDraw & Int32)
        paint.drawPoint(cx, cy+1);
    if (toDraw & Int33)
        paint.drawPoint(cx+1, cy+1);

}

465
void TerminalDisplay::drawLineCharString(	QPainter& painter, int x, int y, const QString& str, 
466
									const Character* attributes)
467
468
469
{
		const QPen& currentPen = painter.pen();
		
470
		if ( attributes->rendition & RE_BOLD )
471
472
473
474
475
476
477
478
479
480
		{
			QPen boldPen(currentPen);
			boldPen.setWidth(3);
			painter.setPen( boldPen );
		}	
		
		for (int i=0 ; i < str.length(); i++)
		{
			uchar code = str[i].cell();
        	if (LineChars[code])
481
            	drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code);
482
483
484
485
486
		}

		painter.setPen( currentPen );
}

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
void TerminalDisplay::setKeyboardCursorShape(KeyboardCursorShape shape)
{
    _cursorShape = shape;
}
TerminalDisplay::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const
{
    return _cursorShape;
}
void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color)
{
    if (useForegroundColor)
        _cursorColor = QColor(); // an invalid color means that
                                 // the foreground color of the
                                 // current character should
                                 // be used

    else
        _cursorColor = color;
}
QColor TerminalDisplay::keyboardCursorColor() const
{
    return _cursorColor;
}
510

511
512
513
514
void TerminalDisplay::setOpacity(qreal opacity)
{
    QColor color(_blendColor);
    color.setAlphaF(opacity);
515
516
517
518
519
520
521
522
523
524
525
526

    // enable automatic background filling to prevent the display
    // flickering if there is no transparency
    /*if ( color.alpha() == 255 ) 
    {
        setAutoFillBackground(true);
    }
    else
    {
        setAutoFillBackground(false);
    }*/

527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
    _blendColor = color.rgba();
}

void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor)
{
        if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff ) 
        {
            QColor color(backgroundColor);
            color.setAlpha(qAlpha(_blendColor));

            painter.save();
            painter.setCompositionMode(QPainter::CompositionMode_Source);
            painter.fillRect(rect, color);
            painter.restore();
        } 
        else
            painter.fillRect(rect, backgroundColor);
}

546
547
548
549
550
551
552
553
554
555
556
557
558
void TerminalDisplay::drawCursor(QPainter& painter, 
                                 const QRect& rect,
                                 const QColor& foregroundColor,
                                 const QColor& /*backgroundColor*/,
                                 bool& invertCharacterColor)
{
    QRect cursorRect = rect;
    cursorRect.setHeight(_fontHeight - _lineSpacing - 1);
    
    if (!_cursorBlinking)
    {
       if ( _cursorColor.isValid() )
           painter.setPen(_cursorColor);
559
560
       else
           painter.setPen(foregroundColor);
561
562
563

       if ( _cursorShape == BlockCursor )
       {
564
565
566
567
568
569
570
571
            // draw the cursor outline, adjusting the area so that
            // it is draw entirely inside 'rect'
            int penWidth = qMax(1,painter.pen().width());

            painter.drawRect(cursorRect.adjusted(penWidth/2,
                                                 penWidth/2,
                                                 - penWidth/2 - penWidth%2,
                                                 - penWidth/2 - penWidth%2));
572
573
574
            if ( hasFocus() )
            {
                painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor);
575
576
577
578
579
580
581
            
                if ( !_cursorColor.isValid() )
                {
                    // invert the colour used to draw the text to ensure that the character at
                    // the cursor position is readable
                    invertCharacterColor = true;
                }
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
            }
       }
       else if ( _cursorShape == UnderlineCursor )
            painter.drawLine(cursorRect.left(),
                             cursorRect.bottom(),
                             cursorRect.right(),
                             cursorRect.bottom());
       else if ( _cursorShape == IBeamCursor )
            painter.drawLine(cursorRect.left(),
                             cursorRect.top(),
                             cursorRect.left(),
                             cursorRect.bottom());
    
    }
}

void TerminalDisplay::drawCharacters(QPainter& painter,
                                     const QRect& rect,
                                     const QString& text,
                                     const Character* style,
                                     bool invertCharacterColor)
{
    // don't draw text which is currently blinking
    if ( _blinking && (style->rendition & RE_BLINK) )
            return;
   
Robert Knight's avatar
   
Robert Knight committed
608
    // setup bold and underline
609
    bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable);
Robert Knight's avatar
   
Robert Knight committed
610
611
    bool useUnderline = style->rendition & RE_UNDERLINE;

612
    QFont font = painter.font();
Robert Knight's avatar
   
Robert Knight committed
613
614
    if (    font.bold() != useBold 
         || font.underline() != useUnderline )
615
616
    {
       font.setBold(useBold);
Robert Knight's avatar
   
Robert Knight committed
617
       font.setUnderline(useUnderline);
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
       painter.setFont(font);
    }

    // setup pen
    const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor );
    const QColor color = textColor.color(_colorTable);
    QPen pen = painter.pen();
    if ( pen.color() != color )
    {
        pen.setColor(color);
        painter.setPen(color);
    }

    // draw text
    if ( isLineCharString(text) )
	  	drawLineCharString(painter,rect.x(),rect.y(),text,style);
    else
        painter.drawText(rect,text);
}

void TerminalDisplay::drawTextFragment(QPainter& painter , 
                                       const QRect& rect,
                                       const QString& text, 
                                       const Character* style)
{
    painter.save();

    // setup painter 
    const QColor foregroundColor = style->foregroundColor.color(_colorTable);
    const QColor backgroundColor = style->backgroundColor.color(_colorTable);
    
    // draw background if different from the display's background color
650
    if ( backgroundColor != palette().background().color() )
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        drawBackground(painter,rect,backgroundColor);

    // draw cursor shape if the current character is the cursor
    // this may alter the foreground and background colors
    bool invertCharacterColor = false;
    if ( style->rendition & RE_CURSOR )
        drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor);

    // draw text
    drawCharacters(painter,rect,text,style,invertCharacterColor);

    painter.restore();
}

665
666
667
void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; }
uint TerminalDisplay::randomSeed() const { return _randomSeed; }

668
#if 0
Waldo Bastian's avatar
Waldo Bastian committed
669
670
671
/*!
    Set XIM Position
*/
672
void TerminalDisplay::setCursorPos(const int curx, const int cury)
Waldo Bastian's avatar
Waldo Bastian committed
673
674
675
676
677
678
{
    QPoint tL  = contentsRect().topLeft();
    int    tLx = tL.x();
    int    tLy = tL.y();

    int xpos, ypos;
679
680
681
    ypos = _bY + tLy + _fontHeight*(cury-1) + _fontAscent;
    xpos = _bX + tLx + _fontWidth*curx;
    //setMicroFocusHint(xpos, ypos, 0, _fontHeight); //### ???
Waldo Bastian's avatar
Waldo Bastian committed
682
    // fprintf(stderr, "x/y = %d/%d\txpos/ypos = %d/%d\n", curx, cury, xpos, ypos);
683
684
    _cursorLine = cury;
    _cursorCol = curx;
Waldo Bastian's avatar
Waldo Bastian committed
685
}
686
#endif
Waldo Bastian's avatar
Waldo Bastian committed
687

688
// scrolls the image by 'lines', down if lines > 0 or up otherwise.
689
//
690
// the terminal emulation keeps track of the scrolling of the character 
691
// image as it receives input, and when the view is updated, it calls scrollImage() 
692
// with the final scroll amount.  this improves performance because scrolling the 
693
694
695
// display is much cheaper than re-rendering all the text for the 
// part of the image which has moved up or down.  
// Instead only new lines have to be drawn
696
//
697
698
699
// note:  it is important that the area of the display which is 
// scrolled aligns properly with the character grid - 
// which has a top left point at (_bX,_bY) , 
700
// a cell width of _fontWidth and a cell height of _fontHeight).    
701
void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion)
702
{
703
704
705
706
707
708
709
    // constrain the region to the display
    // the bottom of the region is capped to the number of lines in the display's
    // internal image - 2, so that the height of 'region' is strictly less
    // than the height of the internal image.
    QRect region = screenWindowRegion;
    region.setBottom( qMin(region.bottom(),this->_lines-2) ); 

710
    if (    lines == 0 
711
712
713
714
715
716
         || _image == 0
         || !region.isValid() 
         || (region.top() + abs(lines)) >= region.bottom() 
         || this->_lines <= region.height() ) return;

   
717
718
719

    QRect scrollRect;

720
721
722
723
724
    //qDebug() << "Scrolled region: top =" << region.top() 
    //         << ", bottom =" << region.bottom()
    //         << ", height =" << region.height() << "lines.  Image height ="
    //         << this->_usedLines << "lines"
    //         << ", scroll =" << lines << "lines";
725

726
727
    void* firstCharPos = &_image[ region.top() * this->_columns ];
    void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ];
728
729
730
731

    int top = _bY + (region.top() * _fontHeight);
    int linesToMove = region.height() - abs(lines);
    int bytesToMove = linesToMove * 
732
                      this->_columns *
733
734
735
736
737
                      sizeof(Character);

    Q_ASSERT( linesToMove > 0 );
    Q_ASSERT( bytesToMove > 0 );

738
    //scroll internal image
739
    if ( lines > 0 )
740
    {
741
742
        // check that the memory areas that we are going to move are valid
        Q_ASSERT( (char*)lastCharPos + bytesToMove < 
743
                  (char*)(_image + (this->_lines * this->_columns)) );
744
        
745
        Q_ASSERT( (lines*this->_columns) < _imageSize ); 
746

747
        //scroll internal image down
748
749
        memmove( firstCharPos , lastCharPos , bytesToMove ); 
      
750
751
        //set region of display to scroll, making sure that
        //the region aligns correctly to the character grid 
752
        scrollRect = QRect( _bX , top, 
753
                            this->_usedColumns * _fontWidth , 
754
                            linesToMove * _fontHeight );
755
756
757
    }
    else
    {
758
759
        // check that the memory areas that we are going to move are valid
        Q_ASSERT( (char*)firstCharPos + bytesToMove < 
760
                  (char*)(_image + (this->_lines * this->_columns)) );
761
762

        //scroll internal image up
763
764
        memmove( lastCharPos , firstCharPos , bytesToMove ); 
     
765
766
        //set region of the display to scroll, making sure that
        //the region aligns correctly to the character grid
767
        QPoint topPoint( _bX , top + abs(lines)*_fontHeight );
768

769
        scrollRect = QRect( topPoint ,
770
                     QSize( this->_usedColumns*_fontWidth , 
771
                            linesToMove * _fontHeight ));
772
773
    }

774
    //scroll the display vertically to match internal _image
775
    scroll( 0 , _fontHeight * (-lines) , scrollRect );
776
}
777

778
void TerminalDisplay::processFilters() 
779
{
780
781
782
783
784
    QTime t;
    t.start();

    _filterChain->setImage(_image,_lines,_columns);

Robert Knight's avatar
   
Robert Knight committed
785
    //qDebug() << "Setup filters in" << t.elapsed() << "ms.";
786

787
    _filterChain->process();
788

Robert Knight's avatar
   
Robert Knight committed
789
    //qDebug() << "Processed filters in" << t.elapsed() << "ms.";
790
791
}

792
void TerminalDisplay::updateImage() 
793
{
794
795
796
  if ( !_screenWindow )
      return;

797
798
  // optimization - scroll the existing image where possible and 
  // avoid expensive text drawing for parts of the image that 
Robert Knight's avatar
   
Robert Knight committed
799
  // can simply be moved up or down
800
801
  scrollImage( _screenWindow->scrollCount() ,
               _screenWindow->scrollRegion() );
802
803
  _screenWindow->resetScrollCount();

804
  Character* const newimg = _screenWindow->getImage();
805
806
  int lines = _screenWindow->windowLines();
  int columns = _screenWindow->windowColumns();
807
808
809

  setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() );

810
811
  if (!_image)
     updateImageSize(); // Create _image
812

813
814
  Q_ASSERT( this->_usedLines <= this->_lines );
  Q_ASSERT( this->_usedColumns <= this->_columns );
815

816
  int y,x,len;
817
818
819
820

  QPoint tL  = contentsRect().topLeft();
  int    tLx = tL.x();
  int    tLy = tL.y();
821
  _hasBlinker = false;
822

823
  CharacterColor cf;       // undefined
824
  CharacterColor _clipboard;       // undefined
825
  int cr  = -1;   // undefined
826

827
828
  const int linesToUpdate = qMin(this->_lines, qMax(0,lines  ));
  const int columnsToUpdate = qMin(this->_columns,qMax(0,columns));
829

830
  QChar *disstrU = new QChar[columnsToUpdate];
831
  char *dirtyMask = new char[columnsToUpdate+2]; 
832
  QRegion dirtyRegion;
833

834
  // debugging variable, this records the number of lines that are found to
835
  // be 'dirty' ( ie. have changed from the old _image to the new _image ) and
Robert Knight's avatar
   
Robert Knight committed
836
  // which therefore need to be repainted
837
838
  int dirtyLineCount = 0;

839
  for (y = 0; y < linesToUpdate; y++)
840
  {
841
    const Character*       currentLine = &_image[y*this->_columns];
842
    const Character* const newLine = &newimg[y*columns];
843

844
845
    bool updateLine = false;
    
846
    // The dirty mask indicates which characters need repainting. We also
Waldo Bastian's avatar
Waldo Bastian committed
847
848
    // mark surrounding neighbours dirty, in case the character exceeds
    // its cell boundaries
849
    memset(dirtyMask, 0, columnsToUpdate+2);
850
851
   
    for( x = 0 ; x < columnsToUpdate ; x++)
Waldo Bastian's avatar
Waldo Bastian committed
852
    {
853
854
855
856
        if ( newLine[x] != currentLine[x] ) 
        {
            dirtyMask[x] = true;
        }
Waldo Bastian's avatar
Waldo Bastian committed
857
    }
858

859
    if (!_resizing) // not while _resizing, we're expecting a paintEvent
860
    for (x = 0; x < columnsToUpdate; x++)
861
    {
862
      _hasBlinker |= (newLine[x].rendition & RE_BLINK);
863
    
Waldo Bastian's avatar
Waldo Bastian committed
864
865
866
867
      // Start drawing if this character or the next one differs.
      // We also take the next one into account to handle the situation
      // where characters exceed their cell width.
      if (dirtyMask[x])
868
      {
869
        quint16 c = newLine[x+0].character;
870
871
872
        if ( !c )
            continue;
        int p = 0;
Stephan Binner's avatar
Stephan Binner committed
873
        disstrU[p++] = c; //fontMap(c);
874
        bool lineDraw = isLineChar(c);
875
876
        bool doubleWidth = (newLine[x+1].character == 0);
        cr = newLine[x].rendition;
877
        _clipboard = newLine[x].backgroundColor;
878
        if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor;
879
        int lln = columnsToUpdate - x;
880
881
        for (len = 1; len < lln; len++)
        {
Robert Knight's avatar
   
Robert Knight committed
882
            const Character& ch = newLine[x+len];
883

Robert Knight's avatar
   
Robert Knight committed
884
885
886
887
            if (!ch.character)
                continue; // Skip trailing part of multi-col chars.

            if (  ch.foregroundColor != cf || 
888
                  ch.backgroundColor != _clipboard || 
Robert Knight's avatar
   
Robert Knight committed
889
890
891
892
                  ch.rendition != cr ||
                  !dirtyMask[x+len] || 
                  isLineChar(c) != lineDraw || 
                  (newLine[x+len+1].character == 0) != doubleWidth )
893
            break;
894

Stephan Binner's avatar
Stephan Binner committed
895
          disstrU[p++] = c; //fontMap(c);
896
        }
897
898

        QString unistr(disstrU, p);
899

900
        bool save__fixedFont = _fixedFont;
901
        if (lineDraw)
902
           _fixedFont = false;
903
        if (doubleWidth)
904
           _fixedFont = false;
905

906
		updateLine = true;
907

908
		_fixedFont = save__fixedFont;
909
910
        x += len - 1;
      }
911
      
912
    }
913

914
	//both the top and bottom halves of double height _lines must always be redrawn
Robert Knight's avatar
   
Robert Knight committed
915
916
	//although both top and bottom halves contain the same characters, only 
    //the top one is actually 
917
	//drawn.
918
919
    if (_lineProperties.count() > y)
        updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT);
Robert Knight's avatar
   
Robert Knight committed
920

921
    // if the characters on the line are different in the old and the new _image
Robert Knight's avatar
   
Robert Knight committed
922
    // then this line must be repainted.    
923
924
    if (updateLine)
    {
925
        dirtyLineCount++;
Robert Knight's avatar
   
Robert Knight committed
926
927
928

        // add the area occupied by this line to the region which needs to be
        // repainted
929
930
931
932
        QRect dirtyRect = QRect( _bX+tLx , 
                                 _bY+tLy+_fontHeight*y , 
                                 _fontWidth * columnsToUpdate , 
                                 _fontHeight ); 	
933

934
        dirtyRegion |= dirtyRect;
935
    }
936

937
938
    // replace the line of characters in the old _image with the 
    // current line of the new _image 
939
    memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character));
940
  }
941

942
  // free the image from the screen window
943
  delete[] newimg;
944

945
  // debugging - display a count of the number of lines that will need 
Robert Knight's avatar
   
Robert Knight committed
946
  // to be repainted
947
  //qDebug() << "dirty line count = " << dirtyLineCount;
948

949
950
951
  // if the new _image is smaller than the previous _image, then ensure that the area
  // outside the new _image is cleared 
  if ( linesToUpdate < _usedLines )
952
  {
953
954
955
956
    dirtyRegion |= QRect(   _bX+tLx , 
                            _bY+tLy+_fontHeight*linesToUpdate , 
                            _fontWidth * this->_columns , 
                            _fontHeight * (_usedLines-linesToUpdate) );
957
  }
958
  _usedLines = linesToUpdate;
959
  
960
  if ( columnsToUpdate < _usedColumns )
961
  {
962
963
964
965
    dirtyRegion |= QRect(   _bX+tLx+columnsToUpdate*_fontWidth , 
                            _bY+tLy , 
                            _fontWidth * (_usedColumns-columnsToUpdate) , 
                            _fontHeight * this->_lines );
966
  }
967
  _usedColumns = columnsToUpdate;
968

969
970
  dirtyRegion |= _inputMethodData.previousPreeditRect;

971
972
  //qDebug() << "Expecting to update: " << dirtyRegion.boundingRect();

Robert Knight's avatar
   
Robert Knight committed
973
  // update the parts of the display which have changed
974
  update(dirtyRegion);
Stephan Kulow's avatar
Stephan Kulow committed
975

976
977
  if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY ); 
  if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; }
978
979
  delete[] dirtyMask;
  delete[] disstrU;
980

981
982
983
  showResizeNotification();
}

984
void TerminalDisplay::showResizeNotification()
985
{
986
  if (_resizing && _terminalSizeHint)
987
  {
988
989
     if (_terminalSizeStartup) {
       _terminalSizeStartup=false;
990
991
       return;
     }
992
     if (!_resizeWidget)