terminal.cpp 44.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
    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/>.
*/

John Brooks's avatar
John Brooks committed
20
#include <QGuiApplication>
21
#include <QClipboard>
22
#include <QDebug>
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

#include "terminal.h"
#include "ptyiface.h"
#include "textrender.h"
#include "util.h"

Terminal::Terminal(QObject *parent) :
    QObject(parent), iRenderer(0), iPtyIFace(0), iWindow(0), iUtil(0),
    iTermSize(0,0), iEmitCursorChangeSignal(true),
    iShowCursor(true), iUseAltScreenBuffer(false), iAppCursorKeys(false)
{
    zeroChar.c = ' ';
    zeroChar.bgColor = defaultBgColor;
    zeroChar.fgColor = defaultFgColor;
    zeroChar.attrib = 0;

    escape = -1;

    iTermAttribs.currentFgColor = defaultFgColor;
    iTermAttribs.currentBgColor = defaultBgColor;
    iTermAttribs.currentAttrib = 0;
    iTermAttribs.cursorPos = QPoint(0,0);
    iMarginBottom = 0;
    iMarginTop = 0;

    resetBackBufferScrollPos();

    iTermAttribs_saved = iTermAttribs;
    iTermAttribs_saved_alt = iTermAttribs;

    resetTerminal();
}

void Terminal::setRenderer(TextRender* tr)
{
    iRenderer = tr;

    if(tr) {
        tr->updateTermSize();
        connect(this, SIGNAL(displayBufferChanged()), tr, SLOT(redraw()));
        connect(this, SIGNAL(cursorPosChanged(QPoint)), tr, SLOT(redraw()));
        connect(this, SIGNAL(termSizeChanged(QSize)), tr, SLOT(redraw()));
    } else {
        qDebug() << "warning: null text renderer";
    }
}

void Terminal::setPtyIFace(PtyIFace *pty)
{
    iPtyIFace = pty;
    if(!pty) {
        qDebug() << "warning: null pty iface";
    }
}

void Terminal::setCursorPos(QPoint pos)
{
    if( iTermAttribs.cursorPos != pos ) {
        int tlimit = 1;
        int blimit = iTermSize.height();
        if(iTermAttribs.originMode) {
            tlimit = iMarginTop;
            blimit = iMarginBottom;
        }

        if(pos.x() < 1)
            pos.setX(1);
        if(pos.x() > iTermSize.width()+1)
            pos.setX(iTermSize.width()+1);
        if(pos.y() < tlimit)
            pos.setY(tlimit);
        if(pos.y() > blimit)
            pos.setY(blimit);

        iTermAttribs.cursorPos=pos;
        if(iEmitCursorChangeSignal)
            emit cursorPosChanged(pos);
    }
}

QPoint Terminal::cursorPos()
{
    return iTermAttribs.cursorPos;
}

bool Terminal::showCursor()
{
    if(iBackBufferScrollPos != 0)
        return false;

    return iShowCursor;
}

QList<QList<TermChar> >& Terminal::buffer()
{
    if(iUseAltScreenBuffer)
        return iAltBuffer;

    return iBuffer;
}

void Terminal::setTermSize(QSize size)
{
    if( iTermSize != size ) {
        iMarginTop = 1;
        iMarginBottom = size.height();
        iTermSize=size;

        resetTabs();

        emit termSizeChanged(size);
    }
}

void Terminal::putString(QString str, bool unEscape)
{
    if (unEscape) {
        str.replace("\\r", "\r");
        str.replace("\\n", "\n");
        str.replace("\\e", QChar(ch_ESC));
        str.replace("\\b", "\b");
        str.replace("\\t", "\t");

146
        //hex
147 148 149
        while(str.indexOf("\\x") != -1) {
            int i = str.indexOf("\\x")+2;
            QString num;
150
            while(num.length() < 2 && str.length()>i && Util::charIsHexDigit(str.at(i))) {
151 152 153 154 155 156 157
                num.append(str.at(i));
                i++;
            }
            str.remove(i-2-num.length(), num.length()+2);
            bool ok;
            str.insert(i-2-num.length(), QChar(num.toInt(&ok,16)));
        }
158
        //octal
159 160 161
        while(str.indexOf("\\0") != -1) {
            int i = str.indexOf("\\0")+2;
            QString num;
162
            while(num.length() < 3 && str.length()>i &&
Aard's avatar
Aard committed
163
                  (str.at(i).toLatin1() >= 48 && str.at(i).toLatin1() <= 55)) { //accept only 0-7
164 165 166 167 168 169 170 171 172 173 174 175 176
                num.append(str.at(i));
                i++;
            }
            str.remove(i-2-num.length(), num.length()+2);
            bool ok;
            str.insert(i-2-num.length(), QChar(num.toInt(&ok,8)));
        }
    }

    if(iPtyIFace)
        iPtyIFace->writeTerm(str);
}

177
void Terminal::keyPress(int key, int modifiers, const QString& text)
178
{
179
    QString toWrite;
180 181 182

    resetBackBufferScrollPos();

183 184 185 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
    if (key > 0xFFFF) {
        int modcode = (modifiers & Qt::ShiftModifier ? 1 : 0) | 
                      (modifiers & Qt::AltModifier ? 2 : 0) |
                      (modifiers & Qt::ControlModifier ? 4 : 0);

        if (modcode == 0) {
            QString fmt;
            char cursorModif='[';
            if(iAppCursorKeys)
                cursorModif = 'O';

            if( key==Qt::Key_Up ) fmt = QString("%2%1A").arg(cursorModif);
            if( key==Qt::Key_Down ) fmt = QString("%2%1B").arg(cursorModif);
            if( key==Qt::Key_Right ) fmt = QString("%2%1C").arg(cursorModif);
            if( key==Qt::Key_Left ) fmt = QString("%2%1D").arg(cursorModif);
            if( key==Qt::Key_PageUp ) fmt = "%1[5~";
            if( key==Qt::Key_PageDown ) fmt = "%1[6~";
            if( key==Qt::Key_Home ) fmt = "%1OH";
            if( key==Qt::Key_End ) fmt = "%1OF";
            if( key==Qt::Key_Insert ) fmt = "%1[2~";
            if( key==Qt::Key_Delete ) fmt = "%1[3~";

            if( key==Qt::Key_F1 ) fmt = "%1OP";
            if( key==Qt::Key_F2 ) fmt = "%1OQ";
            if( key==Qt::Key_F3 ) fmt = "%1OR";
            if( key==Qt::Key_F4 ) fmt = "%1OS";
            if( key==Qt::Key_F5 ) fmt = "%1[15~";
            if( key==Qt::Key_F6 ) fmt = "%1[17~";
            if( key==Qt::Key_F7 ) fmt = "%1[18~";
            if( key==Qt::Key_F8 ) fmt = "%1[19~";
            if( key==Qt::Key_F9 ) fmt = "%1[20~";
            if( key==Qt::Key_F10 ) fmt = "%1[21~";
            if( key==Qt::Key_F11 ) fmt = "%1[23~";
            if( key==Qt::Key_F12 ) fmt = "%1[24~";
            
            if (!fmt.isEmpty())
                toWrite += fmt.arg(ch_ESC);
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
        } else {
            QString fmt;
            char modChar = '1' + modcode;

            if( key==Qt::Key_Up ) fmt = "%1[1;%2A";
            if( key==Qt::Key_Down ) fmt = "%1[1;%2B";
            if( key==Qt::Key_Right ) fmt = "%1[1;%2C";
            if( key==Qt::Key_Left ) fmt = "%1[1;%2D";
            if( key==Qt::Key_PageUp ) fmt = "%1[5;%2~";
            if( key==Qt::Key_PageDown ) fmt = "%1[6;%2~";
            if( key==Qt::Key_Home ) fmt = "%1[1;%2H";
            if( key==Qt::Key_End ) fmt = "%1[1;%2F";
            if( key==Qt::Key_Insert ) fmt = "%1[2;%2~";
            if( key==Qt::Key_Delete ) fmt = "%1[3;%2~";

            if( key==Qt::Key_F1 ) fmt = "%1[1;%2P";
            if( key==Qt::Key_F2 ) fmt = "%1[1;%2Q";
            if( key==Qt::Key_F3 ) fmt = "%1[1;%2R";
            if( key==Qt::Key_F4 ) fmt = "%1[1;%2S";
            if( key==Qt::Key_F5 ) fmt = "%1[15;%2~";
            if( key==Qt::Key_F6 ) fmt = "%1[17;%2~";
            if( key==Qt::Key_F7 ) fmt = "%1[18;%2~";
            if( key==Qt::Key_F8 ) fmt = "%1[19;%2~";
            if( key==Qt::Key_F9 ) fmt = "%1[20;%2~";
            if( key==Qt::Key_F10 ) fmt = "%1[21;%2~";
            if( key==Qt::Key_F11 ) fmt = "%1[23;%2~";
            if( key==Qt::Key_F12 ) fmt = "%1[24;%2~";

            if (!fmt.isEmpty())
                toWrite += fmt.arg(ch_ESC).arg(modChar);
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
        if( key==Qt::Key_Enter || key==Qt::Key_Return ) {
            if ( (modifiers & (Qt::ShiftModifier | Qt::ControlModifier)) ==
                (Qt::ShiftModifier | Qt::ControlModifier) )
                toWrite += QChar(0x9E);
            else if (modifiers & Qt::ControlModifier)
                toWrite += QChar(0x1E); // ^^
            else if (modifiers & Qt::ShiftModifier)
                toWrite += "\n";
            else if(iNewLineMode)
                toWrite += "\r\n";
            else
                toWrite += "\r";
        }
        if( key==Qt::Key_Backspace ) {
            if ( (modifiers & (Qt::ShiftModifier | Qt::ControlModifier)) ==
                (Qt::ShiftModifier | Qt::ControlModifier) )
                toWrite += QChar(0x9F);
            else if (modifiers & Qt::ControlModifier)
                toWrite += QChar(0x1F); // ^_
            else
                toWrite += "\x7F";
        }
        if( key==Qt::Key_Tab || key==Qt::Key_Backtab ) {
            if ( key == Qt::Key_Backtab ) modifiers |= Qt::ShiftModifier;
            if (modifiers & Qt::ControlModifier) {
                char modChar = '5' + (modifiers & Qt::ShiftModifier ? 1 : 0);
                toWrite += QString("%1[1;%2I").arg(ch_ESC).arg(modChar);
            } else if (modifiers & Qt::ShiftModifier) {
                toWrite += QString("%1[Z").arg(ch_ESC);
283
            } else {
284
                toWrite += "\t";
285 286
            }
        }
287

288 289 290 291 292 293 294 295 296 297 298 299
        if( key==Qt::Key_Escape ) {
            if (modifiers & Qt::ShiftModifier)
                toWrite += QChar(0x9B);
            else
                toWrite += QString(1,ch_ESC);
        }

        if (!toWrite.isEmpty()) {
            if(iPtyIFace)
                iPtyIFace->writeTerm(toWrite);
        } else {
            qDebug() << "unknown special key: " << key;
300
        }
301 302 303
        return;
    }

304 305 306 307
    QChar c(key);

    if (c.isLetter()) {
        c = ((modifiers & Qt::ShiftModifier) != 0) ? c.toUpper() : c.toLower();
308
    }
309 310 311

    if((modifiers & Qt::AltModifier) != 0) {
        toWrite.append(ch_ESC);
312 313
    }

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    if ((modifiers & Qt::ControlModifier) != 0) {
        char asciiVal = c.toUpper().toLatin1();

        if (asciiVal >= 0x41 && asciiVal <= 0x5f) {
            // Turn uppercase characters into their control code equivalent
            toWrite.append(asciiVal - 0x40);
        } else {
            qWarning() << "Ctrl+" << c << " does not translate into a control code";
        }
    } else {
        if (text.isEmpty()) {
            toWrite.append(c);
        } else {
            toWrite.append(text);
        }
    }

    if (iPtyIFace) {
332
        iPtyIFace->writeTerm(toWrite);
333 334
    }
    return;
335 336 337 338 339 340 341 342 343 344 345 346 347
}

void Terminal::insertInBuffer(const QString& chars)
{
    if(iTermSize.isNull()) {
        qDebug() << "null size terminal";
        return;
    }

    iEmitCursorChangeSignal = false;

    for(int i=0; i<chars.size(); i++) {
        QChar ch = chars.at(i);
Aard's avatar
Aard committed
348
        if(ch.toLatin1()=='\n' || ch.toLatin1()==11 || ch.toLatin1()==12) {  // line feed, vertical tab or form feed
349 350 351 352 353 354 355 356 357 358 359 360 361
            if(cursorPos().y()==iMarginBottom) {
                scrollFwd(1);
                if(iNewLineMode)
                    setCursorPos(QPoint(1,cursorPos().y()));
            }
            else if(cursorPos().x() <= termSize().width()) // ignore newline after <termwidth> cols (terminfo: xenl)
            {
                if(iNewLineMode)
                    setCursorPos(QPoint(1,cursorPos().y()+1));
                else
                    setCursorPos(QPoint(cursorPos().x(), cursorPos().y()+1));
            }
        }
Aard's avatar
Aard committed
362
        else if(ch.toLatin1()=='\r') {  // carriage return
363 364
            setCursorPos(QPoint(1,cursorPos().y()));
        }
Aard's avatar
Aard committed
365
        else if(ch.toLatin1()=='\b' || ch.toLatin1()==127) {  //backspace & del (only move cursor, don't erase)
366 367
            setCursorPos(QPoint(cursorPos().x()-1,cursorPos().y()));
        }
Aard's avatar
Aard committed
368
        else if(ch.toLatin1()=='\a') {  // BEL
369 370 371 372 373 374 375 376
            if(escape==']') {  // BEL also ends OSC sequence
                escape=-1;
                oscSequence(oscSeq);
                oscSeq.clear();
            } else {
                iUtil->bellAlert();
            }
        }
Aard's avatar
Aard committed
377
        else if(ch.toLatin1()=='\t') {  //tab
378 379 380 381 382 383 384 385 386
            if(cursorPos().y() <= iTabStops.size()) {
                for(int i=0; i<iTabStops[cursorPos().y()-1].count(); i++) {
                    if(iTabStops[cursorPos().y()-1][i] > cursorPos().x()) {
                        setCursorPos(QPoint( iTabStops[cursorPos().y()-1][i], cursorPos().y() ));
                        break;
                    }
                }
            }
        }
Aard's avatar
Aard committed
387
        else if(ch.toLatin1()==14 || ch.toLatin1()==15) {  //SI and SO, related to character set... ignore
388 389 390
        }
        else {
            if( escape>=0 ) {
Aard's avatar
Aard committed
391
                if( escape==0 && (ch.toLatin1()=='[') ) {
392 393 394
                    escape='['; //ansi sequence
                    escSeq += ch;
                }
Aard's avatar
Aard committed
395
                else if( escape==0 && (ch.toLatin1()==']') ) {
396 397 398
                    escape=']'; //osc sequence
                    oscSeq += ch;
                }
Aard's avatar
Aard committed
399 400
                else if( escape==0 && multiCharEscapes.contains(ch.toLatin1())) {
                    escape = ch.toLatin1();
401 402
                    escSeq += ch;
                }
Aard's avatar
Aard committed
403
                else if( escape==0 && ch.toLatin1()=='\\' ) {  // ESC\ also ends OSC sequence
404 405 406 407
                    escape=-1;
                    oscSequence(oscSeq);
                    oscSeq.clear();
                }
Aard's avatar
Aard committed
408
                else if (ch.toLatin1()==ch_ESC) {
409 410 411 412 413 414 415 416 417 418 419 420
                    escape = 0;
                }
                else if( escape=='[' || multiCharEscapes.contains(escape) ) {
                    escSeq += ch;
                }
                else if( escape==']' ) {
                    oscSeq += ch;
                }
                else if( multiCharEscapes.contains(escape) ) {
                    escSeq += ch;
                }
                else {
Aard's avatar
Aard committed
421
                    escControlChar(QByteArray(1,ch.toLatin1()));
422 423 424
                    escape=-1;
                }

Aard's avatar
Aard committed
425
                if( escape=='[' && ch.toLatin1() >= 64 && ch.toLatin1() <= 126 && ch.toLatin1() != '[' ) {
426 427 428 429 430 431 432 433 434 435 436 437
                    ansiSequence(escSeq);
                    escape=-1;
                    escSeq.clear();
                }
                if( multiCharEscapes.contains(escape) && escSeq.length()>=2 ) {
                    escControlChar(escSeq);
                    escape=-1;
                    escSeq.clear();
                }
            } else {
                if (ch.isPrint())
                    insertAtCursor(ch, !iReplaceMode);
Aard's avatar
Aard committed
438
                else if (ch.toLatin1()==ch_ESC)
439
                    escape=0;
440
                else if (ch.toLatin1() != 0)
Aard's avatar
Aard committed
441
                    qDebug() << "unprintable char" << int(ch.toLatin1());
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
            }
        }
    }

    iEmitCursorChangeSignal = true;
    emit displayBufferChanged();
}

void Terminal::insertAtCursor(QChar c, bool overwriteMode, bool advanceCursor)
{
    if(cursorPos().x() > iTermSize.width() && advanceCursor) {
        if(iTermAttribs.wrapAroundMode) {
            if(cursorPos().y()>=iMarginBottom) {
                scrollFwd(1);
                setCursorPos(QPoint(1, cursorPos().y()));
            } else {
                setCursorPos(QPoint(1, cursorPos().y()+1));
            }
        } else {
            setCursorPos(QPoint(iTermSize.width(), cursorPos().y()));
        }
    }

    while(currentLine().size() < cursorPos().x() )
        currentLine().append(zeroChar);

    if(!overwriteMode)
        currentLine().insert(cursorPos().x()-1,zeroChar);

    currentLine()[cursorPos().x()-1].c = c;
    currentLine()[cursorPos().x()-1].fgColor = iTermAttribs.currentFgColor;
    currentLine()[cursorPos().x()-1].bgColor = iTermAttribs.currentBgColor;
    currentLine()[cursorPos().x()-1].attrib = iTermAttribs.currentAttrib;

    if (advanceCursor) {
        setCursorPos(QPoint(cursorPos().x()+1,cursorPos().y()));
    }
}

void Terminal::deleteAt(QPoint pos)
{
    clearAt(pos);
    buffer()[pos.y()-1].removeAt(pos.x()-1);
}

void Terminal::clearAt(QPoint pos)
{
    if(pos.y() <= 0 || pos.y()-1 > buffer().size() ||
            pos.x() <= 0 || pos.x()-1 > buffer()[pos.y()-1].size())
    {
        qDebug() << "warning: trying to clear char out of bounds";
        return;
    }

    // just in case...
    while(buffer().size() < pos.y())
        buffer().append(QList<TermChar>());
    while(buffer()[pos.y()-1].size() < pos.x() )
        buffer()[pos.y()-1].append(zeroChar);

    buffer()[pos.y()-1][pos.x()-1] = zeroChar;
}

void Terminal::eraseLineAtCursor(int from, int to)
{
    if(from==-1 && to==-1) {
        currentLine().clear();
        return;
    }
    if(from < 1)
        from=1;
    from--;

    if(to < 1 || to > currentLine().size())
        to=currentLine().size();
    to--;

    if(from>to)
        return;

    for(int i=from; i<=to; i++) {
        currentLine()[i] = zeroChar;
    }
}

void Terminal::clearAll(bool wholeBuffer)
{
    clearSelection();
    if(wholeBuffer) {
        backBuffer().clear();
        resetBackBufferScrollPos();
    }
    buffer().clear();
    setCursorPos(QPoint(1,1));
}


void Terminal::ansiSequence(const QString& seq)
{
    if(seq.length() <= 1 || seq.at(0)!='[')
        return;

    QChar cmdChar = seq.at(seq.length()-1);
    QString extra;
    QList<int> params;

    int x=1;
    while(x<seq.length()-1 && !QChar(seq.at(x)).isNumber())
        x++;

    QList<QString> tmp = seq.mid(x,seq.length()-x-1).split(';');
    foreach(QString b, tmp) {
        bool ok=false;
        int t = b.toInt(&ok);
        if(ok) {
            params.append(t);
        }
    }
    if(x>1)
        extra = seq.mid(1,x-1);

    bool unhandled = false;

Aard's avatar
Aard committed
565
    switch(cmdChar.toLatin1())
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 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 608 609 610 611 612 613 614 615 616 617 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 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    {
    case 'A': //cursor up
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( cursorPos().x(), qMax(iMarginTop, cursorPos().y()-params.at(0)) ));
        break;
    case 'B': //cursor down
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( cursorPos().x(), qMin(iMarginBottom, cursorPos().y()+params.at(0)) ));
        break;
    case 'C': //cursor fwd
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( qMin(iTermSize.width(),cursorPos().x()+params.at(0)), cursorPos().y() ));
        break;
    case 'D': //cursor back
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( qMax(1,cursorPos().x()-params.at(0)), cursorPos().y() ));
        break;
    case 'E': //cursor next line
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( 1, qMin(iMarginBottom, cursorPos().y()+params.at(0)) ));
        break;
    case 'F': //cursor prev line
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( 1, qMax(iMarginTop, cursorPos().y()-params.at(0)) ));
        break;
    case 'G': //go to column
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( params.at(0), cursorPos().y() ));
        break;
    case 'H': //cursor pos
    case 'f': //cursor pos
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        while(params.count()<2)
            params.append(1);
        if (iTermAttribs.originMode)
            setCursorPos(QPoint( params.at(1), params.at(0)+iMarginTop-1 ));
        else
            setCursorPos(QPoint( params.at(1), params.at(0) ));
        break;
    case 'J': //erase data
        if(!extra.isEmpty() && extra!="?") {
            unhandled=true;
            break;
        }
        if(params.count()>=1 && params.at(0)==1) {
            eraseLineAtCursor(1,cursorPos().x());
            for(int i=0; i<cursorPos().y()-1; i++) {
                buffer()[i].clear();
            }
        } else if(params.count()>=1 && params.at(0)==2) {
            clearAll();
        } else {
            eraseLineAtCursor(cursorPos().x());
            for(int i=cursorPos().y(); i<buffer().size(); i++)
                buffer()[i].clear();
        }
        break;
    case 'K': //erase in line
        if(!extra.isEmpty() && extra!="?") {
            unhandled=true;
            break;
        }
        if(params.count()>=1 && params.at(0)==1) {
            eraseLineAtCursor(1,cursorPos().x());
        }
        else if(params.count()>=1 && params.at(0)==2) {
            currentLine().clear();
        } else {
            eraseLineAtCursor(cursorPos().x());
        }
        break;

    case 'L':  // insert lines
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(cursorPos().y() < iMarginTop || cursorPos().y() > iMarginBottom)
            break;
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        if(params.at(0) > iMarginBottom-cursorPos().y())
            scrollBack(iMarginBottom-cursorPos().y(), cursorPos().y());
        else
            scrollBack(params.at(0), cursorPos().y());
        setCursorPos(QPoint(1,cursorPos().y()));
        break;
    case 'M':  // delete lines
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(cursorPos().y() < iMarginTop || cursorPos().y() > iMarginBottom)
            break;
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        if(params.at(0) > iMarginBottom-cursorPos().y())
            scrollFwd(iMarginBottom-cursorPos().y(), cursorPos().y());
        else
            scrollFwd(params.at(0), cursorPos().y());
        setCursorPos(QPoint(1,cursorPos().y()));
        break;

    case 'P': // delete characters
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        for(int i=0; i<params.at(0); i++)
            deleteAt(cursorPos());
        break;
    case '@': // insert blank characters
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0] = 1;
        for(int i=1; i<=params.at(0); i++)
            insertAtCursor(zeroChar.c, false, false);
        break;

    case 'S':  // scroll up n lines
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        scrollFwd(params.at(0));
        break;
    case 'T':  // scroll down n lines
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        scrollBack(params.at(0));
        break;

    case 'c': // vt100 identification
        if(params.count()==0)
            params.append(0);
        if(params.count()==1 && params.at(0)==0) {
Aard's avatar
Aard committed
769
            QString toWrite = QString("%1[?1;2c").arg(ch_ESC).toLatin1();
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
            if(iPtyIFace)
                iPtyIFace->writeTerm(toWrite);
        } else unhandled=true;
        break;

    case 'd': //go to row
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count()<1)
            params.append(1);
        if(params.at(0)==0)
            params[0]=1;
        setCursorPos(QPoint( cursorPos().x(), params.at(0) ));
        break;

    case 'g': //tab stop manipulation
        if(params.count()==0)
            params.append(0);
        if(params.at(0)==0 && extra=="") {  //clear tab at current position
            if(cursorPos().y() <= iTabStops.size()) {
                int idx = iTabStops[cursorPos().y()-1].indexOf(cursorPos().x());
                if(idx != -1)
                    iTabStops[cursorPos().y()-1].removeAt(idx);
            }
        }
        else if(params.at(0)==3 && extra=="") {  //clear all tabs
            iTabStops.clear();
        }
        break;

    case 'n':
        if(params.count()>=1 && params.at(0)==6 && extra=="") {  // write cursor pos
Aard's avatar
Aard committed
804
            QString toWrite = QString("%1[%2;%3R").arg(ch_ESC).arg(cursorPos().y()).arg(cursorPos().x()).toLatin1();
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
            if(iPtyIFace)
                iPtyIFace->writeTerm(toWrite);
        } else unhandled=true;
        break;

    case 'p':
        if(extra=="!") {  // reset terminal
            resetTerminal();
        } else unhandled=true;
        break;

    case 's': //save cursor
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        iTermAttribs_saved = iTermAttribs;
        break;
    case 'u': //restore cursor
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        iTermAttribs = iTermAttribs_saved;
        break;

    case 'm': //graphics mode
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count() > 0) {
837 838 839
            // xterm 256-colour support
            if(params.count() > 1 && (params[0] == 38 || params[0] == 48)) {
                if(params.count() > 2 && params[1] == 5 &&
840 841
                   params[2] >= 0 && params[2] <= 255) {
                    if(params[0] == 38)
842 843 844 845 846 847 848 849
                        iTermAttribs.currentFgColor = params[2];
                    else
                        iTermAttribs.currentBgColor = params[2];
                }
                // TODO: 2;r;g;b for 24-bit colour support (Konsole etc)
                break;
            }

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
            if(params.contains(0)) {
                iTermAttribs.currentFgColor = defaultFgColor;
                iTermAttribs.currentBgColor = defaultBgColor;
                iTermAttribs.currentAttrib = attribNone;
            }
            if(params.contains(1))
                iTermAttribs.currentAttrib |= attribBold;
            if(params.contains(4))
                iTermAttribs.currentAttrib |= attribUnderline;
            if(params.contains(7))
                iTermAttribs.currentAttrib |= attribNegative;

            if(params.contains(22))
                iTermAttribs.currentAttrib &= ~attribBold;
            if(params.contains(24))
                iTermAttribs.currentAttrib &= ~attribUnderline;
            if(params.contains(27))
                iTermAttribs.currentAttrib &= ~attribNegative;

            foreach(int p, params) {
                if(p >= 30 && p<= 37) {
                    iTermAttribs.currentFgColor = p-30;
                }
                if(p >= 40 && p<= 47) {
                    iTermAttribs.currentBgColor = p-40;
                }
            }
877

878 879 880 881 882 883 884 885 886 887
            // high-intensity regular-weight extension (nonstandard)
            foreach(int p, params) {
                if(p >= 90 && p<= 97) {
                    iTermAttribs.currentFgColor = p-90+8;
                }
                if(p >= 100 && p<= 107) {
                    iTermAttribs.currentBgColor = p-100+8;
                }
            }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
            if(params.contains(39))
                iTermAttribs.currentFgColor = defaultFgColor;
            if(params.contains(49))
                iTermAttribs.currentBgColor = defaultBgColor;
        } else {
            iTermAttribs.currentFgColor = defaultFgColor;
            iTermAttribs.currentBgColor = defaultBgColor;
            iTermAttribs.currentAttrib = attribNone;
        }
        break;

    case 'h':
        if(params.count()>=1 && params.contains(1) && extra=="?") { // application cursor keys
            iAppCursorKeys = true;
        }
        else if(params.count()>=1 && params.contains(3) && extra=="?") { //column mode
            // not supported, just clear screen, move cursor home & reset scrolling region
            clearAll();
            resetTabs();
            iMarginTop = 1;
            iMarginBottom = iTermSize.height();
        }
        else if(params.count()>=1 && params.contains(6) && extra=="?") { //origin mode enable
            iTermAttribs.originMode = true;
        }
        else if(params.count()>=1 && params.contains(7) && extra=="?") { //wraparound mode enable
            iTermAttribs.wrapAroundMode = true;
        }
        else if(params.count()>=1 && params.contains(12) && extra=="?") { // start blinking cursor
            // just ignore, we don't blink
        }
        else if(params.count()>=1 && params.contains(25) && extra=="?") { // show cursor
            iShowCursor = true;
        }
        else if(params.count()>=1 && params.contains(1049) && extra=="?") { //use alt screen buffer & save cursor
            iTermAttribs_saved_alt = iTermAttribs;
            iUseAltScreenBuffer = true;
            iMarginTop = 1;
            iMarginBottom = iTermSize.height();
            resetBackBufferScrollPos();

            clearAll();
            resetTabs();
            emit displayBufferChanged();
        }
        else if(params.count()>=1 && params.contains(4) && extra=="") {
            iReplaceMode = true;
        }
        else if(params.count()>=1 && params.contains(20) && extra=="") {
            iNewLineMode = true;
        }
        else unhandled=true;
        break;

    case 'l':
        if(params.count()>=1 && params.contains(1) && extra=="?") { // normal cursor keys
            iAppCursorKeys = false;
        }
        else if(params.count()>=1 && params.contains(3) && extra=="?") { //column mode
            // not supported, just clear screen, move cursor home & reset scrolling region
            clearAll();
            resetTabs();
            iMarginTop = 1;
            iMarginBottom = iTermSize.height();
        }
        else if(params.count()>=1 && params.contains(6) && extra=="?") { //origin mode disable
            iTermAttribs.originMode = false;
        }
        else if(params.count()>=1 && params.contains(7) && extra=="?") { //wraparound mode disable
            iTermAttribs.wrapAroundMode = false;
        }
        else if(params.count()>=1 && params.contains(12) && extra=="?") { // stop blinking cursor
            // no need to do anything, we don't blink
        }
        else if(params.count()>=1 && params.contains(25) && extra=="?") { // hide cursor
            iShowCursor = false;
        }
        else if(params.count()>=1 && params.contains(1049) && extra=="?") { //return from alt screen buffer & restore cursor
            iUseAltScreenBuffer = false;
            iTermAttribs = iTermAttribs_saved_alt;
            iMarginBottom = iTermSize.height();
            iMarginTop = 1;
            resetBackBufferScrollPos();
            resetTabs();
            emit displayBufferChanged();
        }

        else if(params.count()>=1 && params.contains(4) && extra=="") {
            iReplaceMode = false;
        }
        else if(params.count()>=1 && params.contains(20) && extra=="") {
            iNewLineMode = false;
        }
        else unhandled=true;
        break;

    case 'r':  // scrolling region
        if(!extra.isEmpty()) {
            unhandled=true;
            break;
        }
        if(params.count() < 2) {
            while(params.count() < 2)
                params.append(1);
            params[0] = 1;
            params[1] = iTermSize.height();
        }
        if(params.at(0) < 1)
            params[0] = 1;
        if(params.at(1) > iTermSize.height())
            params[1] = iTermSize.height();
        iMarginTop = params.at(0);
        iMarginBottom = params.at(1);
        if(iMarginTop >= iMarginBottom) {
            //invalid scroll region
            if(iMarginTop == iTermSize.height()) {
                iMarginTop = iMarginBottom - 1;
            } else {
                iMarginBottom = iMarginTop + 1;
            }
        }
        setCursorPos(QPoint( 1, iMarginTop ));
        break;

    default:
        unhandled=true;
        break;
    }

    if (unhandled)
        qDebug() << "unhandled ansi sequence " << cmdChar << params << extra;
}

void Terminal::oscSequence(const QString& seq)
{
    if(seq.length() <= 1 || seq.at(0)!=']')
        return;

    // set window title
    if( seq.length() >= 3 && seq.at(0)==']' &&
        (seq.at(1)=='0' || seq.at(1)=='2') &&
        seq.at(2)==';' )
    {
        if(iWindow) {
            iUtil->setWindowTitle(seq.mid(3));
        }
        return;
    }

    qDebug() << "unhandled OSC" << seq;
}

void Terminal::escControlChar(const QString& seq)
{
    QChar ch;

    if(seq.length()==1) {
        ch = seq.at(0);
    } else if (seq.length()>1 ){ // control sequences longer than 1 characters
        if( seq.at(0) == '(' || seq.at(0)==')' ) // character set, ignore this for now...
            return;
        if( seq.at(0) == '#' && seq.at(1)=='8' ) { // test mode, fill screen with 'E'
            clearAll(true);
            for(int i=0; i<termSize().height(); i++) {
                QList<TermChar> line;
                for(int j=0; j<termSize().width(); j++) {
                    TermChar c = zeroChar;
                    c.c = 'E';
                    line.append(c);
                }
                buffer().append(line);
            }
            return;
        }
    }

Aard's avatar
Aard committed
1064
    if(ch.toLatin1()=='7') { //save cursor
1065 1066
        iTermAttribs_saved = iTermAttribs;
    }
Aard's avatar
Aard committed
1067
    else if(ch.toLatin1()=='8') { //restore cursor
1068 1069
        iTermAttribs = iTermAttribs_saved;
    }
Aard's avatar
Aard committed
1070
    else if(ch.toLatin1()=='>' || ch.toLatin1()=='=') { //app keypad/normal keypad - ignore these for now...
1071 1072
    }

Aard's avatar
Aard committed
1073
    else if(ch.toLatin1()=='H') {  // set a tab stop at cursor position
1074 1075 1076 1077 1078 1079
        while(iTabStops.size() < cursorPos().y())
            iTabStops.append(QList<int>());

        iTabStops[cursorPos().y()-1].append(cursorPos().x());
        qSort(iTabStops[cursorPos().y()-1]);
    }
Aard's avatar
Aard committed
1080
    else if(ch.toLatin1()=='D') {  // cursor down/scroll down one line
1081 1082
        scrollFwd(1, cursorPos().y());
    }
Aard's avatar
Aard committed
1083
    else if(ch.toLatin1()=='M') {  // cursor up/scroll up one line
1084 1085 1086
        scrollBack(1, cursorPos().y());
    }

Aard's avatar
Aard committed
1087
    else if(ch.toLatin1()=='E') {  // new line
1088 1089 1090 1091 1092 1093 1094
        if(cursorPos().y()==iMarginBottom) {
            scrollFwd(1);
            setCursorPos(QPoint(1,cursorPos().y()));
        } else {
            setCursorPos(QPoint(1,cursorPos().y()+1));
        }
    }
Aard's avatar
Aard committed
1095
    else if(ch.toLatin1()=='c') {  // full reset
1096 1097
        resetTerminal();
    }
Aard's avatar
Aard committed
1098
    else if(ch.toLatin1()=='g') {  // visual bell
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        iUtil->bellAlert();
    }
    else {
        qDebug() << "unhandled escape code ESC" << seq;
    }
}

QList<TermChar>& Terminal::currentLine()
{
    while(buffer().size() <= cursorPos().y()-1)
        buffer().append(QList<TermChar>());

    if( cursorPos().y() >= 1 &&
            cursorPos().y() <= buffer().size() )
    {
        return buffer()[cursorPos().y()-1];
    }

    // we shouldn't get here
    return buffer()[buffer().size()-1];
}

const QStringList Terminal::printableLinesFromCursor(int lines)
{
    QStringList ret;

    int start = cursorPos().y() - lines;
    int end = cursorPos().y() + lines;

    for(int l=start-1; l<end; l++) {
        ret.append("");
        if(l >= 0 && l < buffer().size()) {
            for(int i=0; i<buffer()[l].size(); i++) {
                if(buffer()[l][i].c.isPrint())
                    ret[ret.size()-1].append(buffer()[l][i].c);
            }
        }
    }

    return ret;
}

void Terminal::trimBackBuffer()
{
    while(backBuffer().size() > maxScrollBackLines) {
        backBuffer().removeFirst();
    }
}

void Terminal::scrollBack(int lines, int insertAt)
{
    if(lines <= 0)
        return;

    adjustSelectionPosition(lines);

    bool useBackbuffer = true;
    if(insertAt==-1) {
        insertAt = iMarginTop;
        useBackbuffer = false;
    }
    insertAt--;

    while(lines>0) {
        if(!iUseAltScreenBuffer) {
            if(iBackBuffer.size()>0 && useBackbuffer)
                buffer().insert(insertAt, iBackBuffer.takeLast());
            else
                buffer().insert(insertAt, QList<TermChar>());
        } else {
            buffer().insert(insertAt, QList<TermChar>());
        }

        int rm = iMarginBottom;
        if(rm >= buffer().size())
            rm = buffer().size()-1;

        buffer().removeAt(rm);

        lines--;
    }
}

void Terminal::scrollFwd(int lines, int removeAt)
{
    if(lines <= 0)
        return;

    adjustSelectionPosition(-lines);

    if(removeAt==-1) {
        removeAt = iMarginTop;
    }
    removeAt--;

    while(buffer().size() < iMarginBottom)
        buffer().append(QList<TermChar>());

    while(lines>0) {
        buffer().insert(iMarginBottom, QList<TermChar>());

        if(!iUseAltScreenBuffer)
            iBackBuffer.append( buffer().takeAt(removeAt) );
        else
            buffer().removeAt(removeAt);

        lines--;
    }
    trimBackBuffer();
}

void Terminal::resetTerminal()
{
    iBuffer.clear();
    iAltBuffer.clear();
    iBackBuffer.clear();

    iTermAttribs.currentFgColor = defaultFgColor;
    iTermAttribs.currentBgColor = defaultBgColor;
    iTermAttribs.currentAttrib = 0;
    iTermAttribs.cursorPos = QPoint(1,1);
    iTermAttribs.wrapAroundMode = true;
    iTermAttribs.originMode = false;

    iTermAttribs_saved = iTermAttribs;
    iTermAttribs_saved_alt = iTermAttribs;

    iMarginBottom = iTermSize.height();
    iMarginTop = 1;

    iShowCursor = true;
    iUseAltScreenBuffer = false;
    iAppCursorKeys = false;
    iReplaceMode = false;
    iNewLineMode = false;

    resetBackBufferScrollPos();

    resetTabs();
    clearSelection();
}

void Terminal::resetTabs()
{
    iTabStops.clear();
    for(int i=0; i<iTermSize.height(); i++) {
        int tab=1;
        iTabStops.append(QList<int>());
        while(tab <= iTermSize.width()) {
            iTabStops.last().append(tab);
            tab += 8;
        }
    }
}

void Terminal::pasteFromClipboard()
{
John Brooks's avatar
John Brooks committed
1256
    QClipboard *cb = QGuiApplication::clipboard();
1257

coderus's avatar
coderus committed
1258 1259 1260
    if(iPtyIFace && !cb->text().isEmpty()) {
        resetBackBufferScrollPos();
        iPtyIFace->writeTerm(cb->text());
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    }
}

const QStringList Terminal::grabURLsFromBuffer()
{
    QStringList ret;
    QByteArray buf;

    //backbuffer
    if ((iUtil->settingsValue("general/grabUrlsFromBackbuffer").toBool()
         && !iUseAltScreenBuffer)
        || backBufferScrollPos() > 0)  //a lazy workaround: just grab everything when the buffer is being scrolled (TODO: make a proper fix)
    {
        for (int i=0; i<iBackBuffer.size(); i++) {
            for (int j=0; j<iBackBuffer[i].size(); j++) {
                if (iBackBuffer[i][j].c.isPrint())
                    buf.append(iBackBuffer[i][j].c);
                else if (iBackBuffer[i][j].c == 0)
                    buf.append(' ');
            }
            if (iBackBuffer[i].size() < iTermSize.width())
                buf.append(' ');
        }
    }

    //main buffer
    for (int i=0; i<buffer().size(); i++) {
        for (int j=0; j<buffer()[i].size(); j++) {
            if (buffer()[i][j].c.isPrint())
                buf.append(buffer()[i][j].c);
            else if (buffer()[i][j].c == 0)
                buf.append(' ');
        }
        if (buffer()[i].size() < iTermSize.width())
            buf.append(' ');
    }

    QStringList lookFor;
    lookFor.append("http://");
    lookFor.append("https://");

    foreach(QString prot, lookFor) {
        int ind=0;
        while( ind != -1 ) {
            ind = buf.indexOf(prot, ind);
            if(ind!=-1) {
                int ind2 = buf.indexOf(" ",ind);
                int l=-1;
                if(ind2!=-1)
                    l = ind2-ind;
                ret << buf.mid(ind,l); // the URL
                ind += prot.length();
            }
        }
    }
    ret.removeDuplicates();
    return ret;
}

QString Terminal::getUserMenuXml()
{
    if(!iUtil)
        return QString();

    QString ret;
    QFile f( iUtil->configPath()+"/menu.xml" );
    if(f.open(QIODevice::ReadOnly|QIODevice::Text)) {
        ret = f.readAll();
        f.close();
    }

    return ret;
}

void Terminal::scrollBackBufferFwd(int lines)
{
    if(iUseAltScreenBuffer || lines<=0)
        return;

    clearSelection();

    iBackBufferScrollPos -= lines;
    if(iBackBufferScrollPos < 0)
        iBackBufferScrollPos = 0;

    if (iRenderer) {
        iRenderer->setShowBufferScrollIndicator(iBackBufferScrollPos != 0);
        iRenderer->redraw();
    }
}

void Terminal::scrollBackBufferBack(int lines)
{
    if (iUseAltScreenBuffer || lines<=0)
        return;

    clearSelection();

    iBackBufferScrollPos += lines;
    if (iBackBufferScrollPos > iBackBuffer.size())
        iBackBufferScrollPos = iBackBuffer.size();

    if (iRenderer) {
        iRenderer->setShowBufferScrollIndicator(iBackBufferScrollPos != 0);
        iRenderer->redraw();
    }
}

void Terminal::resetBackBufferScrollPos()
{
    if(iBackBufferScrollPos==0 && iSelection.isNull())
        return;

    iBackBufferScrollPos = 0;
    clearSelection();

    if (iRenderer) {
        iRenderer->setShowBufferScrollIndicator(false);
        iRenderer->redraw();
    }
}

void Terminal::copySelectionToClipboard()
{
    if (selection().isNull())
        return;

John Brooks's avatar
John Brooks committed
1388
    QClipboard *cb = QGuiApplication::clipboard();
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    cb->clear();

    QString text;
    QString line;

    // backbuffer
    if (iBackBufferScrollPos > 0 && !iUseAltScreenBuffer) {
        int lineFrom = iBackBuffer.size() - iBackBufferScrollPos + selection().top() - 1;
        int lineTo = iBackBuffer.size() - iBackBufferScrollPos + selection().bottom() - 1;

        for (int i=lineFrom; i<=lineTo; i++) {
            if (i >= 0 && i < iBackBuffer.size()) {
                line.clear();
                int start = 0;
                int end = iBackBuffer[i].size()-1;
coderus's avatar
coderus committed
1404
                if (i==lineFrom) {
1405
                    start = selection().left()-1;
coderus's avatar
coderus committed
1406 1407
                }
                if (i==lineTo) {
1408
                    end = selection().right()-1;
coderus's avatar
coderus committed
1409
                }
1410 1411 1412
                for (int j=start; j<=end; j++) {
                    if (j >= 0 && j < iBackBuffer[i].size() && iBackBuffer[i][j].c.isPrint())
                        line += iBackBuffer[i][j].c;
1413
                }
1414
                text += line.trimmed() + "\n";
1415 1416
            }
        }
1417
    }
1418

1419 1420 1421 1422 1423 1424 1425 1426
    // main buffer
    int lineFrom = selection().top()-1-iBackBufferScrollPos;
    int lineTo = selection().bottom()-1-iBackBufferScrollPos;
    for (int i=lineFrom; i<=lineTo; i++) {
        if (i >= 0 && i < buffer().size()) {
            line.clear();
            int start = 0;
            int end = buffer()[i].size()-1;
coderus's avatar
coderus committed
1427
            if (i==lineFrom) {
1428
                start = selection().left()-1;
coderus's avatar
coderus committed
1429 1430
            }
            if (i==lineTo) {
1431
                end = selection().right()-1;
coderus's avatar
coderus committed
1432
            }
1433 1434 1435
            for (int j=start; j<=end; j++) {
                if (j >= 0 && j < buffer()[i].size() && buffer()[i][j].c.isPrint())
                    line += buffer()[i][j].c;
1436
            }
1437
            text += line.trimmed() + "\n";
1438
        }
1439
    }
1440

1441
    //qDebug() << text.trimmed();
1442

1443
    cb->setText(text.trimmed());
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
}

void Terminal::adjustSelectionPosition(int lines)
{
    // adjust selection position when terminal contents move

    if (iSelection.isNull() || lines==0)
        return;

    int tx = iSelection.left();
    int ty = iSelection.top() + lines;
    int bx = iSelection.right();
    int by = iSelection.bottom() + lines;

    if (ty<1) {
        ty = 1;
        tx = 1;
    }
    if (by>iTermSize.height()) {
        by = iTermSize.height();
        bx = iTermSize.width();
    }
    if (by<1 || ty>iTermSize.height()) {
        clearSelection();
        return;
    }

    iSelection = QRect(QPoint(tx,ty), QPoint(bx,by));

    if (iRenderer)
        iRenderer->redraw();
}

void Terminal::setSelection(QPoint start, QPoint end)
{
    if (start.y() > end.y())
        qSwap(start, end);
    if (start.y() == end.y() && start.x() > end.x())
        qSwap(start, end);

    if (start.x() < 1)
        start.rx() = 1;
    if (start.y() < 1)
        start.ry() = 1;
    if (end.x() > iTermSize.width())
        end.rx() = iTermSize.width();
    if (end.y() > iTermSize.height())
        end.ry() = iTermSize.height();

    iSelection = QRect(start, end);

    if (iRenderer)
        iRenderer->redraw();
}

void Terminal::clearSelection()
{
    if (iSelection.isNull())
        return;

    iSelection = QRect();

    if (iUtil)
        iUtil->selectionFinished();
    if (iRenderer)
        iRenderer->redraw();
}

QRect Terminal::selection()
{
    return iSelection;
}