textrender.cpp 14.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
    Copyright 2011-2012 Heikki Holstila <heikki.holstila@gmail.com>

    This file is part of FingerTerm.

    FingerTerm 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.

    FingerTerm 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 FingerTerm.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QtGui>
#include "textrender.h"
#include "terminal.h"
#include "util.h"

25 26 27
Terminal* TextRender::sTerm = 0;
Util* TextRender::sUtil = 0;

John Brooks's avatar
John Brooks committed
28
TextRender::TextRender(QQuickItem *parent) :
29
    QQuickPaintedItem(parent),
30 31
    newSelection(true),
    iAllowGestures(true)
32
{
John Brooks's avatar
John Brooks committed
33
    setFlag(ItemHasContents);
34

35 36
    connect(this,SIGNAL(widthChanged()),this,SLOT(updateTermSize()));
    connect(this,SIGNAL(heightChanged()),this,SLOT(updateTermSize()));
37 38 39 40 41 42 43 44 45 46 47
    connect(this,SIGNAL(fontSizeChanged()),this,SLOT(updateTermSize()));

    //normal
    iColorTable.append(QColor(0, 0, 0));
    iColorTable.append(QColor(210, 0, 0));
    iColorTable.append(QColor(0, 210, 0));
    iColorTable.append(QColor(210, 210, 0));
    iColorTable.append(QColor(0, 0, 240));
    iColorTable.append(QColor(210, 0, 210));
    iColorTable.append(QColor(0, 210, 210));
    iColorTable.append(QColor(235, 235, 235));
48

49 50 51 52 53 54 55 56 57 58
    //bright
    iColorTable.append(QColor(127, 127, 127));
    iColorTable.append(QColor(255, 0, 0));
    iColorTable.append(QColor(0, 255, 0));
    iColorTable.append(QColor(255, 255, 0));
    iColorTable.append(QColor(92, 92, 255));
    iColorTable.append(QColor(255, 0, 255));
    iColorTable.append(QColor(0, 255, 255));
    iColorTable.append(QColor(255, 255, 255));

59 60
    //colour cube
    for (int r = 0x00; r < 0x100; r += 0x33)
61 62 63
        for (int g = 0x00; g < 0x100; g += 0x33)
            for (int b = 0x00; b < 0x100; b += 0x33)
                iColorTable.append(QColor(r, g, b));
64 65 66 67 68 69 70 71 72 73

    //greyscale ramp
    int ramp[] = {
          0,  11,  22,  33,  44,  55,  66,  77,  88,  99, 110, 121,
        133, 144, 155, 166, 177, 188, 199, 210, 221, 232, 243, 255
    };
    for (int i = 0; i < 24; i++)
        iColorTable.append(QColor(ramp[i], ramp[i], ramp[i]));

    if(iColorTable.size() != 256)
74 75 76
        qFatal("invalid color table");

    iShowBufferScrollIndicator = false;
77

78
    iFont = QFont(sUtil->fontFamily(), sUtil->fontSize());
elros34's avatar
elros34 committed
79
    iFont.setStyleHint(QFont::Monospace, QFont::StyleStrategy(QFont::PreferDefault | QFont::ForceIntegerMetrics));
80 81 82 83 84 85
    iFont.setBold(false);
    QFontMetrics fontMetrics(iFont);
    iFontHeight = fontMetrics.height();
    iFontWidth = fontMetrics.maxWidth();
    iFontDescent = fontMetrics.descent();

86
    Q_ASSERT(sTerm);
87 88
    connect(sTerm, SIGNAL(displayBufferChanged()), this, SLOT(redraw()));
    connect(sTerm, SIGNAL(cursorPosChanged(QPoint)), this, SLOT(redraw()));
Pekka Vuorela's avatar
Pekka Vuorela committed
89
    connect(sTerm, SIGNAL(termSizeChanged(int,int)), this, SLOT(redraw()));
90 91 92
    connect(sTerm, SIGNAL(selectionChanged()), this, SLOT(redraw()));
    connect(sTerm, SIGNAL(scrollBackBufferAdjusted(bool)), this, SLOT(handleScrollBack(bool)));
    updateTermSize();
93 94 95 96 97 98
}

TextRender::~TextRender()
{
}

John Brooks's avatar
John Brooks committed
99
void TextRender::paint(QPainter* painter)
100 101 102 103 104
{
    painter->save();
    painter->setFont(iFont);

    int y=0;
105 106
    if (sTerm->backBufferScrollPos() != 0 && sTerm->backBuffer().size()>0) {
        int from = sTerm->backBuffer().size() - sTerm->backBufferScrollPos();
107 108
        if(from<0)
            from=0;
109
        int to = sTerm->backBuffer().size();
110 111
        if(to-from > sTerm->rows())
            to = from + sTerm->rows();
112
        paintFromBuffer(painter, sTerm->backBuffer(), from, to, y);
113 114
        if(to-from < sTerm->rows() && sTerm->buffer().size()>0) {
            int to2 = sTerm->rows() - (to-from);
115 116 117
            if(to2 > sTerm->buffer().size())
                to2 = sTerm->buffer().size();
            paintFromBuffer(painter, sTerm->buffer(), 0, to2, y);
118 119
        }
    } else {
120
        int count = qMin(sTerm->rows(), sTerm->buffer().size());
121
        paintFromBuffer(painter, sTerm->buffer(), 0, count, y);
122 123 124
    }

    // cursor
125
    if (sTerm->showCursor()) {
126
        painter->setOpacity(0.5);
127 128
        QPoint cursor = cursorPixelPos();
        QSize csize = cursorPixelSize();
129 130
        painter->setPen(Qt::transparent);
        painter->setBrush(iColorTable[Terminal::defaultFgColor]);
131 132 133 134
        painter->drawRect(cursor.x(), cursor.y(), csize.width(), csize.height());
    }

    // selection
135
    QRect selection = sTerm->selection();
136 137 138 139 140 141 142 143 144 145 146 147 148
    if (!selection.isNull()) {
        painter->setOpacity(0.5);
        painter->setPen(Qt::transparent);
        painter->setBrush(Qt::blue);
        QPoint start, end;

        if (selection.top() == selection.bottom()) {
            start = charsToPixels(selection.topLeft());
            end = charsToPixels(selection.bottomRight());
            painter->drawRect(start.x(), start.y(),
                              end.x()-start.x()+fontWidth(), end.y()-start.y()+fontHeight());
        } else {
            start = charsToPixels(selection.topLeft());
149
            end = charsToPixels(QPoint(sTerm->columns(), selection.top()));
150 151 152 153
            painter->drawRect(start.x(), start.y(),
                              end.x()-start.x()+fontWidth(), end.y()-start.y()+fontHeight());

            start = charsToPixels(QPoint(1, selection.top()+1));
154
            end = charsToPixels(QPoint(sTerm->columns(), selection.bottom()-1));
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            painter->drawRect(start.x(), start.y(),
                              end.x()-start.x()+fontWidth(), end.y()-start.y()+fontHeight());

            start = charsToPixels(QPoint(1, selection.bottom()));
            end = charsToPixels(selection.bottomRight());
            painter->drawRect(start.x(), start.y(),
                              end.x()-start.x()+fontWidth(), end.y()-start.y()+fontHeight());
        }
    }

    painter->restore();
}

void TextRender::paintFromBuffer(QPainter* painter, QList<QList<TermChar> >& buffer, int from, int to, int &y)
{
    const int leftmargin = 2;
    int cutAfter = property("cutAfter").toInt() + iFontDescent;

173 174 175
    TermChar tmp = sTerm->zeroChar;
    TermChar nextAttrib = sTerm->zeroChar;
    TermChar currAttrib = sTerm->zeroChar;
176 177 178 179 180 181 182 183 184
    int currentX = leftmargin;
    for(int i=from; i<to; i++) {
        y += iFontHeight;

        if(y >= cutAfter)
            painter->setOpacity(0.3);
        else
            painter->setOpacity(1.0);

185
        int xcount = qMin(buffer.at(i).count(), sTerm->columns());
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

        // background for the current line
        currentX = leftmargin;
        int fragWidth = 0;
        for(int j=0; j<xcount; j++) {
            tmp = buffer[i][j];
            fragWidth += iFontWidth;
            if (j==0) {
                currAttrib = tmp;
                nextAttrib = tmp;
            } else if (j<xcount-1) {
                nextAttrib = buffer[i][j+1];
            }

            if (currAttrib.attrib != nextAttrib.attrib ||
                currAttrib.bgColor != nextAttrib.bgColor ||
                currAttrib.fgColor != nextAttrib.fgColor ||
                j==xcount-1)
            {
                drawBgFragment(painter, currentX, y-iFontHeight+iFontDescent, fragWidth, currAttrib);
                currentX += fragWidth;
                fragWidth = 0;
                currAttrib.attrib = nextAttrib.attrib;
                currAttrib.bgColor = nextAttrib.bgColor;
                currAttrib.fgColor = nextAttrib.fgColor;
            }
        }

        // text for the current line
        QString line;
        currentX = leftmargin;
        for (int j=0; j<xcount; j++) {
            tmp = buffer[i][j];
            line += tmp.c;
            if (j==0) {
                currAttrib = tmp;
                nextAttrib = tmp;
            } else if(j<xcount-1) {
                nextAttrib = buffer[i][j+1];
            }

            if (currAttrib.attrib != nextAttrib.attrib ||
                currAttrib.bgColor != nextAttrib.bgColor ||
                currAttrib.fgColor != nextAttrib.fgColor ||
                j==xcount-1)
            {
                drawTextFragment(painter, currentX, y, line, currAttrib);
                currentX += iFontWidth*line.length();
                line.clear();
                currAttrib.attrib = nextAttrib.attrib;
                currAttrib.bgColor = nextAttrib.bgColor;
                currAttrib.fgColor = nextAttrib.fgColor;
            }
        }
    }
}

void TextRender::drawBgFragment(QPainter* painter, int x, int y, int width, TermChar style)
{
    if (style.attrib & attribNegative) {
        int c = style.fgColor;
        style.fgColor = style.bgColor;
        style.bgColor = c;
    }

    if (style.bgColor == Terminal::defaultBgColor)
        return;

    painter->setPen(Qt::transparent);
    painter->setBrush( iColorTable[style.bgColor] );
    painter->drawRect(x, y, width, iFontHeight);
}

void TextRender::drawTextFragment(QPainter* painter, int x, int y, QString text, TermChar style)
{
    if (style.attrib & attribNegative) {
        int c = style.fgColor;
        style.fgColor = style.bgColor;
        style.bgColor = c;
    }
    if (style.attrib & attribBold) {
        iFont.setBold(true);
        painter->setFont(iFont);
        if(style.fgColor < 8)
            style.fgColor += 8;
    } else if(iFont.bold()) {
        iFont.setBold(false);
        painter->setFont(iFont);
    }

    painter->setPen( iColorTable[style.fgColor] );
    painter->setBrush(Qt::transparent);
    painter->drawText(x, y, text);
}

void TextRender::redraw()
{
John Brooks's avatar
John Brooks committed
283
    update();
284 285
}

286
void TextRender::setUtil(Util *util)
287
{
288 289
    sUtil = util;
}
290

291 292 293
void TextRender::setTerminal(Terminal *terminal)
{
    sTerm = terminal;
294 295 296 297
}

void TextRender::updateTermSize()
{
298
    QSize size((width() - 4) / iFontWidth, (height() - 4) / iFontHeight);
299 300 301
    sTerm->setTermSize(size);
}

302 303
void TextRender::mousePress(float eventX, float eventY)
{
304
    if (!allowGestures())
305 306 307 308 309 310 311 312 313 314
        return;

    dragOrigin = QPointF(eventX, eventY);
    newSelection = true;
}

void TextRender::mouseMove(float eventX, float eventY)
{
    QPointF eventPos(eventX, eventY);

315
    if (!allowGestures())
316 317
        return;

318
    if(sUtil->dragMode() == Util::DragScroll) {
319 320
        dragOrigin = scrollBackBuffer(eventPos, dragOrigin);
    }
321
    else if(sUtil->dragMode() == Util::DragSelect) {
322 323 324 325 326 327 328 329 330
        selectionHelper(eventPos, true);
    }
}

void TextRender::mouseRelease(float eventX, float eventY)
{
    QPointF eventPos(eventX, eventY);
    const int reqDragLength = 140;

331
    if (!allowGestures())
332 333
        return;

334
    if(sUtil->dragMode() == Util::DragGestures) {
335 336 337 338 339 340 341 342 343 344 345
        int xdist = qAbs(eventPos.x() - dragOrigin.x());
        int ydist = qAbs(eventPos.y() - dragOrigin.y());
        if(eventPos.x() < dragOrigin.x()-reqDragLength && xdist > ydist*2)
            doGesture(PanLeft);
        else if(eventPos.x() > dragOrigin.x()+reqDragLength && xdist > ydist*2)
            doGesture(PanRight);
        else if(eventPos.y() > dragOrigin.y()+reqDragLength && ydist > xdist*2)
            doGesture(PanDown);
        else if(eventPos.y() < dragOrigin.y()-reqDragLength && ydist > xdist*2)
            doGesture(PanUp);
    }
346
    else if(sUtil->dragMode() == Util::DragScroll) {
347 348
        scrollBackBuffer(eventPos, dragOrigin);
    }
349
    else if(sUtil->dragMode() == Util::DragSelect) {
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        selectionHelper(eventPos, false);
    }
}

void TextRender::selectionHelper(QPointF scenePos, bool selectionOngoing)
{
    int yCorr = fontDescent();

    QPoint start(qRound((dragOrigin.x()+2) / fontWidth()),
                 qRound((dragOrigin.y()+yCorr) / fontHeight()));
    QPoint end(qRound((scenePos.x()+2) / fontWidth()),
               qRound((scenePos.y()+yCorr) / fontHeight()));

    if (start != end) {
        sTerm->setSelection(start, end, selectionOngoing);
        newSelection = false;
    }
}

369 370 371 372 373 374 375 376
void TextRender::handleScrollBack(bool reset)
{
    if (reset) {
        setShowBufferScrollIndicator(false);
    } else {
        setShowBufferScrollIndicator(sTerm->backBufferScrollPos() != 0);
    }
    redraw();
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
}

void TextRender::setFontPointSize(int psize)
{
    if (iFont.pointSize() != psize)
    {
        iFont.setPointSize(psize);
        QFontMetrics fontMetrics(iFont);
        iFontHeight = fontMetrics.height();
        iFontWidth = fontMetrics.maxWidth();
        iFontDescent = fontMetrics.descent();
        emit fontSizeChanged();
    }
}

QPoint TextRender::cursorPixelPos()
{
394
    return charsToPixels(sTerm->cursorPos());
395 396 397 398 399 400 401 402 403 404
}

QPoint TextRender::charsToPixels(QPoint pos)
{
    // not 100% accurrate with all fonts
    return QPoint(2+(pos.x()-1)*iFontWidth, (pos.y()-1)*iFontHeight+iFontDescent+1);
}

QSize TextRender::cursorPixelSize()
{
405
    return QSize(iFontWidth, iFontHeight);
406
}
407

408 409 410 411 412 413 414 415 416 417 418 419 420
bool TextRender::allowGestures()
{
    return iAllowGestures;
}

void TextRender::setAllowGestures(bool allow)
{
    if (iAllowGestures != allow) {
        iAllowGestures = allow;
        emit allowGesturesChanged();
    }
}

421 422 423 424
QPointF TextRender::scrollBackBuffer(QPointF now, QPointF last)
{
    int xdist = qAbs(now.x() - last.x());
    int ydist = qAbs(now.y() - last.y());
425
    int fontSize = fontPointSize();
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

    int lines = ydist / fontSize;

    if(lines > 0 && now.y() < last.y() && xdist < ydist*2) {
        sTerm->scrollBackBufferFwd(lines);
        last = QPointF(now.x(), last.y() - lines * fontSize);
    } else if(lines > 0 && now.y() > last.y() && xdist < ydist*2) {
        sTerm->scrollBackBufferBack(lines);
        last = QPointF(now.x(), last.y() + lines * fontSize);
    }

    return last;
}

void TextRender::doGesture(PanGesture gesture)
{
    if( gesture==PanLeft ) {
443 444
        sUtil->notifyText(sUtil->settingsValue("gestures/panLeftTitle", "Alt-Right").toString());
        sTerm->putString(sUtil->settingsValue("gestures/panLeftCommand", "\\e\\e[C").toString(), true);
445 446
    }
    else if( gesture==PanRight ) {
447 448
        sUtil->notifyText(sUtil->settingsValue("gestures/panRightTitle", "Alt-Left").toString());
        sTerm->putString(sUtil->settingsValue("gestures/panRightCommand", "\\e\\e[D").toString(), true);
449 450
    }
    else if( gesture==PanDown ) {
451 452
        sUtil->notifyText(sUtil->settingsValue("gestures/panDownTitle", "Page Up").toString());
        sTerm->putString(sUtil->settingsValue("gestures/panDownCommand", "\\e[5~").toString(), true);
453 454
    }
    else if( gesture==PanUp ) {
455 456
        sUtil->notifyText(sUtil->settingsValue("gestures/panUpTitle", "Page Down").toString());
        sTerm->putString(sUtil->settingsValue("gestures/panUpCommand", "\\e[6~").toString(), true);
457 458
    }
}