mergeresultwindow.cpp 107 KB
Newer Older
Joachim Eibl's avatar
Joachim Eibl committed
1 2 3 4
/***************************************************************************
                          mergeresultwindow.cpp  -  description
                             -------------------
    begin                : Sun Apr 14 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 "mergeresultwindow.h"
19
#include "options.h"
Joachim Eibl's avatar
Joachim Eibl committed
20

Joachim Eibl's avatar
Joachim Eibl committed
21 22
#include <QApplication>
#include <QClipboard>
23 24
#include <QComboBox>
#include <QCursor>
Joachim Eibl's avatar
Joachim Eibl committed
25 26
#include <QDir>
#include <QFile>
27
#include <QHBoxLayout>
Joachim Eibl's avatar
Joachim Eibl committed
28
#include <QKeyEvent>
29
#include <QLabel>
Joachim Eibl's avatar
Joachim Eibl committed
30
#include <QLineEdit>
31 32 33 34
#include <QMouseEvent>
#include <QPainter>
#include <QRegExp>
#include <QStatusBar>
Joachim Eibl's avatar
Joachim Eibl committed
35
#include <QTextCodec>
36 37
#include <QTextLayout>
#include <QTextStream>
Joachim Eibl's avatar
Joachim Eibl committed
38
#include <QUrl>
Joachim Eibl's avatar
0.9.93  
Joachim Eibl committed
39
//Added by qt3to4:
40
#include <QDropEvent>
Joachim Eibl's avatar
0.9.93  
Joachim Eibl committed
41
#include <QEvent>
42
#include <QFocusEvent>
Joachim Eibl's avatar
0.9.93  
Joachim Eibl committed
43
#include <QInputEvent>
44
#include <QMimeData>
Joachim Eibl's avatar
0.9.93  
Joachim Eibl committed
45
#include <QPaintEvent>
46 47
#include <QPixmap>
#include <QResizeEvent>
Joachim Eibl's avatar
0.9.93  
Joachim Eibl committed
48
#include <QTextStream>
49 50
#include <QTimerEvent>
#include <QWheelEvent>
Joachim Eibl's avatar
Joachim Eibl committed
51

Michael Reeves's avatar
Michael Reeves committed
52 53
#include <KLocalizedString>
#include <KMessageBox>
Joachim Eibl's avatar
Joachim Eibl committed
54 55 56

int g_bAutoSolve = true;

Joachim Eibl's avatar
Joachim Eibl committed
57
#undef leftInfoWidth
Joachim Eibl's avatar
Joachim Eibl committed
58 59

MergeResultWindow::MergeResultWindow(
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
    QWidget* pParent,
    Options* pOptions,
    QStatusBar* pStatusBar)
    : QWidget(pParent)
{
    setObjectName("MergeResultWindow");
    setFocusPolicy(Qt::ClickFocus);

    m_firstLine = 0;
    m_horizScrollOffset = 0;
    m_nofLines = 0;
    m_totalSize = 0;
    m_bMyUpdate = false;
    m_bInsertMode = true;
    m_scrollDeltaX = 0;
    m_scrollDeltaY = 0;
    m_bModified = false;
    m_eOverviewMode = Overview::eOMNormal;

    m_pldA = 0;
    m_pldB = 0;
    m_pldC = 0;
    m_sizeA = 0;
    m_sizeB = 0;
    m_sizeC = 0;

    m_pDiff3LineList = 0;
    m_pTotalDiffStatus = 0;
    m_pStatusBar = pStatusBar;
    if(m_pStatusBar)
        connect(m_pStatusBar, SIGNAL(messageChanged(const QString&)), this, SLOT(slotStatusMessageChanged(const QString&)));

    m_pOptions = pOptions;
    m_bPaintingAllowed = false;
    m_delayedDrawTimer = 0;

    m_cursorXPos = 0;
    m_cursorOldXPixelPos = 0;
    m_cursorYPos = 0;
    m_bCursorOn = true;
    m_bCursorUpdate = false;
    m_maxTextWidth = -1;
    connect(&m_cursorTimer, SIGNAL(timeout()), this, SLOT(slotCursorUpdate()));
    m_cursorTimer.setSingleShot(true);
    m_cursorTimer.start(500 /*ms*/);
    m_selection.reset();

    setMinimumSize(QSize(20, 20));
    setFont(m_pOptions->m_font);
Joachim Eibl's avatar
Joachim Eibl committed
109 110 111
}

void MergeResultWindow::init(
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
    const LineData* pLineDataA, int sizeA,
    const LineData* pLineDataB, int sizeB,
    const LineData* pLineDataC, int sizeC,
    const Diff3LineList* pDiff3LineList,
    TotalDiffStatus* pTotalDiffStatus)
{
    m_firstLine = 0;
    m_horizScrollOffset = 0;
    m_nofLines = 0;
    m_bMyUpdate = false;
    m_bInsertMode = true;
    m_scrollDeltaX = 0;
    m_scrollDeltaY = 0;
    setModified(false);

    m_pldA = pLineDataA;
    m_pldB = pLineDataB;
    m_pldC = pLineDataC;
    m_sizeA = sizeA;
    m_sizeB = sizeB;
    m_sizeC = sizeC;

    m_pDiff3LineList = pDiff3LineList;
    m_pTotalDiffStatus = pTotalDiffStatus;

    m_selection.reset();
    m_cursorXPos = 0;
    m_cursorOldXPixelPos = 0;
    m_cursorYPos = 0;

    m_maxTextWidth = -1;

    merge(g_bAutoSolve, -1);
    g_bAutoSolve = true;
    update();
    updateSourceMask();

    showUnsolvedConflictsStatusMessage();
Michael Reeves's avatar
Michael Reeves committed
150 151 152 153
}

void MergeResultWindow::showUnsolvedConflictsStatusMessage()
{
154 155 156 157
    if(m_pStatusBar)
    {
        int wsc;
        int nofUnsolved = getNrOfUnsolvedConflicts(&wsc);
Michael Reeves's avatar
Michael Reeves committed
158

159 160 161
        m_persistentStatusMessage = i18n("Number of remaining unsolved conflicts: %1 (of which %2 are whitespace)", nofUnsolved, wsc);
        m_pStatusBar->showMessage(m_persistentStatusMessage);
    }
Michael Reeves's avatar
Michael Reeves committed
162 163 164 165
}

void MergeResultWindow::slotStatusMessageChanged(const QString& s)
{
166 167 168 169
    if(s.isEmpty() && !m_persistentStatusMessage.isEmpty())
    {
        m_pStatusBar->showMessage(m_persistentStatusMessage, 0);
    }
170 171 172 173
}

void MergeResultWindow::reset()
{
174 175 176 177 178 179 180 181 182
    m_pDiff3LineList = 0;
    m_pTotalDiffStatus = 0;
    m_pldA = 0;
    m_pldB = 0;
    m_pldC = 0;
    if(!m_persistentStatusMessage.isEmpty())
    {
        m_persistentStatusMessage = QString();
    }
Joachim Eibl's avatar
Joachim Eibl committed
183
}
Joachim Eibl's avatar
Joachim Eibl committed
184 185 186 187

// Calculate the merge information for the given Diff3Line.
// Results will be stored in mergeDetails, bConflict, bLineRemoved and src.
void mergeOneLine(
188 189 190 191 192 193 194 195 196 197 198 199 200
    const Diff3Line& d, e_MergeDetails& mergeDetails, bool& bConflict,
    bool& bLineRemoved, int& src, bool bTwoInputs)
{
    mergeDetails = eDefault;
    bConflict = false;
    bLineRemoved = false;
    src = 0;

    if(bTwoInputs) // Only two input files
    {
        if(d.lineA != -1 && d.lineB != -1)
        {
            if(d.pFineAB == 0)
201
            {
202 203
                mergeDetails = eNoChange;
                src = A;
Michael Reeves's avatar
Michael Reeves committed
204
            }
Joachim Eibl's avatar
Joachim Eibl committed
205
            else
206
            {
207 208
                mergeDetails = eBChanged;
                bConflict = true;
209
            }
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 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
        }
        else
        {
            if(d.lineA != -1 && d.lineB == -1)
            {
                mergeDetails = eBDeleted;
                bConflict = true;
            }
            else if(d.lineA == -1 && d.lineB != -1)
            {
                mergeDetails = eBDeleted;
                bConflict = true;
            }
        }
        return;
    }

    // A is base.
    if(d.lineA != -1 && d.lineB != -1 && d.lineC != -1)
    {
        if(d.pFineAB == 0 && d.pFineBC == 0 && d.pFineCA == 0)
        {
            mergeDetails = eNoChange;
            src = A;
        }
        else if(d.pFineAB == 0 && d.pFineBC != 0 && d.pFineCA != 0)
        {
            mergeDetails = eCChanged;
            src = C;
        }
        else if(d.pFineAB != 0 && d.pFineBC != 0 && d.pFineCA == 0)
        {
            mergeDetails = eBChanged;
            src = B;
        }
        else if(d.pFineAB != 0 && d.pFineBC == 0 && d.pFineCA != 0)
        {
            mergeDetails = eBCChangedAndEqual;
            src = C;
        }
        else if(d.pFineAB != 0 && d.pFineBC != 0 && d.pFineCA != 0)
        {
            mergeDetails = eBCChanged;
            bConflict = true;
        }
        else
            assert(false);
    }
    else if(d.lineA != -1 && d.lineB != -1 && d.lineC == -1)
    {
        if(d.pFineAB != 0)
        {
            mergeDetails = eBChanged_CDeleted;
            bConflict = true;
        }
        else
        {
            mergeDetails = eCDeleted;
            bLineRemoved = true;
            src = C;
        }
    }
    else if(d.lineA != -1 && d.lineB == -1 && d.lineC != -1)
    {
        if(d.pFineCA != 0)
        {
            mergeDetails = eCChanged_BDeleted;
            bConflict = true;
        }
        else
        {
            mergeDetails = eBDeleted;
            bLineRemoved = true;
            src = B;
        }
    }
    else if(d.lineA == -1 && d.lineB != -1 && d.lineC != -1)
    {
        if(d.pFineBC != 0)
        {
            mergeDetails = eBCAdded;
            bConflict = true;
        }
        else // B==C
        {
            mergeDetails = eBCAddedAndEqual;
            src = C;
        }
    }
    else if(d.lineA == -1 && d.lineB == -1 && d.lineC != -1)
    {
        mergeDetails = eCAdded;
        src = C;
    }
    else if(d.lineA == -1 && d.lineB != -1 && d.lineC == -1)
    {
        mergeDetails = eBAdded;
        src = B;
    }
    else if(d.lineA != -1 && d.lineB == -1 && d.lineC == -1)
    {
        mergeDetails = eBCDeleted;
        bLineRemoved = true;
        src = C;
    }
    else
        assert(false);
}

bool MergeResultWindow::sameKindCheck(const MergeLine& ml1, const MergeLine& ml2)
{
    if(ml1.bConflict && ml2.bConflict)
    {
        // Both lines have conflicts: If one is only a white space conflict and
        // the other one is a real conflict, then this line returns false.
        return ml1.id3l->bAEqC == ml2.id3l->bAEqC && ml1.id3l->bAEqB == ml2.id3l->bAEqB;
    }
    else
        return (
            (!ml1.bConflict && !ml2.bConflict && ml1.bDelta && ml2.bDelta && ml1.srcSelect == ml2.srcSelect && (ml1.mergeDetails == ml2.mergeDetails || (ml1.mergeDetails != eBCAddedAndEqual && ml2.mergeDetails != eBCAddedAndEqual))) ||
            (!ml1.bDelta && !ml2.bDelta));
}

void MergeResultWindow::merge(bool bAutoSolve, int defaultSelector, bool bConflictsOnly, bool bWhiteSpaceOnly)
{
    if(!bConflictsOnly)
    {
        if(m_bModified)
        {
            int result = KMessageBox::warningYesNo(this,
                                                   i18n("The output has been modified.\n"
                                                        "If you continue your changes will be lost."),
                                                   i18n("Warning"),
                                                   KStandardGuiItem::cont(),
                                                   KStandardGuiItem::cancel());
            if(result == KMessageBox::No)
                return;
        }

        m_mergeLineList.clear();
        m_totalSize = 0;
        int lineIdx = 0;
        Diff3LineList::const_iterator it;
        for(it = m_pDiff3LineList->begin(); it != m_pDiff3LineList->end(); ++it, ++lineIdx)
        {
            const Diff3Line& d = *it;

            MergeLine ml;
            bool bLineRemoved;
            mergeOneLine(d, ml.mergeDetails, ml.bConflict, bLineRemoved, ml.srcSelect, m_pldC == 0);

            // Automatic solving for only whitespace changes.
            if(ml.bConflict &&
               ((m_pldC == 0 && (d.bAEqB || (d.bWhiteLineA && d.bWhiteLineB))) ||
                (m_pldC != 0 && ((d.bAEqB && d.bAEqC) || (d.bWhiteLineA && d.bWhiteLineB && d.bWhiteLineC)))))
            {
                ml.bWhiteSpaceConflict = true;
            }

            ml.d3lLineIdx = lineIdx;
            ml.bDelta = ml.srcSelect != A;
            ml.id3l = it;
            ml.srcRangeLength = 1;

            MergeLine* back = m_mergeLineList.empty() ? 0 : &m_mergeLineList.back();

            bool bSame = back != 0 && sameKindCheck(ml, *back);
            if(bSame)
            {
                ++back->srcRangeLength;
                if(back->bWhiteSpaceConflict && !ml.bWhiteSpaceConflict)
                    back->bWhiteSpaceConflict = false;
            }
            else
            {
                ml.mergeEditLineList.setTotalSizePtr(&m_totalSize);
                m_mergeLineList.push_back(ml);
            }

            if(!ml.bConflict)
            {
                MergeLine& tmpBack = m_mergeLineList.back();
                MergeEditLine mel(ml.id3l);
                mel.setSource(ml.srcSelect, bLineRemoved);
                tmpBack.mergeEditLineList.push_back(mel);
            }
            else if(back == 0 || !back->bConflict || !bSame)
            {
                MergeLine& tmpBack = m_mergeLineList.back();
                MergeEditLine mel(ml.id3l);
                mel.setConflict();
                tmpBack.mergeEditLineList.push_back(mel);
            }
        }
    }

    bool bSolveWhiteSpaceConflicts = false;
    if(bAutoSolve) // when true, then the other params are not used and we can change them here. (see all invocations of merge())
    {
        if(m_pldC == 0 && m_pOptions->m_whiteSpace2FileMergeDefault != 0) // Only two inputs
        {
            defaultSelector = m_pOptions->m_whiteSpace2FileMergeDefault;
            bWhiteSpaceOnly = true;
            bSolveWhiteSpaceConflicts = true;
        }
        else if(m_pldC != 0 && m_pOptions->m_whiteSpace3FileMergeDefault != 0)
        {
            defaultSelector = m_pOptions->m_whiteSpace3FileMergeDefault;
            bWhiteSpaceOnly = true;
            bSolveWhiteSpaceConflicts = true;
        }
    }

    if(!bAutoSolve || bSolveWhiteSpaceConflicts)
    {
        // Change all auto selections
        MergeLineList::iterator mlIt;
        for(mlIt = m_mergeLineList.begin(); mlIt != m_mergeLineList.end(); ++mlIt)
        {
            MergeLine& ml = *mlIt;
            bool bConflict = ml.mergeEditLineList.empty() || ml.mergeEditLineList.begin()->isConflict();
            if(ml.bDelta && (!bConflictsOnly || bConflict) && (!bWhiteSpaceOnly || ml.bWhiteSpaceConflict))
            {
                ml.mergeEditLineList.clear();
                if(defaultSelector == -1 && ml.bDelta)
                {
                    MergeEditLine mel(ml.id3l);
                    ;
                    mel.setConflict();
                    ml.bConflict = true;
                    ml.mergeEditLineList.push_back(mel);
                }
                else
                {
                    Diff3LineList::const_iterator d3llit = ml.id3l;
                    int j;

                    for(j = 0; j < ml.srcRangeLength; ++j)
                    {
                        MergeEditLine mel(d3llit);
                        mel.setSource(defaultSelector, false);

                        int srcLine = defaultSelector == 1 ? d3llit->lineA : defaultSelector == 2 ? d3llit->lineB : defaultSelector == 3 ? d3llit->lineC : -1;

                        if(srcLine != -1)
                        {
                            ml.mergeEditLineList.push_back(mel);
                        }

                        ++d3llit;
                    }

                    if(ml.mergeEditLineList.empty()) // Make a line nevertheless
                    {
                        MergeEditLine mel(ml.id3l);
                        mel.setRemoved(defaultSelector);
                        ml.mergeEditLineList.push_back(mel);
                    }
                }
            }
        }
    }

    MergeLineList::iterator mlIt;
    for(mlIt = m_mergeLineList.begin(); mlIt != m_mergeLineList.end(); ++mlIt)
    {
        MergeLine& ml = *mlIt;
        // Remove all lines that are empty, because no src lines are there.

        int oldSrcLine = -1;
        int oldSrc = -1;
        MergeEditLineList::iterator melIt;
        for(melIt = ml.mergeEditLineList.begin(); melIt != ml.mergeEditLineList.end();)
        {
            MergeEditLine& mel = *melIt;
            int melsrc = mel.src();

            int srcLine = mel.isRemoved() ? -1 : melsrc == 1 ? mel.id3l()->lineA : melsrc == 2 ? mel.id3l()->lineB : melsrc == 3 ? mel.id3l()->lineC : -1;
Joachim Eibl's avatar
Joachim Eibl committed
488

489 490 491 492 493 494
            // At least one line remains because oldSrc != melsrc for first line in list
            // Other empty lines will be removed
            if(srcLine == -1 && oldSrcLine == -1 && oldSrc == melsrc)
                melIt = ml.mergeEditLineList.erase(melIt);
            else
                ++melIt;
Joachim Eibl's avatar
Joachim Eibl committed
495

496 497 498 499
            oldSrcLine = srcLine;
            oldSrc = melsrc;
        }
    }
Joachim Eibl's avatar
Joachim Eibl committed
500

501 502 503 504 505 506 507 508 509
    if(bAutoSolve && !bConflictsOnly)
    {
        if(m_pOptions->m_bRunHistoryAutoMergeOnMergeStart)
            slotMergeHistory();
        if(m_pOptions->m_bRunRegExpAutoMergeOnMergeStart)
            slotRegExpAutoMerge();
        if(m_pldC != 0 && !doRelevantChangesExist())
            emit noRelevantChangesDetected();
    }
Joachim Eibl's avatar
0.9.86  
Joachim Eibl committed
510

511 512 513
    int nrOfSolvedConflicts = 0;
    int nrOfUnsolvedConflicts = 0;
    int nrOfWhiteSpaceConflicts = 0;
Joachim Eibl's avatar
Joachim Eibl committed
514

515 516 517 518 519 520 521
    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if(i->bConflict)
            ++nrOfUnsolvedConflicts;
        else if(i->bDelta)
            ++nrOfSolvedConflicts;
Joachim Eibl's avatar
Joachim Eibl committed
522

523 524 525
        if(i->bWhiteSpaceConflict)
            ++nrOfWhiteSpaceConflicts;
    }
Joachim Eibl's avatar
0.9.86  
Joachim Eibl committed
526

527 528 529
    m_pTotalDiffStatus->nofUnsolvedConflicts = nrOfUnsolvedConflicts;
    m_pTotalDiffStatus->nofSolvedConflicts = nrOfSolvedConflicts;
    m_pTotalDiffStatus->nofWhitespaceConflicts = nrOfWhiteSpaceConflicts;
Joachim Eibl's avatar
0.9.86  
Joachim Eibl committed
530

531 532 533 534
    m_cursorXPos = 0;
    m_cursorOldXPixelPos = 0;
    m_cursorYPos = 0;
    m_maxTextWidth = -1;
535

536 537
    //m_firstLine = 0; // Must not set line/column without scrolling there
    //m_horizScrollOffset = 0;
Joachim Eibl's avatar
0.9.80  
Joachim Eibl committed
538

539
    setModified(false);
Joachim Eibl's avatar
0.9.86  
Joachim Eibl committed
540

541 542
    m_currentMergeLineIt = m_mergeLineList.begin();
    slotGoTop();
Joachim Eibl's avatar
0.9.86  
Joachim Eibl committed
543

544 545
    updateAvailabilities();
    update();
Joachim Eibl's avatar
Joachim Eibl committed
546 547
}

548 549
void MergeResultWindow::setFirstLine(int firstLine)
{
550 551
    m_firstLine = max2(0, firstLine);
    update();
Joachim Eibl's avatar
Joachim Eibl committed
552 553
}

554 555
void MergeResultWindow::setHorizScrollOffset(int horizScrollOffset)
{
556 557
    m_horizScrollOffset = max2(0, horizScrollOffset);
    update();
Joachim Eibl's avatar
Joachim Eibl committed
558 559
}

560 561
int MergeResultWindow::getMaxTextWidth()
{
562 563 564
    if(m_maxTextWidth < 0)
    {
        m_maxTextWidth = 0;
565

566 567 568 569 570 571
        MergeLineList::iterator mlIt = m_mergeLineList.begin();
        for(mlIt = m_mergeLineList.begin(); mlIt != m_mergeLineList.end(); ++mlIt)
        {
            MergeLine& ml = *mlIt;
            MergeEditLineList::iterator melIt;
            for(melIt = ml.mergeEditLineList.begin(); melIt != ml.mergeEditLineList.end(); ++melIt)
572
            {
573 574 575 576 577 578 579 580 581 582 583
                MergeEditLine& mel = *melIt;
                QString s = mel.getString(this);

                QTextLayout textLayout(s, font(), this);
                textLayout.beginLayout();
                textLayout.createLine();
                textLayout.endLayout();
                if(m_maxTextWidth < textLayout.maximumWidth())
                {
                    m_maxTextWidth = textLayout.maximumWidth();
                }
584
            }
585 586 587 588
        }
        m_maxTextWidth += 5; // cursorwidth
    }
    return m_maxTextWidth;
Joachim Eibl's avatar
Joachim Eibl committed
589 590
}

591 592
int MergeResultWindow::getNofLines()
{
593
    return m_totalSize;
Joachim Eibl's avatar
Joachim Eibl committed
594 595
}

596 597
int MergeResultWindow::getVisibleTextAreaWidth()
{
598 599
    // QFontMetrics fm = fontMetrics(); // FIXME used?
    return width() - getTextXOffset();
Joachim Eibl's avatar
Joachim Eibl committed
600 601
}

602 603
int MergeResultWindow::getNofVisibleLines()
{
604 605
    QFontMetrics fm = fontMetrics();
    return (height() - 3) / fm.lineSpacing() - 2;
Joachim Eibl's avatar
Joachim Eibl committed
606 607
}

608 609
int MergeResultWindow::getTextXOffset()
{
610 611
    QFontMetrics fm = fontMetrics();
    return 3 * fm.width('0');
612 613
}

614
void MergeResultWindow::resizeEvent(QResizeEvent* e)
615
{
616 617
    QWidget::resizeEvent(e);
    emit resizeSignal();
Joachim Eibl's avatar
Joachim Eibl committed
618 619
}

620 621
Overview::e_OverviewMode MergeResultWindow::getOverviewMode()
{
622
    return m_eOverviewMode;
Joachim Eibl's avatar
Joachim Eibl committed
623 624
}

625
void MergeResultWindow::setOverviewMode(Overview::e_OverviewMode eOverviewMode)
626
{
627
    m_eOverviewMode = eOverviewMode;
Joachim Eibl's avatar
Joachim Eibl committed
628 629 630
}

// Check whether we should ignore current delta when moving to next/previous delta
631
bool MergeResultWindow::checkOverviewIgnore(MergeLineList::iterator& i)
632
{
633 634 635 636 637 638 639 640
    if(m_eOverviewMode == Overview::eOMNormal) return false;
    if(m_eOverviewMode == Overview::eOMAvsB)
        return i->mergeDetails == eCAdded || i->mergeDetails == eCDeleted || i->mergeDetails == eCChanged;
    if(m_eOverviewMode == Overview::eOMAvsC)
        return i->mergeDetails == eBAdded || i->mergeDetails == eBDeleted || i->mergeDetails == eBChanged;
    if(m_eOverviewMode == Overview::eOMBvsC)
        return i->mergeDetails == eBCAddedAndEqual || i->mergeDetails == eBCDeleted || i->mergeDetails == eBCChangedAndEqual;
    return false;
Joachim Eibl's avatar
Joachim Eibl committed
641 642
}

Joachim Eibl's avatar
Joachim Eibl committed
643
// Go to prev/next delta/conflict or first/last delta.
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
void MergeResultWindow::go(e_Direction eDir, e_EndPoint eEndPoint)
{
    assert(eDir == eUp || eDir == eDown);
    MergeLineList::iterator i = m_currentMergeLineIt;
    bool bSkipWhiteConflicts = !m_pOptions->m_bShowWhiteSpace;
    if(eEndPoint == eEnd)
    {
        if(eDir == eUp)
            i = m_mergeLineList.begin(); // first mergeline
        else
            i = --m_mergeLineList.end(); // last mergeline

        while(isItAtEnd(eDir == eUp, i) && !i->bDelta)
        {
            if(eDir == eUp)
                ++i; // search downwards
            else
                --i; // search upwards
        }
    }
    else if(eEndPoint == eDelta && isItAtEnd(eDir != eUp, i))
    {
        do
        {
            if(eDir == eUp)
                --i;
            else
                ++i;
        } while(isItAtEnd(eDir != eUp, i) && (i->bDelta == false || checkOverviewIgnore(i) || (bSkipWhiteConflicts && i->bWhiteSpaceConflict)));
    }
    else if(eEndPoint == eConflict && isItAtEnd(eDir != eUp, i))
    {
        do
        {
            if(eDir == eUp)
                --i;
            else
                ++i;
        } while(isItAtEnd(eDir != eUp, i) && (i->bConflict == false || (bSkipWhiteConflicts && i->bWhiteSpaceConflict)));
    }
    else if(isItAtEnd(eDir != eUp, i) && eEndPoint == eUnsolvedConflict)
    {
        do
        {
            if(eDir == eUp)
                --i;
            else
                ++i;
        } while(isItAtEnd(eDir != eUp, i) && !i->mergeEditLineList.begin()->isConflict());
    }

    if(isVisible())
        setFocus();

    setFastSelector(i);
699 700 701 702
}

bool MergeResultWindow::isDeltaAboveCurrent()
{
703 704 705 706 707 708 709 710 711
    bool bSkipWhiteConflicts = !m_pOptions->m_bShowWhiteSpace;
    if(m_mergeLineList.empty()) return false;
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(i == m_mergeLineList.begin()) return false;
    do
    {
        --i;
        if(i->bDelta && !checkOverviewIgnore(i) && !(bSkipWhiteConflicts && i->bWhiteSpaceConflict)) return true;
    } while(i != m_mergeLineList.begin());
Michael Reeves's avatar
Michael Reeves committed
712

713
    return false;
Joachim Eibl's avatar
Joachim Eibl committed
714 715
}

716 717
bool MergeResultWindow::isDeltaBelowCurrent()
{
718 719
    bool bSkipWhiteConflicts = !m_pOptions->m_bShowWhiteSpace;
    if(m_mergeLineList.empty()) return false;
720

721 722 723 724 725 726 727 728 729 730
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(i != m_mergeLineList.end())
    {
        ++i;
        for(; i != m_mergeLineList.end(); ++i)
        {
            if(i->bDelta && !checkOverviewIgnore(i) && !(bSkipWhiteConflicts && i->bWhiteSpaceConflict)) return true;
        }
    }
    return false;
731 732 733 734
}

bool MergeResultWindow::isConflictAboveCurrent()
{
735 736 737
    if(m_mergeLineList.empty()) return false;
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(i == m_mergeLineList.begin()) return false;
Joachim Eibl's avatar
Joachim Eibl committed
738

739
    bool bSkipWhiteConflicts = !m_pOptions->m_bShowWhiteSpace;
Joachim Eibl's avatar
Joachim Eibl committed
740

741 742 743 744 745 746 747
    do
    {
        --i;
        if(i->bConflict && !(bSkipWhiteConflicts && i->bWhiteSpaceConflict)) return true;
    } while(i != m_mergeLineList.begin());

    return false;
Joachim Eibl's avatar
Joachim Eibl committed
748 749
}

750 751
bool MergeResultWindow::isConflictBelowCurrent()
{
752 753
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(m_mergeLineList.empty()) return false;
Michael Reeves's avatar
Michael Reeves committed
754

755
    bool bSkipWhiteConflicts = !m_pOptions->m_bShowWhiteSpace;
Michael Reeves's avatar
Michael Reeves committed
756

757 758 759 760 761 762 763 764 765
    if(i != m_mergeLineList.end())
    {
        ++i;
        for(; i != m_mergeLineList.end(); ++i)
        {
            if(i->bConflict && !(bSkipWhiteConflicts && i->bWhiteSpaceConflict)) return true;
        }
    }
    return false;
Joachim Eibl's avatar
Joachim Eibl committed
766 767
}

768 769
bool MergeResultWindow::isUnsolvedConflictAtCurrent()
{
770 771 772
    if(m_mergeLineList.empty()) return false;
    MergeLineList::iterator i = m_currentMergeLineIt;
    return i->mergeEditLineList.begin()->isConflict();
Joachim Eibl's avatar
Joachim Eibl committed
773 774
}

775 776
bool MergeResultWindow::isUnsolvedConflictAboveCurrent()
{
777 778 779 780 781 782 783 784 785 786 787
    if(m_mergeLineList.empty()) return false;
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(i == m_mergeLineList.begin()) return false;

    do
    {
        --i;
        if(i->mergeEditLineList.begin()->isConflict()) return true;
    } while(i != m_mergeLineList.begin());

    return false;
788 789 790 791
}

bool MergeResultWindow::isUnsolvedConflictBelowCurrent()
{
792 793 794 795 796 797 798 799 800 801 802 803
    MergeLineList::iterator i = m_currentMergeLineIt;
    if(m_mergeLineList.empty()) return false;

    if(i != m_mergeLineList.end())
    {
        ++i;
        for(; i != m_mergeLineList.end(); ++i)
        {
            if(i->mergeEditLineList.begin()->isConflict()) return true;
        }
    }
    return false;
804 805 806 807
}

void MergeResultWindow::slotGoTop()
{
808
    go(eUp, eEnd);
Joachim Eibl's avatar
Joachim Eibl committed
809 810
}

811 812
void MergeResultWindow::slotGoCurrent()
{
813
    setFastSelector(m_currentMergeLineIt);
Joachim Eibl's avatar
Joachim Eibl committed
814 815
}

816 817
void MergeResultWindow::slotGoBottom()
{
818
    go(eDown, eEnd);
Joachim Eibl's avatar
Joachim Eibl committed
819 820
}

821 822
void MergeResultWindow::slotGoPrevDelta()
{
823
    go(eUp, eDelta);
Joachim Eibl's avatar
Joachim Eibl committed
824 825
}

826 827
void MergeResultWindow::slotGoNextDelta()
{
828
    go(eDown, eDelta);
Joachim Eibl's avatar
Joachim Eibl committed
829 830
}

831 832
void MergeResultWindow::slotGoPrevConflict()
{
833
    go(eUp, eConflict);
Joachim Eibl's avatar
Joachim Eibl committed
834 835
}

836 837
void MergeResultWindow::slotGoNextConflict()
{
838
    go(eDown, eConflict);
Michael Reeves's avatar
Michael Reeves committed
839 840
}

841 842
void MergeResultWindow::slotGoPrevUnsolvedConflict()
{
843
    go(eUp, eUnsolvedConflict);
Michael Reeves's avatar
Michael Reeves committed
844 845
}

846 847
void MergeResultWindow::slotGoNextUnsolvedConflict()
{
848
    go(eDown, eUnsolvedConflict);
Joachim Eibl's avatar
Joachim Eibl committed
849 850 851 852
}

/** The line is given as a index in the Diff3LineList.
    The function calculates the corresponding iterator. */
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
void MergeResultWindow::slotSetFastSelectorLine(int line)
{
    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if(line >= i->d3lLineIdx && line < i->d3lLineIdx + i->srcRangeLength)
        {
            //if ( i->bDelta )
            {
                setFastSelector(i);
            }
            break;
        }
    }
}

int MergeResultWindow::getNrOfUnsolvedConflicts(int* pNrOfWhiteSpaceConflicts)
{
    int nrOfUnsolvedConflicts = 0;
    if(pNrOfWhiteSpaceConflicts != 0)
        *pNrOfWhiteSpaceConflicts = 0;

    MergeLineList::iterator mlIt = m_mergeLineList.begin();
    for(mlIt = m_mergeLineList.begin(); mlIt != m_mergeLineList.end(); ++mlIt)
    {
        MergeLine& ml = *mlIt;
        MergeEditLineList::iterator melIt = ml.mergeEditLineList.begin();
        if(melIt->isConflict())
        {
            ++nrOfUnsolvedConflicts;
            if(ml.bWhiteSpaceConflict && pNrOfWhiteSpaceConflicts != 0)
                ++*pNrOfWhiteSpaceConflicts;
        }
    }

    return nrOfUnsolvedConflicts;
889 890 891 892
}

void MergeResultWindow::showNrOfConflicts()
{
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
    if(!m_pOptions->m_bShowInfoDialogs)
        return;
    int nrOfConflicts = 0;
    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if(i->bConflict || i->bDelta)
            ++nrOfConflicts;
    }
    QString totalInfo;
    if(m_pTotalDiffStatus->bBinaryAEqB && m_pTotalDiffStatus->bBinaryAEqC)
        totalInfo += i18n("All input files are binary equal.");
    else if(m_pTotalDiffStatus->bTextAEqB && m_pTotalDiffStatus->bTextAEqC)
        totalInfo += i18n("All input files contain the same text.");
    else
    {
        if(m_pTotalDiffStatus->bBinaryAEqB)
            totalInfo += i18n("Files %1 and %2 are binary equal.\n", QString("A"), QString("B"));
        else if(m_pTotalDiffStatus->bTextAEqB)
            totalInfo += i18n("Files %1 and %2 have equal text.\n", QString("A"), QString("B"));
        if(m_pTotalDiffStatus->bBinaryAEqC)
            totalInfo += i18n("Files %1 and %2 are binary equal.\n", QString("A"), QString("C"));
        else if(m_pTotalDiffStatus->bTextAEqC)
            totalInfo += i18n("Files %1 and %2 have equal text.\n", QString("A"), QString("C"));
        if(m_pTotalDiffStatus->bBinaryBEqC)
            totalInfo += i18n("Files %1 and %2 are binary equal.\n", QString("B"), QString("C"));
        else if(m_pTotalDiffStatus->bTextBEqC)
            totalInfo += i18n("Files %1 and %2 have equal text.\n", QString("B"), QString("C"));
    }

    int nrOfUnsolvedConflicts = getNrOfUnsolvedConflicts();

    KMessageBox::information(this,
                             i18n("Total number of conflicts: ") + QString::number(nrOfConflicts) +
                                 i18n("\nNr of automatically solved conflicts: ") + QString::number(nrOfConflicts - nrOfUnsolvedConflicts) +
                                 i18n("\nNr of unsolved conflicts: ") + QString::number(nrOfUnsolvedConflicts) +
                                 "\n" + totalInfo,
                             i18n("Conflicts"));
931 932 933 934
}

void MergeResultWindow::setFastSelector(MergeLineList::iterator i)
{
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
    if(i == m_mergeLineList.end())
        return;
    m_currentMergeLineIt = i;
    emit setFastSelectorRange(i->d3lLineIdx, i->srcRangeLength);

    int line1 = 0;

    MergeLineList::iterator mlIt = m_mergeLineList.begin();
    for(mlIt = m_mergeLineList.begin(); mlIt != m_mergeLineList.end(); ++mlIt)
    {
        if(mlIt == m_currentMergeLineIt)
            break;
        line1 += mlIt->mergeEditLineList.size();
    }

    int nofLines = m_currentMergeLineIt->mergeEditLineList.size();
    int newFirstLine = getBestFirstLine(line1, nofLines, m_firstLine, getNofVisibleLines());
    if(newFirstLine != m_firstLine)
    {
        scroll(0, newFirstLine - m_firstLine);
    }

    if(m_selection.isEmpty())
    {
        m_cursorXPos = 0;
        m_cursorOldXPixelPos = 0;
        m_cursorYPos = line1;
    }

    update();
    updateSourceMask();
    emit updateAvailabilities();
}

void MergeResultWindow::choose(int selector)
{
    if(m_currentMergeLineIt == m_mergeLineList.end())
        return;

    setModified();

    // First find range for which this change works.
    MergeLine& ml = *m_currentMergeLineIt;

    MergeEditLineList::iterator melIt;

    // Now check if selector is active for this range already.
    bool bActive = false;

    // Remove unneeded lines in the range.
    for(melIt = ml.mergeEditLineList.begin(); melIt != ml.mergeEditLineList.end();)
    {
        MergeEditLine& mel = *melIt;
        if(mel.src() == selector)
            bActive = true;

        if(mel.src() == selector || !mel.isEditableText() || mel.isModified())
            melIt = ml.mergeEditLineList.erase(melIt);
        else
Joachim Eibl's avatar
Joachim Eibl committed
994
            ++melIt;
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
    }

    if(!bActive) // Selected source wasn't active.
    {            // Append the lines from selected source here at rangeEnd.
        Diff3LineList::const_iterator d3llit = ml.id3l;
        int j;

        for(j = 0; j < ml.srcRangeLength; ++j)
        {
            MergeEditLine mel(d3llit);
            mel.setSource(selector, false);
            ml.mergeEditLineList.push_back(mel);

            ++d3llit;
        }
    }

    if(!ml.mergeEditLineList.empty())
    {
        // Remove all lines that are empty, because no src lines are there.
        for(melIt = ml.mergeEditLineList.begin(); melIt != ml.mergeEditLineList.end();)
        {
            MergeEditLine& mel = *melIt;
Joachim Eibl's avatar
Joachim Eibl committed
1018

1019
            int srcLine = mel.src() == 1 ? mel.id3l()->lineA : mel.src() == 2 ? mel.id3l()->lineB : mel.src() == 3 ? mel.id3l()->lineC : -1;
Joachim Eibl's avatar
Joachim Eibl committed
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
            if(srcLine == -1)
                melIt = ml.mergeEditLineList.erase(melIt);
            else
                ++melIt;
        }
    }

    if(ml.mergeEditLineList.empty())
    {
        // Insert a dummy line:
        MergeEditLine mel(ml.id3l);
Joachim Eibl's avatar
Joachim Eibl committed
1032

1033 1034 1035 1036
        if(bActive)
            mel.setConflict(); // All src entries deleted => conflict
        else
            mel.setRemoved(selector); // No lines in corresponding src found.
Joachim Eibl's avatar
Joachim Eibl committed
1037

1038 1039 1040 1041 1042 1043 1044 1045
        ml.mergeEditLineList.push_back(mel);
    }

    if(m_cursorYPos >= m_totalSize)
    {
        m_cursorYPos = m_totalSize - 1;
        m_cursorXPos = 0;
    }
Michael Reeves's avatar
Michael Reeves committed
1046

1047 1048 1049 1050 1051
    m_maxTextWidth = -1;
    update();
    updateSourceMask();
    emit updateAvailabilities();
    showUnsolvedConflictsStatusMessage();
Joachim Eibl's avatar
Joachim Eibl committed
1052
}
Joachim Eibl's avatar
Joachim Eibl committed
1053

Michael Reeves's avatar
Michael Reeves committed
1054
// bConflictsOnly: automatically choose for conflicts only (true) or for everywhere (false)
1055
void MergeResultWindow::chooseGlobal(int selector, bool bConflictsOnly, bool bWhiteSpaceOnly)
1056
{
1057
    resetSelection();
Michael Reeves's avatar
Michael Reeves committed
1058

1059 1060 1061 1062
    merge(false, selector, bConflictsOnly, bWhiteSpaceOnly);
    setModified(true);
    update();
    showUnsolvedConflictsStatusMessage();
Joachim Eibl's avatar
Joachim Eibl committed
1063 1064
}

1065 1066
void MergeResultWindow::slotAutoSolve()
{
1067 1068 1069 1070 1071
    resetSelection();
    merge(true, -1);
    setModified(true);
    update();
    showUnsolvedConflictsStatusMessage();
Michael Reeves's avatar
Michael Reeves committed
1072 1073
}

1074 1075
void MergeResultWindow::slotUnsolve()
{
1076 1077 1078 1079 1080
    resetSelection();
    merge(false, -1);
    setModified(true);
    update();
    showUnsolvedConflictsStatusMessage();
Michael Reeves's avatar
Michael Reeves committed
1081 1082
}

1083
static QString calcHistoryLead(const QString& s)
1084
{
1085 1086 1087 1088 1089 1090 1091
    // Return the start of the line until the first white char after the first non white char.
    int i;
    for(i = 0; i < s.length(); ++i)
    {
        if(s[i] != ' ' && s[i] != '\t')
        {
            for(; i < s.length(); ++i)
1092
            {
1093 1094 1095 1096
                if(s[i] == ' ' || s[i] == '\t')
                {
                    return s.left(i);
                }
Michael Reeves's avatar
Michael Reeves committed
1097
            }
1098 1099 1100 1101
            return s; // Very unlikely
        }
    }
    return ""; // Must be an empty string, not a null string.
Michael Reeves's avatar
Michael Reeves committed
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
static void findHistoryRange(const QRegExp& historyStart, bool bThreeFiles, const Diff3LineList* pD3LList,
                             Diff3LineList::const_iterator& iBegin, Diff3LineList::const_iterator& iEnd, int& idxBegin, int& idxEnd)
{
    QString historyLead;
    // Search for start of history
    for(iBegin = pD3LList->begin(), idxBegin = 0; iBegin != pD3LList->end(); ++iBegin, ++idxBegin)
    {
        if(historyStart.exactMatch(iBegin->getString(A)) &&
           historyStart.exactMatch(iBegin->getString(B)) &&
           (!bThreeFiles || historyStart.exactMatch(iBegin->getString(C))))
        {
            historyLead = calcHistoryLead(iBegin->getString(A));
            break;
        }
    }
    // Search for end of history
    for(iEnd = iBegin, idxEnd = idxBegin; iEnd != pD3LList->end(); ++iEnd, ++idxEnd)
    {
        QString sA = iEnd->getString(A);
        QString sB = iEnd->getString(B);
        QString sC = iEnd->getString(C);
        if(!((sA.isEmpty() || historyLead == calcHistoryLead(sA)) &&
             (sB.isEmpty() || historyLead == calcHistoryLead(sB)) &&
             (!bThreeFiles || sC.isEmpty() || historyLead == calcHistoryLead(sC))))
        {
            break; // End of the history
        }
    }
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
bool findParenthesesGroups(const QString& s, QStringList& sl)
{
    sl.clear();
    int i = 0;
    std::list<int> startPosStack;
    int length = s.length();
    for(i = 0; i < length; ++i)
    {
        if(s[i] == '\\' && i + 1 < length && (s[i + 1] == '\\' || s[i + 1] == '(' || s[i + 1] == ')'))
        {
            ++i;
            continue;
        }
        if(s[i] == '(')
        {
            startPosStack.push_back(i);
        }
        else if(s[i] == ')')
        {
            if(startPosStack.empty())
                return false; // Parentheses don't match
            int startPos = startPosStack.back();
            startPosStack.pop_back();
            sl.push_back(s.mid(startPos + 1, i - startPos - 1));
        }
    }
    return startPosStack.empty(); // false if parentheses don't match
}

QString calcHistorySortKey(const QString& keyOrder, QRegExp& matchedRegExpr, const QStringList& parenthesesGroupList)
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
    QStringList keyOrderList = keyOrder.split(',');
    QString key;
    for(QStringList::iterator keyIt = keyOrderList.begin(); keyIt != keyOrderList.end(); ++keyIt)
    {
        if((*keyIt).isEmpty())
            continue;
        bool bOk = false;
        int groupIdx = (*keyIt).toInt(&bOk);
        if(!bOk || groupIdx < 0 || groupIdx > (int)parenthesesGroupList.size())
            continue;
        QString s = matchedRegExpr.cap(groupIdx);
        if(groupIdx == 0)
        {
            key += s + " ";
            continue;
        }

        QString groupRegExp = parenthesesGroupList[groupIdx - 1];
        if(groupRegExp.indexOf('|') < 0 || groupRegExp.indexOf('(') >= 0)
        {
            bool bOk = false;
            int i = s.toInt(&bOk);
            if(bOk && i >= 0 && i < 10000)
                s.sprintf("%04d", i); // This should help for correct sorting of numbers.
            key += s + " ";
        }
        else
        {
            // Assume that the groupRegExp consists of something like "Jan|Feb|Mar|Apr"
            // s is the string that managed to match.
            // Now we want to know at which position it occurred. e.g. Jan=0, Feb=1, Mar=2, etc.
            QStringList sl = groupRegExp.split('|');
            int idx = sl.indexOf(s);
            if(idx < 0)
1199
            {
1200
                // Didn't match
1201
            }
1202
            else
1203
            {
1204 1205 1206
                QString sIdx;
                sIdx.sprintf("%02d", idx + 1); // Up to 99 words in the groupRegExp (more than 12 aren't expected)
                key += sIdx + " ";
1207
            }
1208 1209 1210
        }
    }
    return key;
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
void MergeResultWindow::collectHistoryInformation(
    int src, Diff3LineList::const_iterator iHistoryBegin, Diff3LineList::const_iterator iHistoryEnd,
    HistoryMap& historyMap,
    std::list<HistoryMap::iterator>& hitList // list of iterators
    )
{
    std::list<HistoryMap::iterator>::iterator itHitListFront = hitList.begin();
    Diff3LineList::const_iterator id3l = iHistoryBegin;
    QString historyLead;
    {
        const LineData* pld = id3l->getLineData(src);
        QString s(pld->pLine, pld->size);
        historyLead = calcHistoryLead(s);
    }
    QRegExp historyStart(m_pOptions->m_historyStartRegExp);
    if(id3l == iHistoryEnd)
        return;
    ++id3l; // Skip line with "$Log ... $"
    QRegExp newHistoryEntry(m_pOptions->m_historyEntryStartRegExp);
    QStringList parenthesesGroups;
    findParenthesesGroups(m_pOptions->m_historyEntryStartRegExp, parenthesesGroups);
    QString key;
    MergeEditLineList melList;
    bool bPrevLineIsEmpty = true;
    bool bUseRegExp = !m_pOptions->m_historyEntryStartRegExp.isEmpty();
    for(; id3l != iHistoryEnd; ++id3l)
    {
        const LineData* pld = id3l->getLineData(src);
        if(!pld) continue;
        QString s(pld->pLine, pld->size);
        if(historyLead.isEmpty()) historyLead = calcHistoryLead(s);
        QString sLine = s.mid(historyLead.length());
        if((!bUseRegExp && !sLine.trimmed().isEmpty() && bPrevLineIsEmpty) || (bUseRegExp && newHistoryEntry.exactMatch(sLine)))
        {
            if(!key.isEmpty() && !melList.empty())
            {
                // Only insert new HistoryMapEntry if key not found; in either case p.first is a valid iterator to element key.
                std::pair<HistoryMap::iterator, bool> p = historyMap.insert(HistoryMap::value_type(key, HistoryMapEntry()));
                HistoryMapEntry& hme = p.first->second;
                if(src == A) hme.mellA = melList;
                if(src == B) hme.mellB = melList;
                if(src == C) hme.mellC = melList;
                if(p.second) // Not in list yet?
                {
                    hitList.insert(itHitListFront, p.first);
                }
            }
Joachim Eibl's avatar
Joachim Eibl committed
1260

1261 1262 1263 1264
            if(!bUseRegExp)
                key = sLine;
            else
                key = calcHistorySortKey(m_pOptions->m_historyEntryStartSortKeyOrder, newHistoryEntry, parenthesesGroups);
Joachim Eibl's avatar
Joachim Eibl committed
1265

1266 1267 1268 1269 1270 1271 1272
            melList.clear();
            melList.push_back(MergeEditLine(id3l, src));
        }
        else if(!historyStart.exactMatch(s))
        {
            melList.push_back(MergeEditLine(id3l, src));
        }
Joachim Eibl's avatar
Joachim Eibl committed
1273

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        bPrevLineIsEmpty = sLine.trimmed().isEmpty();
    }
    if(!key.isEmpty())
    {
        // Only insert new HistoryMapEntry if key not found; in either case p.first is a valid iterator to element key.
        std::pair<HistoryMap::iterator, bool> p = historyMap.insert(HistoryMap::value_type(key, HistoryMapEntry()));
        HistoryMapEntry& hme = p.first->second;
        if(src == A) hme.mellA = melList;
        if(src == B) hme.mellB = melList;
        if(src == C) hme.mellC = melList;
        if(p.second) // Not in list yet?
        {
            hitList.insert(itHitListFront, p.first);
        }
    }
    // End of the history
Joachim Eibl's avatar
Joachim Eibl committed
1290 1291
}

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
MergeResultWindow::MergeEditLineList& MergeResultWindow::HistoryMapEntry::choice(bool bThreeInputs)
{
    if(!bThreeInputs)
        return mellA.empty() ? mellB : mellA;
    else
    {
        if(mellA.empty())
            return mellC.empty() ? mellB : mellC; // A doesn't exist, return one that exists
        else if(!mellB.empty() && !mellC.empty())
        { // A, B and C exist
            return mellA;
        }
        else
            return mellB.empty() ? mellB : mellC; // A exists, return the one that doesn't exist
    }
1307 1308
}

1309
bool MergeResultWindow::HistoryMapEntry::staysInPlace(bool bThreeInputs, Diff3LineList::const_iterator& iHistoryEnd)
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
    // The entry should stay in place if the decision made by the automerger is correct.
    Diff3LineList::const_iterator& iHistoryLast = iHistoryEnd;
    --iHistoryLast;
    if(!bThreeInputs)
    {
        if(!mellA.empty() && !mellB.empty() && mellA.begin()->id3l() == mellB.begin()->id3l() &&
           mellA.back().id3l() == iHistoryLast && mellB.back().id3l() == iHistoryLast)
        {
            iHistoryEnd = mellA.begin()->id3l();
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        if(!mellA.empty() && !mellB.empty() && !mellC.empty() && mellA.begin()->id3l() == mellB.begin()->id3l() && mellA.begin()->id3l() == mellC.begin()->id3l() && mellA.back().id3l() == iHistoryLast && mellB.back().id3l() == iHistoryLast && mellC.back().id3l() == iHistoryLast)
        {
            iHistoryEnd = mellA.begin()->id3l();
            return true;
        }
        else
        {
            return false;
        }
    }
Michael Reeves's avatar
Michael Reeves committed
1339 1340
}

1341
void MergeResultWindow::slotMergeHistory()
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 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 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 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 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
    Diff3LineList::const_iterator iD3LHistoryBegin;
    Diff3LineList::const_iterator iD3LHistoryEnd;
    int d3lHistoryBeginLineIdx = -1;
    int d3lHistoryEndLineIdx = -1;

    // Search for history start, history end in the diff3LineList
    findHistoryRange(QRegExp(m_pOptions->m_historyStartRegExp), m_pldC != 0, m_pDiff3LineList, iD3LHistoryBegin, iD3LHistoryEnd, d3lHistoryBeginLineIdx, d3lHistoryEndLineIdx);

    if(iD3LHistoryBegin != m_pDiff3LineList->end())
    {
        // Now collect the historyMap information
        HistoryMap historyMap;
        std::list<HistoryMap::iterator> hitList;
        if(m_pldC == 0)
        {
            collectHistoryInformation(A, iD3LHistoryBegin, iD3LHistoryEnd, historyMap, hitList);
            collectHistoryInformation(B, iD3LHistoryBegin, iD3LHistoryEnd, historyMap, hitList);
        }
        else
        {
            collectHistoryInformation(A, iD3LHistoryBegin, iD3LHistoryEnd, historyMap, hitList);
            collectHistoryInformation(B, iD3LHistoryBegin, iD3LHistoryEnd, historyMap, hitList);
            collectHistoryInformation(C, iD3LHistoryBegin, iD3LHistoryEnd, historyMap, hitList);
        }

        Diff3LineList::const_iterator iD3LHistoryOrigEnd = iD3LHistoryEnd;

        bool bHistoryMergeSorting = m_pOptions->m_bHistoryMergeSorting && !m_pOptions->m_historyEntryStartSortKeyOrder.isEmpty() &&
                                    !m_pOptions->m_historyEntryStartRegExp.isEmpty();

        if(m_pOptions->m_maxNofHistoryEntries == -1)
        {
            // Remove parts from the historyMap and hitList that stay in place
            if(bHistoryMergeSorting)
            {
                while(!historyMap.empty())
                {
                    HistoryMap::iterator hMapIt = historyMap.begin();
                    if(hMapIt->second.staysInPlace(m_pldC != 0, iD3LHistoryEnd))
                        historyMap.erase(hMapIt);
                    else
                        break;
                }
            }
            else
            {
                while(!hitList.empty())
                {
                    HistoryMap::iterator hMapIt = hitList.back();
                    if(hMapIt->second.staysInPlace(m_pldC != 0, iD3LHistoryEnd))
                        hitList.pop_back();
                    else
                        break;
                }
            }
            while(iD3LHistoryOrigEnd != iD3LHistoryEnd)
            {
                --iD3LHistoryOrigEnd;
                --d3lHistoryEndLineIdx;
            }
        }

        MergeLineList::iterator iMLLStart = splitAtDiff3LineIdx(d3lHistoryBeginLineIdx);
        MergeLineList::iterator iMLLEnd = splitAtDiff3LineIdx(d3lHistoryEndLineIdx);
        // Now join all MergeLines in the history
        MergeLineList::iterator i = iMLLStart;
        if(i != iMLLEnd)
        {
            ++i;
            while(i != iMLLEnd)
            {
                iMLLStart->join(*i);
                i = m_mergeLineList.erase(i);
            }
        }
        iMLLStart->mergeEditLineList.clear();
        // Now insert the complete history into the first MergeLine of the history
        iMLLStart->mergeEditLineList.push_back(MergeEditLine(iD3LHistoryBegin, m_pldC == 0 ? B : C));
        QString lead = calcHistoryLead(iD3LHistoryBegin->getString(A));
        MergeEditLine mel(m_pDiff3LineList->end());
        mel.setString(lead);
        iMLLStart->mergeEditLineList.push_back(mel);

        int historyCount = 0;
        if(bHistoryMergeSorting)
        {
            // Create a sorted history
            HistoryMap::reverse_iterator hmit;
            for(hmit = historyMap.rbegin(); hmit != historyMap.rend(); ++hmit)
            {
                if(historyCount == m_pOptions->m_maxNofHistoryEntries)
                    break;
                ++historyCount;
                HistoryMapEntry& hme = hmit->second;
                MergeEditLineList& mell = hme.choice(m_pldC != 0);
                if(!mell.empty())
                    iMLLStart->mergeEditLineList.splice(iMLLStart->mergeEditLineList.end(), mell, mell.begin(), mell.end());
            }
        }
        else
        {
            // Create history in order of appearance
            std::list<HistoryMap::iterator>::iterator hlit;
            for(hlit = hitList.begin(); hlit != hitList.end(); ++hlit)
            {
                if(historyCount == m_pOptions->m_maxNofHistoryEntries)
                    break;
                ++historyCount;
                HistoryMapEntry& hme = (*hlit)->second;
                MergeEditLineList& mell = hme.choice(m_pldC != 0);
                if(!mell.empty())
                    iMLLStart->mergeEditLineList.splice(iMLLStart->mergeEditLineList.end(), mell, mell.begin(), mell.end());
            }
            // If the end of start is empty and the first line at the end is empty remove the last line of start
            if(!iMLLStart->mergeEditLineList.empty() && !iMLLEnd->mergeEditLineList.empty())
            {
                QString lastLineOfStart = iMLLStart->mergeEditLineList.back().getString(this);
                QString firstLineOfEnd = iMLLEnd->mergeEditLineList.front().getString(this);
                if(lastLineOfStart.mid(lead.length()).trimmed().isEmpty() && firstLineOfEnd.mid(lead.length()).trimmed().isEmpty())
                    iMLLStart->mergeEditLineList.pop_back();
            }
        }
        setFastSelector(iMLLStart);
        update();
    }
}

void MergeResultWindow::slotRegExpAutoMerge()
{
    if(m_pOptions->m_autoMergeRegExp.isEmpty())
        return;

    QRegExp vcsKeywords(m_pOptions->m_autoMergeRegExp);
    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if(i->bConflict)
        {
            Diff3LineList::const_iterator id3l = i->id3l;
            if(vcsKeywords.exactMatch(id3l->getString(A)) &&
               vcsKeywords.exactMatch(id3l->getString(B)) &&
               (m_pldC == 0 || vcsKeywords.exactMatch(id3l->getString(C))))
            {
                MergeEditLine& mel = *i->mergeEditLineList.begin();
                mel.setSource(m_pldC == 0 ? B : C, false);
                splitAtDiff3LineIdx(i->d3lLineIdx + 1);
            }
        }
    }
    update();
}

// This doesn't detect user modifications and should only be called after automatic merge
// This will only do something for three file merge.
// Irrelevant changes are those where all contributions from B are already contained in C.
// Also irrelevant are conflicts automatically solved (automerge regexp and history automerge)
// Precondition: The VCS-keyword would also be C.
bool MergeResultWindow::doRelevantChangesExist()
{
    if(m_pldC == 0 || m_mergeLineList.size() <= 1)
        return true;

    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if((i->bConflict && i->mergeEditLineList.begin()->src() != C) || i->srcSelect == B)
        {
            return true;
        }
    }

    return false;
}

// Returns the iterator to the MergeLine after the split
MergeResultWindow::MergeLineList::iterator MergeResultWindow::splitAtDiff3LineIdx(int d3lLineIdx)
{
    MergeLineList::iterator i;
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        if(i->d3lLineIdx == d3lLineIdx)
        {
            // No split needed, this is the beginning of a MergeLine
            return i;
        }
        else if(i->d3lLineIdx > d3lLineIdx)
        {
            // The split must be in the previous MergeLine
            --i;
            MergeLine& ml = *i;
            MergeLine newML;
            ml.split(newML, d3lLineIdx);
            ++i;
            return m_mergeLineList.insert(i, newML);
        }
    }
    // The split must be in the previous MergeLine
    --i;
    MergeLine& ml = *i;
    MergeLine newML;
    ml.split(newML, d3lLineIdx);
    ++i;
    return m_mergeLineList.insert(i, newML);
}

void MergeResultWindow::slotSplitDiff(int firstD3lLineIdx, int lastD3lLineIdx)
{
    if(lastD3lLineIdx >= 0)
        splitAtDiff3LineIdx(lastD3lLineIdx + 1);
    setFastSelector(splitAtDiff3LineIdx(firstD3lLineIdx));
}

void MergeResultWindow::slotJoinDiffs(int firstD3lLineIdx, int lastD3lLineIdx)
{
    MergeLineList::iterator i;
    MergeLineList::iterator iMLLStart = m_mergeLineList.end();
    MergeLineList::iterator iMLLEnd = m_mergeLineList.end();
    for(i = m_mergeLineList.begin(); i != m_mergeLineList.end(); ++i)
    {
        MergeLine& ml = *i;
        if(firstD3lLineIdx >= ml.d3lLineIdx && firstD3lLineIdx < ml.d3lLineIdx + ml.srcRangeLength)
        {
            iMLLStart = i;
        }
        if(lastD3lLineIdx >= ml.d3lLineIdx && lastD3lLineIdx < ml.d3lLineIdx + ml.srcRangeLength)
        {
            iMLLEnd = i;
            ++iMLLEnd;
            break;
        }
    }

    bool bJoined = false;
    for(i = iMLLStart; i != iMLLEnd && i != m_mergeLineList.end();)
    {
        if(i == iMLLStart)
        {
            ++i;
        }
        else
        {
            iMLLStart->join(*i);
            i = m_mergeLineList.erase(i);
            bJoined = true;
        }
    }
    if(bJoined)
    {
        iMLLStart->mergeEditLineList.clear();
        // Insert a conflict line as placeholder
        iMLLStart->mergeEditLineList.push_back(MergeEditLine(iMLLStart->id3l));
    }
    setFastSelector(iMLLStart);
}

void MergeResultWindow::myUpdate(int afterMilliSecs)
{
    if(m_delayedDrawTimer)
        killTimer(m_delayedDrawTimer);
    m_bMyUpdate = true;
    m_delayedDrawTimer = startTimer(afterMilliSecs);
}

void MergeResultWindow::timerEvent(QTimerEvent*)
{
    killTimer(m_delayedDrawTimer);
    m_delayedDrawTimer = 0;

    if(m_bMyUpdate)
    {
        update();
        m_bMyUpdate = false;
    }

    if(m_scrollDeltaX != 0 || m_scrollDeltaY != 0)
    {
        m_selection.end(m_selection.lastLine + m_scrollDeltaY, m_selection.lastPos + m_scrollDeltaX);
        emit scroll(m_scrollDeltaX, m_scrollDeltaY);
        killTimer(m_delayedDrawTimer);
        m_delayedDrawTimer = startTimer(50);
    }
}

QString MergeResultWindow::MergeEditLine::getString(const MergeResultWindow* mrw)
{
    if(isRemoved()) {
        return QString();
    }

    if(!isModified())
    {
        int src = m_src;
        if(src == 0) {
            return QString();
        }
        const Diff3Line& d3l = *m_id3l;
        const LineData* pld = 0;
        assert(src == A || src == B || src == C);
        if(src == A && d3l.lineA != -1)
            pld = &mrw->m_pldA[d3l.lineA];
        else if(src == B && d3l.lineB != -1)
            pld = &mrw->m_pldB[d3l.lineB];
        else if(src == C && d3l.lineC != -1)
            pld = &mrw->m_pldC[d3l.lineC];

        if(pld == 0)
        {
            // assert(false);      This is no error.
            return QString();
        }

        return QString(pld->pLine, pld->size);
    }
    else
    {
        return m_str;
    }
    return 0;
Joachim Eibl's avatar
Joachim Eibl committed
1661 1662 1663
}

/// Converts the cursor-posOnScreen into a text index, considering tabulators.
1664
int convertToPosInText(const QString& /*s*/, int posOnScreen, int /*tabSize*/)
1665
{
1666
    return posOnScreen;
1667
}
Joachim Eibl's avatar
Joachim Eibl committed
1668

1669 1670 1671 1672 1673 1674
//   int localPosOnScreen = 0;
//   int size=s.length();
//   for ( int i=0; i<size; ++i )
//   {
//      if ( localPosOnScreen>=posOnScreen )
//         return i;
Joachim Eibl's avatar
Joachim Eibl committed
1675

1676 1677
//      // All letters except tabulator have width one.
//      int letterWidth = s[i]!='\t' ? 1 : tabber( localPosOnScreen, tabSize );
Joachim Eibl's avatar
Joachim Eibl committed
1678

1679 1680 1681 1682 1683 1684 1685
//      localPosOnScreen += letterWidth;

//      if ( localPosOnScreen>posOnScreen )
//         return i;
//   }
//   return size;
//}
Joachim Eibl's avatar
Joachim Eibl committed
1686 1687

/// Converts the index into the text to a cursor-posOnScreen considering tabulators.
1688
int convertToPosOnScreen(const QString& /*p*/, int posInText, int /*tabSize*/)
1689
{
1690
    return posInText;
Joachim Eibl's avatar
Joachim Eibl committed
1691
}
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
//   int posOnScreen = 0;
//   for ( int i=0; i<posInText; ++i )
//   {
//      // All letters except tabulator have width one.
//      int letterWidth = p[i]!='\t' ? 1 : tabber( posOnScreen, tabSize );

//      posOnScreen += letterWidth;
//   }
//   return posOnScreen;
//}
Joachim Eibl's avatar
Joachim Eibl committed
1702

1703
QVector<QTextLayout::FormatRange> MergeResultWindow::getTextLayoutForLine(int line, const QString& str, QTextLayout& textLayout)
1704
{
Michael Reeves's avatar
Michael Reeves committed
1705 1706
    // tabs
    QTextOption textOption;
1707 1708
    textOption.setTabStop(QFontMetricsF(font()).width(' ') * m_pOptions->m_tabSize);
    if(m_pOptions->m_bShowWhiteSpaceCharacters)
Michael Reeves's avatar
Michael Reeves committed
1709
    {
1710
        textOption.setFlags(QTextOption::ShowTabsAndSpaces);
Michael Reeves's avatar
Michael Reeves committed
1711
    }
1712
    textLayout.setTextOption(textOption);
Michael Reeves's avatar
Michael Reeves committed
1713

1714
    if(m_pOptions->m_bShowWhiteSpaceCharacters)
Michael Reeves's avatar
Michael Reeves committed
1715
    {
Michael Reeves's avatar
Michael Reeves committed
1716
        // This additional format is only necessary for the tab arrow
1717
        QVector<QTextLayout::FormatRange> formats;
Michael Reeves's avatar
Michael Reeves committed
1718 1719 1720
        QTextLayout::FormatRange formatRange;
        formatRange.start = 0;
        formatRange.length = str.length();
1721 1722 1723
        formatRange.format.setFont(font());
        formats.append(formatRange);
        textLayout.setFormats(formats);
Michael Reeves's avatar
Michael Reeves committed
1724 1725 1726
    }
    QVector<QTextLayout::FormatRange> selectionFormat;
    textLayout.beginLayout();
1727
    if(m_selection.lineWithin(line))
Michael Reeves's avatar
Michael Reeves committed
1728
    {
1729 1730 1731 1732
        int firstPosInText = convertToPosInText(str, m_selection.firstPosInLine(line), m_pOptions->m_tabSize);
        int lastPosInText = convertToPosInText(str, m_selection.lastPosInLine(line), m_pOptions->m_tabSize);
        int lengthInText = max2(0, lastPosInText - firstPosInText);
        if(lengthInText > 0)
Michael Reeves's avatar
Michael Reeves committed
1733 1734 1735 1736 1737
            m_selection.bSelectionContainsData = true;

        QTextLayout::FormatRange selection;
        selection.start = firstPosInText;
        selection.length = lengthInText;
1738 1739 1740
        selection.format.setBackground(palette().highlight());
        selection.format.setForeground(palette().highlightedText().color());
        selectionFormat.push_back(selection);
Michael Reeves's avatar
Michael Reeves committed
1741 1742
    }
    QTextLine textLine = textLayout.createLine();
1743
    textLine.setPosition(QPointF(0, fontMetrics().leading()));
Michael Reeves's avatar
Michael Reeves committed
1744 1745
    textLayout.endLayout();
    int cursorWidth = 5;
1746 1747
    if(m_pOptions->m_bRightToLeftLanguage)
        textLayout.setPosition(QPointF(width() - textLayout.maximumWidth() - getTextXOffset() + m_horizScrollOffset - cursorWidth, 0));
Michael Reeves's avatar
Michael Reeves committed
1748
    else