difftextwindow.cpp 67.8 KB
Newer Older
Joachim Eibl's avatar
Joachim Eibl committed
1 2 3 4
/***************************************************************************
                          difftextwindow.cpp  -  description
                             -------------------
    begin                : Mon Apr 8 2002
Joachim Eibl's avatar
Joachim Eibl committed
5
    copyright            : (C) 2002-2007 by Joachim Eibl
Joachim Eibl's avatar
Joachim Eibl committed
6
    email                : joachim.eibl at gmx.de
Joachim Eibl's avatar
Joachim Eibl committed
7 8 9 10 11 12 13 14 15 16 17
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

Joachim Eibl's avatar
Joachim Eibl committed
18
#include "difftextwindow.h"
Michael Reeves's avatar
Michael Reeves committed
19
#include "kdiff3.h"
Joachim Eibl's avatar
Joachim Eibl committed
20
#include "merger.h"
21
#include "options.h"
Joachim Eibl's avatar
Joachim Eibl committed
22 23

#include <QApplication>
24 25 26
#include <QDir>
#include <QDragEnterEvent>
#include <QFileDialog>
Joachim Eibl's avatar
Joachim Eibl committed
27 28
#include <QLabel>
#include <QLayout>
29
#include <QLineEdit>
30
#include <QMenu>
31 32
#include <QMimeData>
#include <QPushButton>
Michael Reeves's avatar
Michael Reeves committed
33
#include <QRunnable>
34 35 36
#include <QStatusBar>
#include <QTextCodec>
#include <QTextLayout>
Michael Reeves's avatar
Michael Reeves committed
37
#include <QThreadPool>
38 39 40
#include <QToolTip>
#include <QUrl>
#include <qnamespace.h>
Joachim Eibl's avatar
Joachim Eibl committed
41

42
#include <KLocalizedString>
Joachim Eibl's avatar
Joachim Eibl committed
43

44
#include <assert.h>
Joachim Eibl's avatar
Joachim Eibl committed
45 46
#include <cmath>
#include <cstdlib>
Michael Reeves's avatar
Michael Reeves committed
47 48

static QAtomicInt s_runnableCount = 0;
Joachim Eibl's avatar
Joachim Eibl committed
49

50 51
class DiffTextWindowData
{
52
  public:
Michael Reeves's avatar
Michael Reeves committed
53
    explicit DiffTextWindowData(DiffTextWindow* p)
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
    {
        m_pDiffTextWindow = p;
        m_bPaintingAllowed = false;
        m_pLineData = 0;
        m_size = 0;
        m_bWordWrap = false;
        m_delayedDrawTimer = 0;
        m_pDiff3LineVector = 0;
        m_pManualDiffHelpList = 0;
        m_pOptions = 0;
        m_fastSelectorLine1 = 0;
        m_fastSelectorNofLines = 0;
        m_bTriple = 0;
        m_winIdx = 0;
        m_firstLine = 0;
        m_oldFirstLine = 0;
        m_horizScrollOffset = 0;
        m_lineNumberWidth = 0;
        m_maxTextWidth = -1;
        m_pStatusBar = 0;
        m_scrollDeltaX = 0;
        m_scrollDeltaY = 0;
        m_bMyUpdate = false;
        m_bSelectionInProgress = false;
        m_pTextCodec = 0;
#if defined(_WIN32) || defined(Q_OS_OS2)
        m_eLineEndStyle = eLineEndStyleDos;
#else
        m_eLineEndStyle = eLineEndStyleUnix;
#endif
    }
    DiffTextWindow* m_pDiffTextWindow;
Michael Reeves's avatar
Michael Reeves committed
86
    DiffTextWindowFrame* m_pDiffTextWindowFrame = NULL;
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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    QTextCodec* m_pTextCodec;
    e_LineEndStyle m_eLineEndStyle;

    bool m_bPaintingAllowed;
    const LineData* m_pLineData;
    int m_size;
    QString m_filename;
    bool m_bWordWrap;
    int m_delayedDrawTimer;

    const Diff3LineVector* m_pDiff3LineVector;
    Diff3WrapLineVector m_diff3WrapLineVector;
    const ManualDiffHelpList* m_pManualDiffHelpList;

    class WrapLineCacheData
    {
      public:
        WrapLineCacheData() : m_d3LineIdx(0), m_textStart(0), m_textLength(0) {}
        WrapLineCacheData(int d3LineIdx, int textStart, int textLength)
            : m_d3LineIdx(d3LineIdx), m_textStart(textStart), m_textLength(textLength) {}
        int m_d3LineIdx;
        int m_textStart;
        int m_textLength;
    };
    QList<QVector<WrapLineCacheData>> m_wrapLineCacheList;

    Options* m_pOptions;
    QColor m_cThis;
    QColor m_cDiff1;
    QColor m_cDiff2;
    QColor m_cDiffBoth;

    int m_fastSelectorLine1;
    int m_fastSelectorNofLines;

    bool m_bTriple;
    int m_winIdx;
    int m_firstLine;
    int m_oldFirstLine;
    int m_horizScrollOffset;
    int m_lineNumberWidth;
    QAtomicInt m_maxTextWidth;

    void getLineInfo(
        const Diff3Line& d,
        int& lineIdx,
        DiffList*& pFineDiff1, DiffList*& pFineDiff2, // return values
        int& changed, int& changed2);

    QString getString(int d3lIdx);
    QString getLineString(int line);

    void writeLine(
        MyPainter& p, const LineData* pld,
        const DiffList* pLineDiff1, const DiffList* pLineDiff2, int line,
        int whatChanged, int whatChanged2, int srcLineIdx,
        int wrapLineOffset, int wrapLineLength, bool bWrapLine, const QRect& invalidRect, int deviceWidth);

    void draw(MyPainter& p, const QRect& invalidRect, int deviceWidth, int beginLine, int endLine);

    QStatusBar* m_pStatusBar;

    Selection m_selection;

    int m_scrollDeltaX;
    int m_scrollDeltaY;

    bool m_bMyUpdate;
    void myUpdate(int afterMilliSecs);

    int leftInfoWidth() { return 4 + m_lineNumberWidth; } // Nr of information columns on left side
    int convertLineOnScreenToLineInSource(int lineOnScreen, e_CoordType coordType, bool bFirstLine);

    bool m_bSelectionInProgress;
    QPoint m_lastKnownMousePos;
    void prepareTextLayout(QTextLayout& textLayout, bool bFirstLine, int visibleTextWidth = -1);
Joachim Eibl's avatar
Joachim Eibl committed
163
};
Joachim Eibl's avatar
Joachim Eibl committed
164 165

DiffTextWindow::DiffTextWindow(
166 167 168 169 170
    DiffTextWindowFrame* pParent,
    QStatusBar* pStatusBar,
    Options* pOptions,
    int winIdx)
    : QWidget(pParent)
171
{
172 173 174
    setObjectName(QString("DiffTextWindow%1").arg(winIdx));
    setAttribute(Qt::WA_OpaquePaintEvent);
    //setAttribute( Qt::WA_PaintOnScreen );
Joachim Eibl's avatar
Joachim Eibl committed
175

176 177 178 179
    d = new DiffTextWindowData(this);
    d->m_pDiffTextWindowFrame = pParent;
    setFocusPolicy(Qt::ClickFocus);
    setAcceptDrops(true);
Joachim Eibl's avatar
Joachim Eibl committed
180

181 182
    d->m_pOptions = pOptions;
    init(0, 0, d->m_eLineEndStyle, 0, 0, 0, 0, false);
Joachim Eibl's avatar
Joachim Eibl committed
183

184
    setMinimumSize(QSize(20, 20));
Joachim Eibl's avatar
Joachim Eibl committed
185

186 187 188 189
    d->m_pStatusBar = pStatusBar;
    d->m_bPaintingAllowed = true;
    d->m_bWordWrap = false;
    d->m_winIdx = winIdx;
190

191
    setFont(d->m_pOptions->m_font);
Joachim Eibl's avatar
Joachim Eibl committed
192 193
}

194 195
DiffTextWindow::~DiffTextWindow()
{
196
    delete d;
Joachim Eibl's avatar
Joachim Eibl committed
197
}
Joachim Eibl's avatar
Joachim Eibl committed
198 199

void DiffTextWindow::init(
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
    const QString& filename,
    QTextCodec* pTextCodec,
    e_LineEndStyle eLineEndStyle,
    const LineData* pLineData,
    int size,
    const Diff3LineVector* pDiff3LineVector,
    const ManualDiffHelpList* pManualDiffHelpList,
    bool bTriple)
{
    d->m_filename = filename;
    d->m_pLineData = pLineData;
    d->m_size = size;
    d->m_pDiff3LineVector = pDiff3LineVector;
    d->m_diff3WrapLineVector.clear();
    d->m_pManualDiffHelpList = pManualDiffHelpList;

    d->m_firstLine = 0;
    d->m_oldFirstLine = -1;
    d->m_horizScrollOffset = 0;
    d->m_bTriple = bTriple;
    d->m_scrollDeltaX = 0;
    d->m_scrollDeltaY = 0;
    d->m_bMyUpdate = false;
    d->m_fastSelectorLine1 = 0;
    d->m_fastSelectorNofLines = 0;
    d->m_lineNumberWidth = 0;
    d->m_maxTextWidth = -1;
    d->m_selection.reset();
    d->m_selection.oldFirstLine = -1; // reset is not enough here.
    d->m_selection.oldLastLine = -1;
    d->m_selection.lastLine = -1;

    d->m_pTextCodec = pTextCodec;
    d->m_eLineEndStyle = eLineEndStyle;

    update();
    d->m_pDiffTextWindowFrame->init();
237 238 239 240
}

void DiffTextWindow::reset()
{
241 242 243 244 245
    d->m_pLineData = 0;
    d->m_size = 0;
    d->m_pDiff3LineVector = 0;
    d->m_filename = "";
    d->m_diff3WrapLineVector.clear();
246 247
}

248
void DiffTextWindow::setPaintingAllowed(bool bAllowPainting)
249
{
250 251 252 253 254 255 256 257
    if(d->m_bPaintingAllowed != bAllowPainting)
    {
        d->m_bPaintingAllowed = bAllowPainting;
        if(d->m_bPaintingAllowed)
            update();
        else
            reset();
    }
258 259
}

260
void DiffTextWindow::dragEnterEvent(QDragEnterEvent* e)
261
{
262 263
    e->setAccepted(e->mimeData()->hasUrls() || e->mimeData()->hasText());
    // Note that the corresponding drop is handled in KDiff3App::eventFilter().
264 265 266 267
}

void DiffTextWindow::setFirstLine(int firstLine)
{
268
    int fontHeight = fontMetrics().lineSpacing();
269

270
    int newFirstLine = max2(0, firstLine);
271

272
    int deltaY = fontHeight * (d->m_firstLine - newFirstLine);
273

274
    d->m_firstLine = newFirstLine;
275

276 277 278 279 280 281 282 283 284 285 286 287
    if(d->m_bSelectionInProgress && d->m_selection.firstLine != -1)
    {
        int line, pos;
        convertToLinePos(d->m_lastKnownMousePos.x(), d->m_lastKnownMousePos.y(), line, pos);
        d->m_selection.end(line, pos);
        update();
    }
    else
    {
        QWidget::scroll(0, deltaY);
    }
    d->m_pDiffTextWindowFrame->setFirstLine(d->m_firstLine);
288 289 290 291
}

int DiffTextWindow::getFirstLine()
{
292
    return d->m_firstLine;
293 294 295 296
}

void DiffTextWindow::setHorizScrollOffset(int horizScrollOffset)
{
297 298
    int fontWidth = fontMetrics().width('0');
    int xOffset = d->leftInfoWidth() * fontWidth;
299

300
    int deltaX = d->m_horizScrollOffset - qMax(0, horizScrollOffset);
301

302
    d->m_horizScrollOffset = qMax(0, horizScrollOffset);
303

304
    QRect r(xOffset, 0, width() - xOffset, height());
305

306 307 308 309 310
    if(d->m_pOptions->m_bRightToLeftLanguage)
    {
        deltaX = -deltaX;
        r = QRect(width() - xOffset - 2, 0, -(width() - xOffset), height()).normalized();
    }
311

312 313 314 315 316 317 318 319 320 321 322
    if(d->m_bSelectionInProgress && d->m_selection.firstLine != -1)
    {
        int line, pos;
        convertToLinePos(d->m_lastKnownMousePos.x(), d->m_lastKnownMousePos.y(), line, pos);
        d->m_selection.end(line, pos);
        update();
    }
    else
    {
        QWidget::scroll(deltaX, 0, r);
    }
323 324 325 326
}

int DiffTextWindow::getMaxTextWidth()
{
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    if(d->m_bWordWrap)
    {
        return getVisibleTextAreaWidth();
    }
    else if(getAtomic(d->m_maxTextWidth) < 0)
    {
        d->m_maxTextWidth = 0;
        QTextLayout textLayout(QString(), font(), this);
        for(int i = 0; i < d->m_size; ++i)
        {
            textLayout.clearLayout();
            textLayout.setText(d->getString(i));
            d->prepareTextLayout(textLayout, true);
            if(textLayout.maximumWidth() > getAtomic(d->m_maxTextWidth))
                d->m_maxTextWidth = textLayout.maximumWidth();
        }
    }
    return getAtomic(d->m_maxTextWidth);
Michael Reeves's avatar
Michael Reeves committed
345 346
}

347 348
int DiffTextWindow::getNofLines()
{
349
    return d->m_bWordWrap ? d->m_diff3WrapLineVector.size() : d->m_pDiff3LineVector->size();
Michael Reeves's avatar
Michael Reeves committed
350 351
}

352
int DiffTextWindow::convertLineToDiff3LineIdx(int line)
353
{
354 355 356 357
    if(line >= 0 && d->m_bWordWrap && d->m_diff3WrapLineVector.size() > 0)
        return d->m_diff3WrapLineVector[min2(line, (int)d->m_diff3WrapLineVector.size() - 1)].diff3LineIndex;
    else
        return line;
Michael Reeves's avatar
Michael Reeves committed
358 359
}

360
int DiffTextWindow::convertDiff3LineIdxToLine(int d3lIdx)
361
{
362 363 364 365
    if(d->m_bWordWrap && d->m_pDiff3LineVector != 0 && d->m_pDiff3LineVector->size() > 0)
        return (*d->m_pDiff3LineVector)[min2(d3lIdx, (int)d->m_pDiff3LineVector->size() - 1)]->sumLinesNeededForDisplay;
    else
        return d3lIdx;
Joachim Eibl's avatar
Joachim Eibl committed
366 367 368 369 370 371
}

/** Returns a line number where the linerange [line, line+nofLines] can
    be displayed best. If it fits into the currently visible range then
    the returned value is the current firstLine.
*/
372
int getBestFirstLine(int line, int nofLines, int firstLine, int visibleLines)
373
{
374 375 376 377 378 379 380 381
    int newFirstLine = firstLine;
    if(line < firstLine || line + nofLines + 2 > firstLine + visibleLines)
    {
        if(nofLines > visibleLines || nofLines <= (2 * visibleLines / 3 - 1))
            newFirstLine = line - visibleLines / 3;
        else
            newFirstLine = line - (visibleLines - nofLines);
    }
382

383
    return newFirstLine;
384 385
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
void DiffTextWindow::setFastSelectorRange(int line1, int nofLines)
{
    d->m_fastSelectorLine1 = line1;
    d->m_fastSelectorNofLines = nofLines;
    if(isVisible())
    {
        int newFirstLine = getBestFirstLine(
            convertDiff3LineIdxToLine(d->m_fastSelectorLine1),
            convertDiff3LineIdxToLine(d->m_fastSelectorLine1 + d->m_fastSelectorNofLines) - convertDiff3LineIdxToLine(d->m_fastSelectorLine1),
            d->m_firstLine,
            getNofVisibleLines());
        if(newFirstLine != d->m_firstLine)
        {
            scroll(0, newFirstLine - d->m_firstLine);
        }

        update();
    }
}
405

406
void DiffTextWindow::showStatusLine(int line)
407
{
408 409 410 411 412 413 414 415 416 417 418 419 420 421
    int d3lIdx = convertLineToDiff3LineIdx(line);
    if(d->m_pDiff3LineVector != 0 && d3lIdx >= 0 && d3lIdx < (int)d->m_pDiff3LineVector->size())
    {
        const Diff3Line* pD3l = (*d->m_pDiff3LineVector)[d3lIdx];
        if(pD3l != 0)
        {
            int l = pD3l->getLineInFile(d->m_winIdx);

            QString s = i18n("File") + " " + d->m_filename;
            if(l != -1)
                s += ": " + i18n("Line") + " " + QString::number(l + 1);
            else
                s += ": " + i18n("Line not available");
            if(d->m_pStatusBar != 0) d->m_pStatusBar->showMessage(s);
422

423 424 425
            emit lineClicked(d->m_winIdx, l);
        }
    }
426 427
}

428 429 430 431 432
void DiffTextWindow::focusInEvent(QFocusEvent* e)
{
    emit gotFocus();
    QWidget::focusInEvent(e);
}
433

434
void DiffTextWindow::mousePressEvent(QMouseEvent* e)
435
{
436 437 438 439 440
    if(e->button() == Qt::LeftButton)
    {
        int line;
        int pos;
        convertToLinePos(e->x(), e->y(), line, pos);
441

442 443
        int fontWidth = fontMetrics().width('0');
        int xOffset = d->leftInfoWidth() * fontWidth;
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        if((!d->m_pOptions->m_bRightToLeftLanguage && e->x() < xOffset) || (d->m_pOptions->m_bRightToLeftLanguage && e->x() > width() - xOffset))
        {
            emit setFastSelectorLine(convertLineToDiff3LineIdx(line));
            d->m_selection.firstLine = -1; // Disable current d->m_selection
        }
        else
        { // Selection
            resetSelection();
            d->m_selection.start(line, pos);
            d->m_selection.end(line, pos);
            d->m_bSelectionInProgress = true;
            d->m_lastKnownMousePos = e->pos();

            showStatusLine(line);
        }
    }
461 462
}

463
bool isCTokenChar(QChar c)
464
{
465 466 467
    return (c == '_') ||
           (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
           (c >= '0' && c <= '9');
468 469
}

470 471
/// Calculate where a token starts and ends, given the x-position on screen.
void calcTokenPos(const QString& s, int posOnScreen, int& pos1, int& pos2, int tabSize)
472
{
473 474 475 476 477 478 479 480
    // Cursor conversions that consider g_tabSize
    int pos = convertToPosInText(s, max2(0, posOnScreen), tabSize);
    if(pos >= (int)s.length())
    {
        pos1 = s.length();
        pos2 = s.length();
        return;
    }
481

482 483
    pos1 = pos;
    pos2 = pos + 1;
484

485 486 487 488 489
    if(isCTokenChar(s[pos1]))
    {
        while(pos1 >= 0 && isCTokenChar(s[pos1]))
            --pos1;
        ++pos1;
490

491 492 493
        while(pos2 < (int)s.length() && isCTokenChar(s[pos2]))
            ++pos2;
    }
494 495
}

496
void DiffTextWindow::mouseDoubleClickEvent(QMouseEvent* e)
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
    d->m_bSelectionInProgress = false;
    d->m_lastKnownMousePos = e->pos();
    if(e->button() == Qt::LeftButton)
    {
        int line;
        int pos;
        convertToLinePos(e->x(), e->y(), line, pos);

        // Get the string data of the current line
        QString s;
        if(d->m_bWordWrap)
        {
            if(line < 0 || line >= (int)d->m_diff3WrapLineVector.size())
                return;
            const Diff3WrapLine& d3wl = d->m_diff3WrapLineVector[line];
            s = d->getString(d3wl.diff3LineIndex).mid(d3wl.wrapLineOffset, d3wl.wrapLineLength);
        }
        else
        {
            if(line < 0 || line >= (int)d->m_pDiff3LineVector->size())
                return;
            s = d->getString(line);
        }

        if(!s.isEmpty())
        {
            int pos1, pos2;
            calcTokenPos(s, pos, pos1, pos2, d->m_pOptions->m_tabSize);

            resetSelection();
            d->m_selection.start(line, convertToPosOnScreen(s, pos1, d->m_pOptions->m_tabSize));
            d->m_selection.end(line, convertToPosOnScreen(s, pos2, d->m_pOptions->m_tabSize));
            update();
            // emit d->m_selectionEnd() happens in the mouseReleaseEvent.
            showStatusLine(line);
        }
    }
Joachim Eibl's avatar
Joachim Eibl committed
535 536
}

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
void DiffTextWindow::mouseReleaseEvent(QMouseEvent* e)
{
    d->m_bSelectionInProgress = false;
    d->m_lastKnownMousePos = e->pos();
    //if ( e->button() == LeftButton )
    {
        if(d->m_delayedDrawTimer)
            killTimer(d->m_delayedDrawTimer);
        d->m_delayedDrawTimer = 0;
        if(d->m_selection.firstLine != -1)
        {
            emit selectionEnd();
        }
    }
    d->m_scrollDeltaX = 0;
    d->m_scrollDeltaY = 0;
553 554
}

555 556 557 558 559 560 561 562 563 564 565 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
inline int sqr(int x) { return x * x; }

void DiffTextWindow::mouseMoveEvent(QMouseEvent* e)
{
    int line;
    int pos;
    convertToLinePos(e->x(), e->y(), line, pos);
    d->m_lastKnownMousePos = e->pos();

    if(d->m_selection.firstLine != -1)
    {
        d->m_selection.end(line, pos);

        showStatusLine(line);

        // Scroll because mouse moved out of the window
        const QFontMetrics& fm = fontMetrics();
        int fontWidth = fm.width('0');
        int deltaX = 0;
        int deltaY = 0;
        if(!d->m_pOptions->m_bRightToLeftLanguage)
        {
            if(e->x() < d->leftInfoWidth() * fontWidth) deltaX = -1 - abs(e->x() - d->leftInfoWidth() * fontWidth) / fontWidth;
            if(e->x() > width()) deltaX = +1 + abs(e->x() - width()) / fontWidth;
        }
        else
        {
            if(e->x() > width() - 1 - d->leftInfoWidth() * fontWidth) deltaX = +1 + abs(e->x() - (width() - 1 - d->leftInfoWidth() * fontWidth)) / fontWidth;
            if(e->x() < fontWidth) deltaX = -1 - abs(e->x() - fontWidth) / fontWidth;
        }
        if(e->y() < 0) deltaY = -1 - sqr(e->y()) / sqr(fm.lineSpacing());
        if(e->y() > height()) deltaY = +1 + sqr(e->y() - height()) / sqr(fm.lineSpacing());
        if((deltaX != 0 && d->m_scrollDeltaX != deltaX) || (deltaY != 0 && d->m_scrollDeltaY != deltaY))
        {
            d->m_scrollDeltaX = deltaX;
            d->m_scrollDeltaY = deltaY;
            emit scroll(deltaX, deltaY);
            if(d->m_delayedDrawTimer)
                killTimer(d->m_delayedDrawTimer);
            d->m_delayedDrawTimer = startTimer(50);
        }
        else
        {
            d->m_scrollDeltaX = deltaX;
            d->m_scrollDeltaY = deltaY;
            d->myUpdate(0);
        }
    }
}
604 605 606

void DiffTextWindowData::myUpdate(int afterMilliSecs)
{
607 608 609 610
    if(m_delayedDrawTimer)
        m_pDiffTextWindow->killTimer(m_delayedDrawTimer);
    m_bMyUpdate = true;
    m_delayedDrawTimer = m_pDiffTextWindow->startTimer(afterMilliSecs);
611 612 613 614
}

void DiffTextWindow::timerEvent(QTimerEvent*)
{
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
    killTimer(d->m_delayedDrawTimer);
    d->m_delayedDrawTimer = 0;

    if(d->m_bMyUpdate)
    {
        int fontHeight = fontMetrics().lineSpacing();

        if(d->m_selection.oldLastLine != -1)
        {
            int lastLine;
            int firstLine;
            if(d->m_selection.oldFirstLine != -1)
            {
                firstLine = min3(d->m_selection.oldFirstLine, d->m_selection.lastLine, d->m_selection.oldLastLine);
                lastLine = max3(d->m_selection.oldFirstLine, d->m_selection.lastLine, d->m_selection.oldLastLine);
            }
            else
            {
                firstLine = min2(d->m_selection.lastLine, d->m_selection.oldLastLine);
                lastLine = max2(d->m_selection.lastLine, d->m_selection.oldLastLine);
            }
            int y1 = (firstLine - d->m_firstLine) * fontHeight;
            int y2 = min2(height(), (lastLine - d->m_firstLine + 1) * fontHeight);

            if(y1 < height() && y2 > 0)
            {
                QRect invalidRect = QRect(0, y1 - 1, width(), y2 - y1 + fontHeight); // Some characters in exotic exceed the regular bottom.
                update(invalidRect);
            }
        }

        d->m_bMyUpdate = false;
    }

    if(d->m_scrollDeltaX != 0 || d->m_scrollDeltaY != 0)
    {
        d->m_selection.end(d->m_selection.lastLine + d->m_scrollDeltaY, d->m_selection.lastPos + d->m_scrollDeltaX);
        emit scroll(d->m_scrollDeltaX, d->m_scrollDeltaY);
        killTimer(d->m_delayedDrawTimer);
        d->m_delayedDrawTimer = startTimer(50);
    }
656 657 658 659
}

void DiffTextWindow::resetSelection()
{
660 661
    d->m_selection.reset();
    update();
662 663
}

664
void DiffTextWindow::convertToLinePos(int x, int y, int& line, int& pos)
665
{
666 667
    const QFontMetrics& fm = fontMetrics();
    int fontHeight = fm.lineSpacing();
668

669
    int yOffset = -d->m_firstLine * fontHeight;
670

671 672 673 674 675 676 677 678 679 680
    line = (y - yOffset) / fontHeight;
    if(line >= 0 && (!d->m_pOptions->m_bWordWrap || line < d->m_diff3WrapLineVector.count()))
    {
        QString s = d->getLineString(line);
        QTextLayout textLayout(s, font(), this);
        d->prepareTextLayout(textLayout, !d->m_pOptions->m_bWordWrap || d->m_diff3WrapLineVector[line].wrapLineOffset == 0);
        pos = textLayout.lineAt(0).xToCursor(x - textLayout.position().x());
    }
    else
        pos = -1;
681 682 683 684
}

int Selection::firstPosInLine(int l)
{
685
    assert(firstLine != -1);
686

687 688 689 690 691 692 693 694 695 696 697
    int l1 = firstLine;
    int l2 = lastLine;
    int p1 = firstPos;
    int p2 = lastPos;
    if(l1 > l2) {
        std::swap(l1, l2);
        std::swap(p1, p2);
    }
    if(l1 == l2 && p1 > p2) {
        std::swap(p1, p2);
    }
698

699 700 701
    if(l == l1)
        return p1;
    return 0;
702 703 704 705
}

int Selection::lastPosInLine(int l)
{
706
    assert(firstLine != -1);
707

708 709 710 711
    int l1 = firstLine;
    int l2 = lastLine;
    int p1 = firstPos;
    int p2 = lastPos;
712

713 714 715 716 717 718 719
    if(l1 > l2) {
        std::swap(l1, l2);
        std::swap(p1, p2);
    }
    if(l1 == l2 && p1 > p2) {
        std::swap(p1, p2);
    }
720

721 722 723
    if(l == l2)
        return p2;
    return INT_MAX;
724 725
}

726
bool Selection::within(int l, int p)
727
{
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    if(firstLine == -1) return false;
    int l1 = firstLine;
    int l2 = lastLine;
    int p1 = firstPos;
    int p2 = lastPos;
    if(l1 > l2) {
        std::swap(l1, l2);
        std::swap(p1, p2);
    }
    if(l1 == l2 && p1 > p2) {
        std::swap(p1, p2);
    }
    if(l1 <= l && l <= l2)
    {
        if(l1 == l2)
            return p >= p1 && p < p2;
        if(l == l1)
            return p >= p1;
        if(l == l2)
            return p < p2;
        return true;
    }
    return false;
751 752
}

753
bool Selection::lineWithin(int l)
754
{
755 756 757
    if(firstLine == -1) return false;
    int l1 = firstLine;
    int l2 = lastLine;
758

759 760 761
    if(l1 > l2) {
        std::swap(l1, l2);
    }
762

763
    return (l1 <= l && l <= l2);
764 765 766 767
}

class FormatRangeHelper
{
768 769 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 804 805 806 807 808 809 810 811 812
  private:
    QFont m_font;
    QPen m_pen;
    QColor m_background;
    int m_currentPos;

  public:
    QVector<QTextLayout::FormatRange> m_formatRanges;

    FormatRangeHelper()
    {
        m_pen = QColor(Qt::black);
        m_background = QColor(Qt::white);
        m_currentPos = 0;
    }
    void setFont(const QFont& f)
    {
        m_font = f;
    }
    void setPen(const QPen& pen)
    {
        m_pen = pen;
    }
    void setBackground(const QColor& background)
    {
        m_background = background;
    }

    void next()
    {
        if(m_formatRanges.isEmpty() || m_formatRanges.back().format.foreground().color() != m_pen.color() || m_formatRanges.back().format.background().color() != m_background)
        {
            QTextLayout::FormatRange fr;
            fr.length = 1;
            fr.start = m_currentPos;
            fr.format.setForeground(m_pen.color());
            fr.format.setBackground(m_background);
            m_formatRanges.append(fr);
        }
        else
        {
            ++m_formatRanges.back().length;
        }
        ++m_currentPos;
    }
813 814
};

815
void DiffTextWindowData::prepareTextLayout(QTextLayout& textLayout, bool /*bFirstLine*/, int visibleTextWidth)
816
{
Michael Reeves's avatar
Michael Reeves committed
817
    QTextOption textOption;
818 819 820 821
    textOption.setTabStop(QFontMetricsF(m_pDiffTextWindow->font()).width(' ') * m_pOptions->m_tabSize);
    if(m_pOptions->m_bShowWhiteSpaceCharacters)
        textOption.setFlags(QTextOption::ShowTabsAndSpaces);
    if(m_pOptions->m_bRightToLeftLanguage)
Michael Reeves's avatar
Michael Reeves committed
822
        textOption.setAlignment(Qt::AlignRight); // only relevant for multi line text layout
823 824
    if(visibleTextWidth >= 0)
        textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
Michael Reeves's avatar
Michael Reeves committed
825

826
    textLayout.setTextOption(textOption);
Michael Reeves's avatar
Michael Reeves committed
827

828 829 830 831 832 833 834 835 836 837 838 839
    if(m_pOptions->m_bShowWhiteSpaceCharacters)
    {
        // This additional format is only necessary for the tab arrow
        QVector<QTextLayout::FormatRange> formats;
        QTextLayout::FormatRange formatRange;
        formatRange.start = 0;
        formatRange.length = textLayout.text().length();
        formatRange.format.setFont(m_pDiffTextWindow->font());
        formats.append(formatRange);
        textLayout.setFormats(formats);
    }
    textLayout.beginLayout();
Michael Reeves's avatar
Michael Reeves committed
840

841 842
    int leading = m_pDiffTextWindow->fontMetrics().leading();
    int height = 0;
Michael Reeves's avatar
Michael Reeves committed
843

Michael Reeves's avatar
Michael Reeves committed
844
    int fontWidth = m_pDiffTextWindow->fontMetrics().width('0');
Michael Reeves's avatar
Michael Reeves committed
845 846
    int xOffset = leftInfoWidth() * fontWidth - m_horizScrollOffset;
    int textWidth = visibleTextWidth;
847
    if(textWidth < 0)
Michael Reeves's avatar
Michael Reeves committed
848 849 850
        textWidth = m_pDiffTextWindow->width() - xOffset;

    int indentation = 0;
851 852
    while(1)
    {
Michael Reeves's avatar
Michael Reeves committed
853
        QTextLine line = textLayout.createLine();
854
        if(!line.isValid())
Michael Reeves's avatar
Michael Reeves committed
855 856 857
            break;

        height += leading;
858 859 860
        //if ( !bFirstLine )
        //   indentation = m_pDiffTextWindow->fontMetrics().width(' ') * m_pOptions->m_tabSize;
        if(visibleTextWidth >= 0)
Michael Reeves's avatar
Michael Reeves committed
861
        {
862 863
            line.setLineWidth(visibleTextWidth - indentation);
            line.setPosition(QPointF(indentation, height));
Michael Reeves's avatar
Michael Reeves committed
864
            height += line.height();
Michael Reeves's avatar
Michael Reeves committed
865
            //bFirstLine = false;
Michael Reeves's avatar
Michael Reeves committed
866
        }
Michael Reeves's avatar
Michael Reeves committed
867 868
        else // only one line
        {
869
            line.setPosition(QPointF(indentation, height));
Michael Reeves's avatar
Michael Reeves committed
870 871 872 873 874
            break;
        }
    }

    textLayout.endLayout();
875 876
    if(m_pOptions->m_bRightToLeftLanguage)
        textLayout.setPosition(QPointF(textWidth - textLayout.maximumWidth(), 0));
Michael Reeves's avatar
Michael Reeves committed
877
    else
878
        textLayout.setPosition(QPointF(xOffset, 0));
879
}
Joachim Eibl's avatar
Joachim Eibl committed
880

Joachim Eibl's avatar
Joachim Eibl committed
881
void DiffTextWindowData::writeLine(
882 883 884 885 886 887 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
    MyPainter& p,
    const LineData* pld,
    const DiffList* pLineDiff1,
    const DiffList* pLineDiff2,
    int line,
    int whatChanged,
    int whatChanged2,
    int srcLineIdx,
    int wrapLineOffset,
    int wrapLineLength,
    bool bWrapLine,
    const QRect& invalidRect,
    int deviceWidth)
{
    QFont normalFont = p.font();
    QFont diffFont = normalFont;
    diffFont.setItalic(m_pOptions->m_bItalicForDeltas);
    const QFontMetrics& fm = p.fontMetrics();
    int fontHeight = fm.lineSpacing();
    int fontAscent = fm.ascent();
    int fontWidth = fm.width('0');

    int xOffset = leftInfoWidth() * fontWidth - m_horizScrollOffset;
    int yOffset = (line - m_firstLine) * fontHeight;

    QRect lineRect(0, yOffset, deviceWidth, fontHeight);
    if(!invalidRect.intersects(lineRect))
    {
        return;
    }

    int fastSelectorLine1 = m_pDiffTextWindow->convertDiff3LineIdxToLine(m_fastSelectorLine1);
    int fastSelectorLine2 = m_pDiffTextWindow->convertDiff3LineIdxToLine(m_fastSelectorLine1 + m_fastSelectorNofLines) - 1;

    bool bFastSelectionRange = (line >= fastSelectorLine1 && line <= fastSelectorLine2);
    QColor bgColor = m_pOptions->m_bgColor;
    QColor diffBgColor = m_pOptions->m_diffBgColor;

    if(bFastSelectionRange)
    {
        bgColor = m_pOptions->m_currentRangeBgColor;
        diffBgColor = m_pOptions->m_currentRangeDiffBgColor;
    }

    if(yOffset + fontHeight < invalidRect.top() || invalidRect.bottom() < yOffset - fontHeight)
        return;

    int changed = whatChanged;
    if(pLineDiff1 != 0) changed |= 1;
    if(pLineDiff2 != 0) changed |= 2;

    QColor c = m_pOptions->m_fgColor;
    p.setPen(c);
    if(changed == 2) {
        c = m_cDiff2;
    }
    else if(changed == 1)
    {
        c = m_cDiff1;
    }
    else if(changed == 3)
    {
        c = m_cDiffBoth;
    }

    if(pld != 0)
    {
        // First calculate the "changed" information for each character.
        int i = 0;
        QString lineString(pld->pLine, pld->size);
        if(!lineString.isEmpty())
        {
            switch(lineString[lineString.length() - 1].unicode())
            {
            case '\n':
                lineString[lineString.length() - 1] = 0x00B6;
                break; // "Pilcrow", "paragraph mark"
            case '\r':
                lineString[lineString.length() - 1] = 0x00A4;
                break; // Currency sign ;0x2761 "curved stem paragraph sign ornament"
                //case '\0b' : lineString[lineString.length()-1] = 0x2756; break; // some other nice looking character
            }
        }
        QVector<UINT8> charChanged(pld->size);
        Merger merger(pLineDiff1, pLineDiff2);
        while(!merger.isEndReached() && i < pld->size)
        {
            if(i < pld->size)
Joachim Eibl's avatar
Joachim Eibl committed
970
            {
971 972 973 974 975 976 977 978 979 980 981
                charChanged[i] = merger.whatChanged();
                ++i;
            }
            merger.next();
        }

        int outPos = 0;

        int lineLength = m_bWordWrap ? wrapLineOffset + wrapLineLength : lineString.length();

        FormatRangeHelper frh;
Michael Reeves's avatar
Michael Reeves committed
982

983 984 985 986
        for(i = wrapLineOffset; i < lineLength; ++i)
        {
            QColor c = m_pOptions->m_fgColor;
            int cchanged = charChanged[i] | whatChanged;
Michael Reeves's avatar
Michael Reeves committed
987

988 989
            if(cchanged == 2) {
                c = m_cDiff2;
Michael Reeves's avatar
Michael Reeves committed
990
            }
991 992 993 994 995
            else if(cchanged == 1)
            {
                c = m_cDiff1;
            }
            else if(cchanged == 3)
996
            {
997 998 999 1000 1001 1002 1003 1004
                c = m_cDiffBoth;
            }

            if(c != m_pOptions->m_fgColor && whatChanged2 == 0 && !m_pOptions->m_bShowWhiteSpace)
            {
                // The user doesn't want to see highlighted white space.
                c = m_pOptions->m_fgColor;
            }
Michael Reeves's avatar
Michael Reeves committed
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
            //QRect outRect( xOffset + outPixelPos, yOffset, charWidth*spaces, fontHeight );
            //if ( m_pOptions->m_bRightToLeftLanguage )
            //   outRect = QRect( deviceWidth-1-(xOffset + outPixelPos), yOffset, -charWidth*spaces, fontHeight ).normalized();
            //if ( invalidRect.intersects( outRect ) )
            {
                frh.setBackground(bgColor);
                if(!m_selection.within(line, outPos))
                {

                    if(c != m_pOptions->m_fgColor)
                    {
                        QColor lightc = diffBgColor;
                        frh.setBackground(lightc);
                        // Setting italic font here doesn't work: Changing the font only when drawing is too late
                    }

                    frh.setPen(c);
                    frh.next();
                    frh.setFont(normalFont);
                }
                else
                {
                    frh.setBackground(m_pDiffTextWindow->palette().highlight().color());
                    frh.setPen(m_pDiffTextWindow->palette().highlightedText().color());
                    frh.next();

                    m_selection.bSelectionContainsData = true;
                }
Michael Reeves's avatar
Michael Reeves committed
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

            ++outPos;
        } // end for

        QTextLayout textLayout(lineString.mid(wrapLineOffset, lineLength - wrapLineOffset), m_pDiffTextWindow->font(), m_pDiffTextWindow);
        prepareTextLayout(textLayout, !m_bWordWrap || wrapLineOffset == 0);
        textLayout.draw(&p, QPoint(0, yOffset), frh.m_formatRanges /*, const QRectF & clip = QRectF() */);
    }

    p.fillRect(0, yOffset, leftInfoWidth() * fontWidth, fontHeight, m_pOptions->m_bgColor);

    xOffset = (m_lineNumberWidth + 2) * fontWidth;
    int xLeft = m_lineNumberWidth * fontWidth;
    p.setPen(m_pOptions->m_fgColor);
    if(pld != 0)
    {
        if(m_pOptions->m_bShowLineNumbers && !bWrapLine)
        {
            QString num;
            num.sprintf("%0*d", m_lineNumberWidth, srcLineIdx + 1);
            p.drawText(0, yOffset + fontAscent, num);
            //p.drawLine( xLeft -1, yOffset, xLeft -1, yOffset+fontHeight-1 );
        }
        if(!bWrapLine || wrapLineLength > 0)
        {
Michael Reeves's avatar
Michael Reeves committed
1060
#if defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
1061
            Qt::PenStyle wrapLinePenStyle = Qt::DashLine; // Qt::DotLine doesn't work on Mac (Qt4.8.6).
Michael Reeves's avatar
Michael Reeves committed
1062
#else
1063
            Qt::PenStyle wrapLinePenStyle = Qt::DotLine;
Michael Reeves's avatar
Michael Reeves committed
1064
#endif
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 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 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
            p.setPen(QPen(m_pOptions->m_fgColor, 0, bWrapLine ? wrapLinePenStyle : Qt::SolidLine));
            p.drawLine(xOffset + 1, yOffset, xOffset + 1, yOffset + fontHeight - 1);
            p.setPen(QPen(m_pOptions->m_fgColor, 0, Qt::SolidLine));
        }
    }
    if(c != m_pOptions->m_fgColor && whatChanged2 == 0) //&& whatChanged==0 )
    {
        if(m_pOptions->m_bShowWhiteSpace)
        {
            p.setBrushOrigin(0, 0);
            p.fillRect(xLeft, yOffset, fontWidth * 2 - 1, fontHeight, QBrush(c, Qt::Dense5Pattern));
        }
    }
    else
    {
        p.fillRect(xLeft, yOffset, fontWidth * 2 - 1, fontHeight, c == m_pOptions->m_fgColor ? bgColor : c);
    }

    if(bFastSelectionRange)
    {
        p.fillRect(xOffset + fontWidth - 1, yOffset, 3, fontHeight, m_pOptions->m_fgColor);
    }

    // Check if line needs a manual diff help mark
    ManualDiffHelpList::const_iterator ci;
    for(ci = m_pManualDiffHelpList->begin(); ci != m_pManualDiffHelpList->end(); ++ci)
    {
        const ManualDiffHelpEntry& mdhe = *ci;
        int rangeLine1 = -1;
        int rangeLine2 = -1;
        if(m_winIdx == 1) {
            rangeLine1 = mdhe.lineA1;
            rangeLine2 = mdhe.lineA2;
        }
        if(m_winIdx == 2) {
            rangeLine1 = mdhe.lineB1;
            rangeLine2 = mdhe.lineB2;
        }
        if(m_winIdx == 3) {
            rangeLine1 = mdhe.lineC1;
            rangeLine2 = mdhe.lineC2;
        }
        if(rangeLine1 >= 0 && rangeLine2 >= 0 && srcLineIdx >= rangeLine1 && srcLineIdx <= rangeLine2)
        {
            p.fillRect(xOffset - fontWidth, yOffset, fontWidth - 1, fontHeight, m_pOptions->m_manualHelpRangeColor);
            break;
        }
    }
}

void DiffTextWindow::paintEvent(QPaintEvent* e)
{
    QRect invalidRect = e->rect();
    if(invalidRect.isEmpty() || !d->m_bPaintingAllowed)
        return;

    if(d->m_pDiff3LineVector == 0 || (d->m_diff3WrapLineVector.empty() && d->m_bWordWrap))
    {
        QPainter p(this);
        p.fillRect(invalidRect, d->m_pOptions->m_bgColor);
        return;
    }

    bool bOldSelectionContainsData = d->m_selection.bSelectionContainsData;
    d->m_selection.bSelectionContainsData = false;

    int endLine = min2(d->m_firstLine + getNofVisibleLines() + 2, getNofLines());

    MyPainter p(this, d->m_pOptions->m_bRightToLeftLanguage, width(), fontMetrics().width('0'));

    p.setFont(font());
    p.QPainter::fillRect(invalidRect, d->m_pOptions->m_bgColor);

    d->draw(p, invalidRect, width(), d->m_firstLine, endLine);
    p.end();

    d->m_oldFirstLine = d->m_firstLine;
    d->m_selection.oldLastLine = -1;
    if(d->m_selection.oldFirstLine != -1)
        d->m_selection.oldFirstLine = -1;

    if(!bOldSelectionContainsData && d->m_selection.bSelectionContainsData)
        emit newSelection();
}

void DiffTextWindow::print(MyPainter& p, const QRect&, int firstLine, int nofLinesPerPage)
{
    if(d->m_pDiff3LineVector == 0 || !d->m_bPaintingAllowed ||
       (d->m_diff3WrapLineVector.empty() && d->m_bWordWrap))
        return;
    resetSelection();
    int oldFirstLine = d->m_firstLine;
    d->m_firstLine = firstLine;
    QRect invalidRect = QRect(0, 0, 1000000000, 1000000000);
    QColor bgColor = d->m_pOptions->m_bgColor;
    d->m_pOptions->m_bgColor = Qt::white;
    d->draw(p, invalidRect, p.window().width(), firstLine, min2(firstLine + nofLinesPerPage, getNofLines()));
    d->m_pOptions->m_bgColor = bgColor;
    d->m_firstLine = oldFirstLine;
}

void DiffTextWindowData::draw(MyPainter& p, const QRect& invalidRect, int deviceWidth, int beginLine, int endLine)
{
    m_lineNumberWidth = m_pOptions->m_bShowLineNumbers ? (int)log10((double)qMax(m_size, 1)) + 1 : 0;

    if(m_winIdx == 1)
    {
        m_cThis = m_pOptions->m_colorA;
        m_cDiff1 = m_pOptions->m_colorB;
        m_cDiff2 = m_pOptions->m_colorC;
    }
    if(m_winIdx == 2)
    {
        m_cThis = m_pOptions->m_colorB;
        m_cDiff1 = m_pOptions->m_colorC;
        m_cDiff2 = m_pOptions->m_colorA;
    }
    if(m_winIdx == 3)
    {
        m_cThis = m_pOptions->m_colorC;
        m_cDiff1 = m_pOptions->m_colorA;
        m_cDiff2 = m_pOptions->m_colorB;
    }
    m_cDiffBoth = m_pOptions->m_colorForConflict; // Conflict color

    p.setPen(m_cThis);

    for(int line = beginLine; line < endLine; ++line)
    {
        int wrapLineOffset = 0;
        int wrapLineLength = 0;
        const Diff3Line* d3l = 0;
        bool bWrapLine = false;
        if(m_bWordWrap)
        {
            Diff3WrapLine& d3wl = m_diff3WrapLineVector[line];
            wrapLineOffset = d3wl.wrapLineOffset;
            wrapLineLength = d3wl.wrapLineLength;
            d3l = d3wl.pD3L;
            bWrapLine = line > 0 && m_diff3WrapLineVector[line - 1].pD3L == d3l;
        }
        else
        {
            d3l = (*m_pDiff3LineVector)[line];
        }
        DiffList* pFineDiff1;
        DiffList* pFineDiff2;
        int changed = 0;
        int changed2 = 0;

        int srcLineIdx = -1;
        getLineInfo(*d3l, srcLineIdx, pFineDiff1, pFineDiff2, changed, changed2);

        writeLine(
            p,                                               // QPainter
            srcLineIdx == -1 ? 0 : &m_pLineData[srcLineIdx], // Text in this line
            pFineDiff1,
            pFineDiff2,
            line, // Line on the screen
            changed,
            changed2,
            srcLineIdx,
            wrapLineOffset,
            wrapLineLength,
            bWrapLine,
            invalidRect,
            deviceWidth);
    }
}

QString DiffTextWindowData::getString(int d3lIdx)
{
    if(d3lIdx < 0 || d3lIdx >= (int)m_pDiff3LineVector->size())
        return QString();
    const Diff3Line* d3l = (*m_pDiff3LineVector)[d3lIdx];
    DiffList* pFineDiff1;
    DiffList* pFineDiff2;
    int changed = 0;
    int changed2 = 0;
    int lineIdx;
    getLineInfo(*d3l, lineIdx, pFineDiff1, pFineDiff2, changed, changed2);

    if(lineIdx == -1)
        return QString();
    else
    {
        const LineData* ld = &m_pLineData[lineIdx];
        return QString(ld->pLine, ld->size);
    }
    return QString();
}

QString DiffTextWindowData::getLineString(int line)
{
    if(m_bWordWrap)
    {
        if(line < m_diff3WrapLineVector.count())
        {
            int d3LIdx = m_pDiffTextWindow->convertLineToDiff3LineIdx(line);
            return getString(d3LIdx).mid(m_diff3WrapLineVector[line].wrapLineOffset, m_diff3WrapLineVector[line].wrapLineLength);
        }
        else
            return QString();
    }
    else
    {
        return getString(line);
    }
Michael Reeves's avatar
Michael Reeves committed
1273 1274
}

1275
void DiffTextWindowData::getLineInfo(
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
    const Diff3Line& d3l,
    int& lineIdx,
    DiffList*& pFineDiff1, DiffList*& pFineDiff2, // return values
    int& changed, int& changed2)
{
    changed = 0;
    changed2 = 0;
    bool bAEqB = d3l.bAEqB || (d3l.bWhiteLineA && d3l.bWhiteLineB);
    bool bAEqC = d3l.bAEqC || (d3l.bWhiteLineA && d3l.bWhiteLineC);
    bool bBEqC = d3l.bBEqC || (d3l.bWhiteLineB && d3l.bWhiteLineC);
    if(m_winIdx == 1) {
        lineIdx = d3l.lineA;
        pFineDiff1 = d3l.pFineAB;
        pFineDiff2 = d3l.pFineCA;
        changed |= ((d3l.lineB == -1) != (lineIdx == -1) ? 1 : 0) +
                   ((d3l.lineC == -1) != (lineIdx == -1) && m_bTriple ? 2 : 0);
        changed2 |= (bAEqB ? 0 : 1) + (bAEqC || !m_bTriple ? 0 : 2);
    }
    else if(m_winIdx == 2)
    {
        lineIdx = d3l.lineB;
        pFineDiff1 = d3l.pFineBC;
        pFineDiff2 = d3l.pFineAB;
        changed |= ((d3l.lineC == -1) != (lineIdx == -1) && m_bTriple ? 1 : 0) +
                   ((d3l.lineA == -1) != (lineIdx == -1) ? 2 : 0);
        changed2 |= (bBEqC || !m_bTriple ? 0 : 1) + (bAEqB ? 0 : 2);
    }
    else if(m_winIdx == 3)
    {
        lineIdx = d3l.lineC;
        pFineDiff1 = d3l.pFineCA;
        pFineDiff2 = d3l.pFineBC;
        changed |= ((d3l.lineA == -1) != (lineIdx == -1) ? 1 : 0) +
                   ((d3l.lineB == -1) != (lineIdx == -1) ? 2 : 0);
        changed2 |= (bAEqC ? 0 : 1) + (bBEqC ? 0 : 2);
    }
    else
        assert(false);
}

void DiffTextWindow::resizeEvent(QResizeEvent* e)
{
    QSize s = e->size();
    QFontMetrics fm = fontMetrics();
    int visibleLines = s.height() / fm.lineSpacing() - 2;
    int visibleColumns = s.width() / fm.width('0') - d->leftInfoWidth();
    if(e->size().height() != e->oldSize().height())
        emit resizeHeightChangedSignal(visibleLines);
    if(e->size().width() != e->oldSize().width())
        emit resizeWidthChangedSignal(visibleColumns);
    QWidget::resizeEvent(e);
1327 1328 1329 1330
}

int DiffTextWindow::getNofVisibleLines()
{
1331 1332 1333 1334
    QFontMetrics fm = fontMetrics();
    int fmh = fm.lineSpacing();
    int h = height();
    return h / fmh - 1;
1335 1336 1337 1338
}

int DiffTextWindow::getVisibleTextAreaWidth()
{
1339 1340
    QFontMetrics fm = fontMetrics();
    return width() - d->leftInfoWidth() * fm.width('0');
1341 1342 1343 1344
}

QString DiffTextWindow::getSelection()
{
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 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    if(d->m_pLineData == 0)
        return QString();

    QString selectionString;

    int line = 0;
    int lineIdx = 0;

    int it;
    int vectorSize = d->m_bWordWrap ? d->m_diff3WrapLineVector.size() : d->m_pDiff3LineVector->size();
    for(it = 0; it < vectorSize; ++it)
    {
        const Diff3Line* d3l = d->m_bWordWrap ? d->m_diff3WrapLineVector[it].pD3L : (*d->m_pDiff3LineVector)[it];
        if(d->m_winIdx == 1) {
            lineIdx = d3l->lineA;
        }
        else if(d->m_winIdx == 2)
        {
            lineIdx = d3l->lineB;
        }
        else if(d->m_winIdx == 3)
        {
            lineIdx = d3l->lineC;
        }
        else
            assert(false);

        if(lineIdx != -1)
        {
            const QChar* pLine = d->m_pLineData[lineIdx].pLine;
            int size = d->m_pLineData[lineIdx].size;
            QString lineString = QString(pLine, size);

            if(d->m_bWordWrap)
            {
                size = d->m_diff3WrapLineVector[it].wrapLineLength;
                lineString = lineString.mid(d->m_diff3WrapLineVector[it].wrapLineOffset, size);
            }

            for(int i = 0; i < size; ++i)
            {
                if(d->m_selection.within(line, i))
                {
                    selectionString += lineString[i];
                }
            }

            if(d->m_selection.within(line, size) &&
               !(d->m_bWordWrap && it + 1 < vectorSize && d3l == d->m_diff3WrapLineVector[it + 1].pD3L))
            {
#if defined(_WIN32) || defined(Q_OS_OS2)
                selectionString += '\r';
#endif
                selectionString += '\n';
            }
        }

        ++line;
    }

    return selectionString;
}

bool DiffTextWindow::findString(const QString& s, int& d3vLine, int& posInLine, bool bDirDown, bool bCaseSensitive)
{
    int it = d3vLine;
    int endIt = bDirDown ? (int)d->m_pDiff3LineVector->size() : -1;
    int step = bDirDown ? 1 : -1;
    int startPos = posInLine;

    for(; it != endIt; it += step)
    {
        QString line = d->getString(it);
        if(!line.isEmpty())
        {
            int pos = line.indexOf(s, startPos, bCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive);
            if(pos != -1)
1422
            {
1423 1424 1425
                d3vLine = it;
                posInLine = pos;
                return true;
Michael Reeves's avatar
Michael Reeves committed
1426
            }
1427 1428 1429 1430 1431

            startPos = 0;
        }
    }
    return false;
1432