File: patchhighlighter.cpp

package info (click to toggle)
kdevelop 4%3A5.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 52,544 kB
  • sloc: cpp: 254,897; python: 3,380; sh: 1,271; ansic: 657; xml: 221; php: 95; makefile: 36; lisp: 13; sed: 12
file content (691 lines) | stat: -rw-r--r-- 26,315 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/***************************************************************************
   Copyright 2006 David Nolden <david.nolden.kdevelop@art-master.de>
***************************************************************************/

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

#include "patchhighlighter.h"

#include <libkomparediff2/difference.h>
#include <libkomparediff2/diffmodel.h>

#include "patchreview.h"
#include "debug.h"

#include <KColorScheme>
#include <KIconEffect>
#include <KLocalizedString>
#include <KMessageBox>
#include <KParts/MainWindow>
#include <KTextEditor/View>
#include <KTextEditor/Cursor>

#include <KTextEditor/MovingInterface>
#include <KTextEditor/MarkInterface>

#include <interfaces/icore.h>
#include <interfaces/idocument.h>
#include <interfaces/iuicontroller.h>
#include <language/highlighting/colorcache.h>
#include <util/activetooltip.h>

#include <QApplication>
#include <QPointer>
#include <QTextBrowser>
#include <QTextDocument>
#include <QVBoxLayout>
#include <QWidget>

using namespace KDevelop;

namespace
{
QPointer<QWidget> currentTooltip;
KTextEditor::MovingRange* currentTooltipMark;


QSize sizeHintForHtml( const QString& html, QSize maxSize ) {
    QTextDocument doc;
    doc.setHtml( html );

    QSize ret;
    if( doc.idealWidth() > maxSize.width() ) {
        doc.setPageSize( QSize( maxSize.width(), 30 ) );
        ret.setWidth( maxSize.width() );
    }else{
        ret.setWidth( doc.idealWidth() );
    }
    ret.setHeight( doc.size().height() );
    if( ret.height() > maxSize.height() )
        ret.setHeight( maxSize.height() );
    return ret;
}

}

const unsigned int PatchHighlighter::m_allmarks =
    KTextEditor::MarkInterface::markType22 | KTextEditor::MarkInterface::markType23 |
    KTextEditor::MarkInterface::markType24 | KTextEditor::MarkInterface::markType25 |
    KTextEditor::MarkInterface::markType26 | KTextEditor::MarkInterface::markType27;

void PatchHighlighter::showToolTipForMark(const QPoint& pos, KTextEditor::MovingRange* markRange)
{
    if( currentTooltipMark == markRange && currentTooltip )
        return;
    delete currentTooltip;

    //Got the difference
    Diff2::Difference* diff = m_ranges[markRange];

    QString html;
#if 0
    if( diff->hasConflict() )
        html += i18n( "<b><span style=\"color:red\">Conflict</span></b><br/>" );
#endif

    Diff2::DifferenceStringList lines;

    html += QLatin1String("<b>");
    if( diff->applied() ) {
        if( !m_plugin->patch()->isAlreadyApplied() )
            html += i18n( "Applied.<br/>" );

        if( isInsertion( diff ) ) {
            html += i18n( "Insertion<br/>" );
        } else {
            if( isRemoval( diff ) )
                html += i18n( "Removal<br/>" );
            html += i18n( "Previous:<br/>" );
            lines = diff->sourceLines();
        }
    } else {
        if( m_plugin->patch()->isAlreadyApplied() )
            html += i18n( "Reverted.<br/>" );

        if( isRemoval( diff ) ) {
            html += i18n( "Removal<br/>" );
        } else {
            if( isInsertion( diff ) )
                html += i18n( "Insertion<br/>" );

            html += i18n( "Alternative:<br/>" );

            lines = diff->destinationLines();
        }
    }
    html += QLatin1String("</b>");

    for( int a = 0; a < lines.size(); ++a ) {
        Diff2::DifferenceString* line = lines[a];
        uint currentPos = 0;
        QString string = line->string();

        Diff2::MarkerList markers = line->markerList();

        for( int b = 0; b < markers.size(); ++b ) {
            QString spanText = string.mid( currentPos, markers[b]->offset() - currentPos ).toHtmlEscaped();
            if( markers[b]->type() == Diff2::Marker::End && ( currentPos != 0 || markers[b]->offset() != static_cast<uint>( string.size() ) ) )
            {
                html += QLatin1String("<b><span style=\"background:#FFBBBB\">") + spanText + QLatin1String("</span></b>");
            }else{
                html += spanText;
            }
            currentPos = markers[b]->offset();
        }

        html += string.mid(currentPos, string.length()-currentPos).toHtmlEscaped() + QLatin1String("<br/>");
    }

    auto browser = new QTextBrowser;
    browser->setPalette( QApplication::palette() );
    browser->setHtml( html );

    int maxHeight = 500;

    browser->setMinimumSize( sizeHintForHtml( html, QSize( ( ICore::self()->uiController()->activeMainWindow()->width()*2 )/3, maxHeight ) ) );
    browser->setMaximumSize( browser->minimumSize() + QSize( 10, 10 ) );
    if( browser->minimumHeight() != maxHeight )
        browser->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );

    QVBoxLayout* layout = new QVBoxLayout;
    layout->setMargin( 0 );
    layout->addWidget( browser );

    KDevelop::ActiveToolTip* tooltip = new KDevelop::ActiveToolTip( ICore::self()->uiController()->activeMainWindow(), pos + QPoint( 5, -browser->sizeHint().height() - 30 ) );
    tooltip->setLayout( layout );
    tooltip->resize( tooltip->sizeHint() + QSize( 10, 10 ) );
    tooltip->move( pos - QPoint( 0, 20 + tooltip->height() ) );
    tooltip->setHandleRect( QRect( pos - QPoint( 15, 15 ), pos + QPoint( 15, 15 ) ) );

    currentTooltip = tooltip;
    currentTooltipMark = markRange;

    ActiveToolTip::showToolTip( tooltip );
}

void PatchHighlighter::markClicked( KTextEditor::Document* doc, const KTextEditor::Mark& mark, bool& handled ) {
    if( handled || !(mark.type & m_allmarks) )
        return;

    auto range_diff = rangeForMark(mark);
    m_applying = true;

    if (range_diff.first) {
        handled = true;

        KTextEditor::MovingRange *&range = range_diff.first;
        Diff2::Difference *&diff = range_diff.second;

        QString currentText = doc->text( range->toRange() );

        removeLineMarker( range );

        QString sourceText;
        QString targetText;

        for( int a = 0; a < diff->sourceLineCount(); ++a ) {
            sourceText += diff->sourceLineAt( a )->string();
            if (!sourceText.endsWith(QLatin1Char('\n')))
                sourceText += QLatin1Char('\n');
        }

        for( int a = 0; a < diff->destinationLineCount(); ++a ) {
            targetText += diff->destinationLineAt( a )->string();
            if (!targetText.endsWith(QLatin1Char('\n')))
                targetText += QLatin1Char('\n');
        }

        bool applied = diff->applied();
        QString &replace(applied ? targetText : sourceText);
        QString &replaceWith(applied ? sourceText : targetText);

        if( currentText.simplified() != replace.simplified() ) {
            KMessageBox::error( ICore::self()->uiController()->activeMainWindow(), i18n( "Could not apply the change: Text should be \"%1\", but is \"%2\".", replace, currentText ) );

            m_applying = false;
            return;
        }

        diff->apply(!applied);

        KTextEditor::Cursor start = range->start().toCursor();
        range->document()->replaceText( range->toRange(), replaceWith );
        const uint replaceWithLines = replaceWith.count(QLatin1Char('\n'));
        KTextEditor::Range newRange( start, KTextEditor::Cursor(start.line() +  replaceWithLines, start.column()) );

        range->setRange( newRange );

        addLineMarker( range, diff );

        {
            // After applying the change, show the tooltip again, mainly to update an old tooltip
            delete currentTooltip;
            currentTooltip = nullptr;
            bool h = false;
            markToolTipRequested( doc, mark, QCursor::pos(), h );
        }
    }

    m_applying = false;
}

QPair<KTextEditor::MovingRange*, Diff2::Difference*> PatchHighlighter::rangeForMark( const KTextEditor::Mark &mark ) {
    if (!m_applying) {
        for( QMap<KTextEditor::MovingRange*, Diff2::Difference*>::const_iterator it = m_ranges.constBegin(); it != m_ranges.constEnd(); ++it ) {
            if (it.value() && it.key()->start().line() <= mark.line && mark.line <= it.key()->end().line()) {
                return qMakePair(it.key(), it.value());
            }
        }
    }

    return qMakePair(nullptr, nullptr);
}

void PatchHighlighter::markToolTipRequested( KTextEditor::Document*, const KTextEditor::Mark& mark, QPoint pos, bool& handled ) {
    if( handled )
        return;

    if( mark.type & m_allmarks ) {
        //There is a mark in this line. Show the old text.
        auto range = rangeForMark(mark);
        if( range.first ) {
            showToolTipForMark( pos, range.first );
            handled = true;
        }
    }
}

bool PatchHighlighter::isInsertion( Diff2::Difference* diff ) {
    return diff->sourceLineCount() == 0;
}

bool PatchHighlighter::isRemoval( Diff2::Difference* diff ) {
    return diff->destinationLineCount() == 0;
}

void PatchHighlighter::performContentChange( KTextEditor::Document* doc, const QStringList& oldLines, const QStringList& newLines, int editLineNumber ) {
    QPair<QList<Diff2::Difference*>, QList<Diff2::Difference*> > diffChange = m_model->linesChanged( oldLines, newLines, editLineNumber );
    QList<Diff2::Difference*> inserted = diffChange.first;
    QList<Diff2::Difference*> removed = diffChange.second;

    foreach(Diff2::Difference* d, removed) {
        foreach(Diff2::DifferenceString* s, d->sourceLines())
            qCDebug(PLUGIN_PATCHREVIEW) << "removed source" << s->string();
        foreach(Diff2::DifferenceString* s, d->destinationLines())
            qCDebug(PLUGIN_PATCHREVIEW) << "removed destination" << s->string();
    }
    foreach(Diff2::Difference* d, inserted) {
        foreach(Diff2::DifferenceString* s, d->sourceLines())
            qCDebug(PLUGIN_PATCHREVIEW) << "inserted source" << s->string();
        foreach(Diff2::DifferenceString* s, d->destinationLines())
            qCDebug(PLUGIN_PATCHREVIEW) << "inserted destination" << s->string();
    }

    // Remove all ranges that are in the same line (the line markers)
    for (auto it = m_ranges.begin(); it != m_ranges.end();) {
        if (removed.contains(it.value())) {
            KTextEditor::MovingRange* r = it.key();
            removeLineMarker(r); // is altering m_ranges
            it = m_ranges.erase(it);

            delete r;
        } else {
            ++it;
        }
    }
    qDeleteAll(removed);

    KTextEditor::MovingInterface* moving = dynamic_cast<KTextEditor::MovingInterface*>( doc );
    if ( !moving )
        return;

    foreach( Diff2::Difference* diff, inserted ) {
        int lineStart = diff->destinationLineNumber();
        if ( lineStart > 0 ) {
            --lineStart;
        }
        int lineEnd = diff->destinationLineEnd();
        if ( lineEnd > 0 ) {
            --lineEnd;
        }
        KTextEditor::Range newRange( lineStart, 0, lineEnd, 0 );
        KTextEditor::MovingRange * r = moving->newMovingRange( newRange );

        m_ranges[r] = diff;
        addLineMarker( r, diff );
    }
}

void PatchHighlighter::textRemoved( KTextEditor::Document* doc, const KTextEditor::Range& range, const QString& oldText ) {
    if ( m_applying ) { // Do not interfere with patch application
        return;
    }
    qCDebug(PLUGIN_PATCHREVIEW) << "removal range" << range;
    qCDebug(PLUGIN_PATCHREVIEW) << "removed text" << oldText;

    KTextEditor::Cursor cursor = range.start();
    int startLine = cursor.line();
    QStringList removedLines;
    QStringList remainingLines;
    if (startLine > 0) {
        QString above = doc->line(--startLine);
        removedLines << above;
        remainingLines << above;
    }
    const QString changed = doc->line(cursor.line()) + QLatin1Char('\n');
    removedLines << changed.midRef(0, cursor.column()) + oldText + changed.midRef(cursor.column());
    remainingLines << changed;
    if (doc->documentRange().end().line() > cursor.line()) {
        QString below = doc->line(cursor.line() + 1);
        removedLines << below;
        remainingLines << below;
    }

    performContentChange(doc, removedLines, remainingLines, startLine + 1);
}

void PatchHighlighter::newlineRemoved(KTextEditor::Document* doc, int line) {
    if ( m_applying ) { // Do not interfere with patch application
        return;
    }
    qCDebug(PLUGIN_PATCHREVIEW) << "remove newline" << line;

    KTextEditor::Cursor cursor = m_doc->cursorPosition();

    int startLine = line - 1;
    QStringList removedLines;
    QStringList remainingLines;
    if (startLine > 0) {
        QString above = doc->line(--startLine);
        removedLines << above;
        remainingLines << above;
    }
    QString changed = doc->line(line - 1);
    if (cursor.line() == line - 1) {
        removedLines << changed.mid(0, cursor.column());
        removedLines << changed.mid(cursor.column());
    } else {
        removedLines << changed;
        removedLines << QString();
    }
    remainingLines << changed;
    if (doc->documentRange().end().line() >= line) {
        QString below = doc->line(line);
        removedLines << below;
        remainingLines << below;
    }

    performContentChange(doc, removedLines, remainingLines, startLine + 1);
}

void PatchHighlighter::documentReloaded(KTextEditor::Document* doc)
{
    qCDebug(PLUGIN_PATCHREVIEW) << "re-doing";
    //The document was loaded / reloaded
    if ( !m_model->differences() )
        return;
    KTextEditor::MovingInterface* moving = dynamic_cast<KTextEditor::MovingInterface*>( doc );
    if ( !moving )
        return;

    KTextEditor::MarkInterface* markIface = dynamic_cast<KTextEditor::MarkInterface*>( doc );
    if( !markIface )
        return;

    clear();

    KColorScheme scheme( QPalette::Active );

    QImage tintedInsertion = QIcon::fromTheme( QStringLiteral("insert-text") ).pixmap( 16, 16 ).toImage();
    KIconEffect::colorize( tintedInsertion, scheme.foreground( KColorScheme::NegativeText ).color(), 1.0 );
    QImage tintedRemoval = QIcon::fromTheme( QStringLiteral("edit-delete") ).pixmap( 16, 16 ).toImage();
    KIconEffect::colorize( tintedRemoval, scheme.foreground( KColorScheme::NegativeText ).color(), 1.0 );
    QImage tintedChange = QIcon::fromTheme( QStringLiteral("text-field") ).pixmap( 16, 16 ).toImage();
    KIconEffect::colorize( tintedChange, scheme.foreground( KColorScheme::NegativeText ).color(), 1.0 );

    markIface->setMarkDescription( KTextEditor::MarkInterface::markType22, i18n( "Insertion" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType22, QPixmap::fromImage( tintedInsertion ) );
    markIface->setMarkDescription( KTextEditor::MarkInterface::markType23, i18n( "Removal" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType23, QPixmap::fromImage( tintedRemoval ) );
    markIface->setMarkDescription( KTextEditor::MarkInterface::markType24, i18n( "Change" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType24, QPixmap::fromImage( tintedChange ) );

    markIface->setMarkDescription( KTextEditor::MarkInterface::markType25, i18n( "Insertion" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType25, QIcon::fromTheme( QStringLiteral("insert-text") ).pixmap( 16, 16 ) );
    markIface->setMarkDescription( KTextEditor::MarkInterface::markType26, i18n( "Removal" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType26, QIcon::fromTheme( QStringLiteral("edit-delete") ).pixmap( 16, 16 ) );
    markIface->setMarkDescription( KTextEditor::MarkInterface::markType27, i18n( "Change" ) );
    markIface->setMarkPixmap( KTextEditor::MarkInterface::markType27, QIcon::fromTheme( QStringLiteral("text-field") ).pixmap( 16, 16 ) );

    for ( Diff2::DifferenceList::const_iterator it = m_model->differences()->constBegin(); it != m_model->differences()->constEnd(); ++it ) {
        Diff2::Difference* diff = *it;
        int line, lineCount;
        Diff2::DifferenceStringList lines;

        if( diff->applied() ) {
            line = diff->destinationLineNumber();
            lineCount = diff->destinationLineCount();
            lines = diff->destinationLines();
        } else {
            line = diff->sourceLineNumber();
            lineCount = diff->sourceLineCount();
            lines = diff->sourceLines();
        }

        if ( line > 0 )
            line -= 1;

        KTextEditor::Cursor c( line, 0 );
        KTextEditor::Cursor endC( line + lineCount, 0 );
        if ( doc->lines() <= c.line() )
            c.setLine( doc->lines() - 1 );
        if ( doc->lines() <= endC.line() )
            endC.setLine( doc->lines() );

        if ( endC.isValid() && c.isValid() ) {
            KTextEditor::MovingRange * r = moving->newMovingRange( KTextEditor::Range( c, endC ) );
            m_ranges[r] = diff;
            addLineMarker( r, diff );
        }
    }
}

void PatchHighlighter::textInserted(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor, const QString& text) {
    if ( m_applying ) { // Do not interfere with patch application
        return;
    }

    int startLine = cursor.line();
    int endColumn = cursor.column() + text.length();

    qCDebug(PLUGIN_PATCHREVIEW) << "insertion range" <<
        KTextEditor::Range(cursor, KTextEditor::Cursor(startLine, endColumn));
    qCDebug(PLUGIN_PATCHREVIEW) << "inserted text" << text;

    QStringList removedLines;
    QStringList insertedLines;
    if (startLine > 0) {
        const QString above = doc->line(--startLine) + QLatin1Char('\n');
        removedLines << above;
        insertedLines << above;
    }
    const QString changed = doc->line(cursor.line()) + QLatin1Char('\n');
    removedLines << changed.midRef(0, cursor.column()) + changed.midRef(endColumn);
    insertedLines << changed;
    if (doc->documentRange().end().line() > cursor.line()) {
        const QString below = doc->line(cursor.line() + 1) + QLatin1Char('\n');
        removedLines << below;
        insertedLines << below;
    }

    performContentChange(doc, removedLines, insertedLines, startLine + 1);
}

void PatchHighlighter::newlineInserted(KTextEditor::Document* doc, const KTextEditor::Cursor& cursor)
{
    if ( m_applying ) { // Do not interfere with patch application
        return;
    }
    qCDebug(PLUGIN_PATCHREVIEW) << "newline range" <<
        KTextEditor::Range(cursor, KTextEditor::Cursor(cursor.line() + 1, 0));

    int startLine = cursor.line();
    QStringList removedLines;
    QStringList insertedLines;
    if (startLine > 0) {
        const QString above = doc->line(--startLine) + QLatin1Char('\n');
        removedLines << above;
        insertedLines << above;
    }
    insertedLines << QStringLiteral("\n");
    if (doc->documentRange().end().line() > cursor.line()) {
        const QString below = doc->line(cursor.line() + 1) + QLatin1Char('\n');
        removedLines << below;
        insertedLines << below;
    }

    performContentChange(doc, removedLines, insertedLines, startLine + 1);
}

PatchHighlighter::PatchHighlighter( Diff2::DiffModel* model, IDocument* kdoc, PatchReviewPlugin* plugin, bool updatePatchFromEdits )
    : m_doc( kdoc ), m_plugin( plugin ), m_model( model ), m_applying( false ) {
    KTextEditor::Document* doc = kdoc->textDocument();
//     connect( kdoc, SIGNAL(destroyed(QObject*)), this, SLOT(documentDestroyed()) );
    if (updatePatchFromEdits) {
        connect(doc, &KTextEditor::Document::textInserted, this, &PatchHighlighter::textInserted);
        connect(doc, &KTextEditor::Document::lineWrapped, this, &PatchHighlighter::newlineInserted);
        connect(doc, &KTextEditor::Document::textRemoved, this, &PatchHighlighter::textRemoved);
        connect(doc, &KTextEditor::Document::lineUnwrapped, this, &PatchHighlighter::newlineRemoved);
    }
    connect(doc, &KTextEditor::Document::reloaded, this, &PatchHighlighter::documentReloaded);
    connect(doc, &KTextEditor::Document::destroyed, this, &PatchHighlighter::documentDestroyed);

    if ( doc->lines() == 0 )
        return;

    if (qobject_cast<KTextEditor::MarkInterface*>(doc)) {
        //can't use new signal/slot syntax here, MarkInterface is not a QObject
        connect(doc, SIGNAL(markToolTipRequested(KTextEditor::Document*,KTextEditor::Mark,QPoint,bool&)),
                this, SLOT(markToolTipRequested(KTextEditor::Document*,KTextEditor::Mark,QPoint,bool&)));
        connect(doc, SIGNAL(markClicked(KTextEditor::Document*,KTextEditor::Mark,bool&)),
                this, SLOT(markClicked(KTextEditor::Document*,KTextEditor::Mark,bool&)));
    }
    if (qobject_cast<KTextEditor::MovingInterface*>(doc)) {
        //can't use new signal/slot syntax here, MovingInterface is not a QObject
        connect(doc, SIGNAL(aboutToDeleteMovingInterfaceContent(KTextEditor::Document*)),
                this, SLOT(aboutToDeleteMovingInterfaceContent(KTextEditor::Document*)));
        connect(doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)),
                this, SLOT(aboutToDeleteMovingInterfaceContent(KTextEditor::Document*)));
    }

    documentReloaded(doc);
}

void PatchHighlighter::removeLineMarker( KTextEditor::MovingRange* range ) {
    KTextEditor::MovingInterface* moving = dynamic_cast<KTextEditor::MovingInterface*>( range->document() );
    if ( !moving )
        return;

    KTextEditor::MarkInterface* markIface = dynamic_cast<KTextEditor::MarkInterface*>( range->document() );
    if( !markIface )
        return;

    for (int line = range->start().line(); line <= range->end().line(); ++line) {
        markIface->removeMark(line, m_allmarks);
    }

    // Remove all ranges that are in the same line (the line markers)
    for (auto it = m_ranges.begin(); it != m_ranges.end();) {
        if (it.key() != range && range->overlaps(it.key()->toRange())) {
            delete it.key();
            it = m_ranges.erase(it);
        } else {
            ++it;
        }
    }
}

void PatchHighlighter::addLineMarker( KTextEditor::MovingRange* range, Diff2::Difference* diff ) {
    KTextEditor::MovingInterface* moving = dynamic_cast<KTextEditor::MovingInterface*>( range->document() );
    if ( !moving )
        return;

    KTextEditor::MarkInterface* markIface = dynamic_cast<KTextEditor::MarkInterface*>( range->document() );
    if( !markIface )
        return;

    KTextEditor::Attribute::Ptr t( new KTextEditor::Attribute() );

    bool isOriginalState = diff->applied() == m_plugin->patch()->isAlreadyApplied();

    if( isOriginalState ) {
        t->setProperty( QTextFormat::BackgroundBrush, QBrush( ColorCache::self()->blendBackground( QColor( 0, 255, 255 ), 20 ) ) );
    }else{
        t->setProperty( QTextFormat::BackgroundBrush, QBrush( ColorCache::self()->blendBackground( QColor( 255, 0, 255 ), 20 ) ) );
    }
    range->setAttribute( t );
    range->setZDepth( -500 );

    KTextEditor::MarkInterface::MarkTypes mark;

    if( isOriginalState ) {
        mark = KTextEditor::MarkInterface::markType27;

        if( isInsertion( diff ) )
            mark = KTextEditor::MarkInterface::markType25;
        if( isRemoval( diff ) )
            mark = KTextEditor::MarkInterface::markType26;
    }else{
        mark = KTextEditor::MarkInterface::markType24;

        if( isInsertion( diff ) )
            mark = KTextEditor::MarkInterface::markType22;
        if( isRemoval( diff ) )
            mark = KTextEditor::MarkInterface::markType23;
    }

    markIface->addMark( range->start().line(), mark );

    Diff2::DifferenceStringList lines;
    if( diff->applied() )
        lines = diff->destinationLines();
    else
        lines = diff->sourceLines();

    for( int a = 0; a < lines.size(); ++a ) {
        Diff2::DifferenceString* line = lines[a];
        int currentPos = 0;
        QString string = line->string();

        Diff2::MarkerList markers = line->markerList();

        for( int b = 0; b < markers.size(); ++b ) {
            if( markers[b]->type() == Diff2::Marker::End )
            {
                if( currentPos != 0 || markers[b]->offset() != static_cast<uint>( string.size() ) )
                {
                    KTextEditor::MovingRange * r2 = moving->newMovingRange( KTextEditor::Range( KTextEditor::Cursor( a + range->start().line(), currentPos ), KTextEditor::Cursor( a + range->start().line(), markers[b]->offset() ) ) );
                    m_ranges[r2] = nullptr;

                    KTextEditor::Attribute::Ptr t( new KTextEditor::Attribute() );

                    t->setProperty( QTextFormat::BackgroundBrush, QBrush( ColorCache::self()->blendBackground( QColor( 255, 0, 0 ), 70 ) ) );
                    r2->setAttribute( t );
                    r2->setZDepth( -600 );
                }
            }
            currentPos = markers[b]->offset();
        }
    }
}

void PatchHighlighter::clear() {
    if( m_ranges.empty() )
        return;

    KTextEditor::MovingInterface* moving = dynamic_cast<KTextEditor::MovingInterface*>( m_doc->textDocument() );
    if ( !moving )
        return;

    KTextEditor::MarkInterface* markIface = dynamic_cast<KTextEditor::MarkInterface*>( m_doc->textDocument() );
    if( !markIface )
        return;

    foreach( int line, markIface->marks().keys() ) {
        markIface->removeMark( line, m_allmarks );
    }

    // Diff is taking care of its own objects (except removed ones)
    qDeleteAll( m_ranges.keys() );
    m_ranges.clear();
}

PatchHighlighter::~PatchHighlighter() {
    clear();
}

IDocument* PatchHighlighter::doc() {
    return m_doc;
}

void PatchHighlighter::documentDestroyed() {
    qCDebug(PLUGIN_PATCHREVIEW) << "document destroyed";
    m_ranges.clear();
}

void PatchHighlighter::aboutToDeleteMovingInterfaceContent( KTextEditor::Document* ) {
    qCDebug(PLUGIN_PATCHREVIEW) << "about to delete";
    clear();
}

QList< KTextEditor::MovingRange* > PatchHighlighter::ranges() const
{
    return m_ranges.keys();
}