File: abstractlogview.cpp

package info (click to toggle)
glogg 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 832 kB
  • sloc: cpp: 6,649; sh: 66; perl: 32; sed: 25; makefile: 11
file content (1097 lines) | stat: -rw-r--r-- 35,526 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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
/*
 * Copyright (C) 2009, 2010, 2011 Nicolas Bonnefon and other contributors
 *
 * This file is part of glogg.
 *
 * glogg 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 3 of the License, or
 * (at your option) any later version.
 *
 * glogg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with glogg.  If not, see <http://www.gnu.org/licenses/>.
 */

// This file implements the AbstractLogView base class.
// Most of the actual drawing and event management common to the two views
// is implemented in this class.  The class only calls protected virtual
// functions when view specific behaviour is desired, using the template
// pattern.

#include <iostream>

#include <QApplication>
#include <QClipboard>
#include <QFile>
#include <QRect>
#include <QPaintEvent>
#include <QPainter>
#include <QFontMetrics>
#include <QScrollBar>

#include "log.h"

#include "persistentinfo.h"
#include "filterset.h"
#include "logmainview.h"
#include "quickfind.h"
#include "quickfindpattern.h"
#include "overview.h"


LineChunk::LineChunk( int first_col, int last_col, ChunkType type )
{
    // LOG(logDEBUG) << "new LineChunk: " << first_col << " " << last_col;

    start_ = first_col;
    end_   = last_col;
    type_  = type;
}

QList<LineChunk> LineChunk::select( int sel_start, int sel_end ) const
{
    QList<LineChunk> list;

    if ( ( sel_start < start_ ) && ( sel_end < start_ ) ) {
        // Selection BEFORE this chunk: no change
        list << LineChunk( *this );
    }
    else if ( sel_start > end_ ) {
        // Selection AFTER this chunk: no change
        list << LineChunk( *this );
    }
    else /* if ( ( sel_start >= start_ ) && ( sel_end <= end_ ) ) */
    {
        // We only want to consider what's inside THIS chunk
        sel_start = qMax( sel_start, start_ );
        sel_end   = qMin( sel_end, end_ );

        if ( sel_start > start_ )
            list << LineChunk( start_, sel_start - 1, type_ );
        list << LineChunk( sel_start, sel_end, Selected );
        if ( sel_end < end_ )
            list << LineChunk( sel_end + 1, end_, type_ );
    }

    return list;
}

inline void LineDrawer::addChunk( int first_col, int last_col,
        QColor fore, QColor back )
{
    if ( first_col < 0 )
        first_col = 0;
    int length = last_col - first_col + 1;
    if ( length > 0 ) {
        list << Chunk ( first_col, length, fore, back );
    }
}

inline void LineDrawer::addChunk( const LineChunk& chunk,
        QColor fore, QColor back )
{
    int first_col = chunk.start();
    int last_col  = chunk.end();

    addChunk( first_col, last_col, fore, back );
}

inline void LineDrawer::draw( QPainter& painter,
        int xPos, int yPos, int line_width, const QString& line )
{
    QFontMetrics fm = painter.fontMetrics();
    const int fontHeight = fm.height();
    const int fontAscent = fm.ascent();

    foreach ( Chunk chunk, list ) {
        // Draw each chunk
        // LOG(logDEBUG) << "Chunk: " << chunk.start() << " " << chunk.length();
        QString cutline = line.mid( chunk.start(), chunk.length() );
        const int chunk_width = fm.width( cutline );
        painter.fillRect( xPos, yPos, chunk_width,
                fontHeight, chunk.backColor() );
        painter.setPen( chunk.foreColor() );
        painter.drawText( xPos, yPos + fontAscent, cutline );
        xPos += chunk_width;
    }

    // Draw the empty block at the end of the line
    int blank_width = line_width - xPos;

    if ( blank_width > 0 )
        painter.fillRect( xPos, yPos, blank_width, fontHeight, backColor_ );
}

const int DigitsBuffer::timeout_ = 2000;

DigitsBuffer::DigitsBuffer() : QObject()
{
}

void DigitsBuffer::reset()
{
    LOG(logDEBUG) << "DigitsBuffer::reset()";

    timer_.stop();
    digits_.clear();
}

void DigitsBuffer::add( char character )
{
    LOG(logDEBUG) << "DigitsBuffer::add()";

    digits_.append( QChar( character ) );
    timer_.start( timeout_ , this );
}

int DigitsBuffer::content()
{
    int result = digits_.toInt();
    reset();

    return result;
}

void DigitsBuffer::timerEvent( QTimerEvent* event )
{
    if ( event->timerId() == timer_.timerId() ) {
        reset();
    }
    else {
        QObject::timerEvent( event );
    }
}

// Graphic parameters

// Looks better with an odd value
const int AbstractLogView::bulletLineX_ = 11;
const int AbstractLogView::leftMarginPx_ = bulletLineX_ + 2;

const int AbstractLogView::OVERVIEW_WIDTH = 27;

AbstractLogView::AbstractLogView(const AbstractLogData* newLogData,
        const QuickFindPattern* const quickFindPattern, QWidget* parent) :
    QAbstractScrollArea( parent ),
    selectionStartPos_(),
    selectionCurrentEndPos_(),
    autoScrollTimer_(),
    selection_(),
    quickFindPattern_( quickFindPattern ),
    quickFind_( newLogData, &selection_, quickFindPattern ),
    overviewWidget_( this )
{
    logData = newLogData;

    followMode_ = false;

    selectionStarted_ = false;
    markingClickInitiated_ = false;

    firstLine = 0;
    lastLine = 0;
    firstCol = 0;

    overview_ = NULL;

    // Fonts
    useFixedFont_ = false;
    charWidth_ = 1;
    charHeight_ = 1;

    // Create the viewport QWidget
    setViewport( 0 );

    setAttribute( Qt::WA_StaticContents );  // Does it work?

    // Signals
    connect( quickFindPattern_, SIGNAL( patternUpdated() ),
            this, SLOT ( handlePatternUpdated() ) );
    connect( verticalScrollBar(), SIGNAL( sliderMoved( int ) ),
            this, SIGNAL( followDisabled() ) );
    connect( &quickFind_, SIGNAL( notify( const QString& ) ),
            this, SIGNAL( notifyQuickFind( const QString& ) ) );
    connect( &quickFind_, SIGNAL( clearNotification() ),
            this, SIGNAL( clearQuickFindNotification() ) );
    connect( &overviewWidget_, SIGNAL( lineClicked ( int ) ),
            this, SIGNAL( followDisabled() ) );
    connect( &overviewWidget_, SIGNAL( lineClicked ( int ) ),
            this, SLOT( jumpToLine( int ) ) );
}

AbstractLogView::~AbstractLogView()
{
}


//
// Received events
//

void AbstractLogView::changeEvent( QEvent* changeEvent )
{
    QAbstractScrollArea::changeEvent( changeEvent );

    // Stop the timer if the widget becomes inactive
    if ( changeEvent->type() == QEvent::ActivationChange ) {
        if ( ! isActiveWindow() )
            autoScrollTimer_.stop();
    }
    viewport()->update();
}

void AbstractLogView::mousePressEvent( QMouseEvent* mouseEvent )
{
    // Selection implementation
    if ( mouseEvent->button() == Qt::LeftButton )
    {
        int line = convertCoordToLine( mouseEvent->y() );

        if ( mouseEvent->x() < leftMarginPx_ ) {
            // Mark a line if it is clicked in the left margin
            // (only if click and release in the same area)
            markingClickInitiated_ = true;
            markingClickLine_ = line;
        }
        else {
            // Select the line, and start a selection
            if ( line < logData->getNbLine() ) {
                selection_.selectLine( line );
                emit updateLineNumber( line );
                emit newSelection( line );
            }

            // Remember the click in case we're starting a selection
            selectionStarted_ = true;
            selectionStartPos_ = convertCoordToFilePos( mouseEvent->pos() );
            selectionCurrentEndPos_ = selectionStartPos_;
        }
    }
}

void AbstractLogView::mouseMoveEvent( QMouseEvent* mouseEvent )
{
    // Selection implementation
    if ( selectionStarted_ )
    {
        QPoint thisEndPos = convertCoordToFilePos( mouseEvent->pos() );
        if ( thisEndPos != selectionCurrentEndPos_ )
        {
            // Are we on a different line?
            if ( selectionStartPos_.y() != thisEndPos.y() )
            {
                if ( thisEndPos.y() != selectionCurrentEndPos_.y() )
                {
                    // This is a 'range' selection
                    selection_.selectRange( selectionStartPos_.y(),
                            thisEndPos.y() );
                    emit updateLineNumber( thisEndPos.y() );
                    update();
                }
            }
            // So we are on the same line. Are we moving horizontaly?
            else if ( thisEndPos.x() != selectionCurrentEndPos_.x() )
            {
                // This is a 'portion' selection
                selection_.selectPortion( thisEndPos.y(),
                        selectionStartPos_.x(), thisEndPos.x() );
                update();
            }
            // On the same line, and moving vertically then
            else
            {
                // This is a 'line' selection
                selection_.selectLine( thisEndPos.y() );
                emit updateLineNumber( thisEndPos.y() );
                update();
            }
            selectionCurrentEndPos_ = thisEndPos;

            // Do we need to scroll while extending the selection?
            QRect visible = viewport()->rect();
            if ( visible.contains( mouseEvent->pos() ) )
                autoScrollTimer_.stop();
            else if ( ! autoScrollTimer_.isActive() )
                autoScrollTimer_.start( 100, this );
        }
    }
}

void AbstractLogView::mouseReleaseEvent( QMouseEvent* mouseEvent )
{
    if ( markingClickInitiated_ ) {
        markingClickInitiated_ = false;
        int line = convertCoordToLine( mouseEvent->y() );
        if ( line == markingClickLine_ )
            emit markLine( line );
    }
    else {
        selectionStarted_ = false;
        if ( autoScrollTimer_.isActive() )
            autoScrollTimer_.stop();
        updateGlobalSelection();
    }
}

void AbstractLogView::mouseDoubleClickEvent( QMouseEvent* mouseEvent )
{
    if ( mouseEvent->button() == Qt::LeftButton )
    {
        const QPoint pos = convertCoordToFilePos( mouseEvent->pos() );
        selectWordAtPosition( pos );
    }
}

void AbstractLogView::timerEvent( QTimerEvent* timerEvent )
{
    if ( timerEvent->timerId() == autoScrollTimer_.timerId() ) {
        QRect visible = viewport()->rect();
        const QPoint globalPos = QCursor::pos();
        const QPoint pos = viewport()->mapFromGlobal( globalPos );
        QMouseEvent ev( QEvent::MouseMove, pos, globalPos, Qt::LeftButton,
                Qt::LeftButton, Qt::NoModifier );
        mouseMoveEvent( &ev );
        int deltaX = qMax( pos.x() - visible.left(),
                visible.right() - pos.x() ) - visible.width();
        int deltaY = qMax( pos.y() - visible.top(),
                visible.bottom() - pos.y() ) - visible.height();
        int delta = qMax( deltaX, deltaY );

        if ( delta >= 0 ) {
            if ( delta < 7 )
                delta = 7;
            int timeout = 4900 / ( delta * delta );
            autoScrollTimer_.start( timeout, this );

            if ( deltaX > 0 )
                horizontalScrollBar()->triggerAction(
                        pos.x() <visible.center().x() ?
                        QAbstractSlider::SliderSingleStepSub :
                        QAbstractSlider::SliderSingleStepAdd );

            if ( deltaY > 0 )
                verticalScrollBar()->triggerAction(
                        pos.y() <visible.center().y() ?
                        QAbstractSlider::SliderSingleStepSub :
                        QAbstractSlider::SliderSingleStepAdd );
        }
    }
    QAbstractScrollArea::timerEvent( timerEvent );
}

void AbstractLogView::keyPressEvent( QKeyEvent* keyEvent )
{
    LOG(logDEBUG4) << "keyPressEvent received";

    if ( keyEvent->key() == Qt::Key_Left )
        horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
    else if ( keyEvent->key() == Qt::Key_Right )
        horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
    else if ( keyEvent->key() == Qt::Key_Home )
        jumpToStartOfLine();
    else if ( keyEvent->key() == Qt::Key_End )
        jumpToRightOfScreen();
    else {
        const char character = (keyEvent->text())[0].toAscii();

        if ( ( character >= '0' ) && ( character <= '9' ) ) {
            // Adds the digit to the timed buffer
            digitsBuffer_.add( character );
        }
        else {
            switch ( (keyEvent->text())[0].toAscii() ) {
                case 'j':
                    {
                        int delta = qMax( 1, digitsBuffer_.content() );
                        emit followDisabled();
                        //verticalScrollBar()->triggerAction(
                        //QScrollBar::SliderSingleStepAdd);
                        moveSelection( delta );
                        break;
                    }
                case 'k':
                    {
                        int delta = qMin( -1, - digitsBuffer_.content() );
                        emit followDisabled();
                        //verticalScrollBar()->triggerAction(
                        //QScrollBar::SliderSingleStepSub);
                        moveSelection( delta );
                        break;
                    }
                case 'h':
                    horizontalScrollBar()->triggerAction(
                            QScrollBar::SliderSingleStepSub);
                    break;
                case 'l':
                    horizontalScrollBar()->triggerAction(
                            QScrollBar::SliderSingleStepAdd);
                    break;
                case '0':
                    jumpToStartOfLine();
                    break;
                case '$':
                    jumpToEndOfLine();
                    break;
                case 'g':
                    {
                        int newLine = qMax( 0, digitsBuffer_.content() - 1 );
                        if ( newLine >= logData->getNbLine() )
                            newLine = logData->getNbLine() - 1;
                        emit followDisabled();
                        selectAndDisplayLine( newLine );
                        emit updateLineNumber( newLine );
                        break;
                    }
                case 'G':
                    emit followDisabled();
                    selection_.selectLine( logData->getNbLine() - 1 );
                    emit updateLineNumber( logData->getNbLine() - 1 );
                    jumpToBottom();
                    break;
                case 'n':
                    searchNext();
                    break;
                case 'N':
                    searchPrevious();
                    break;
                case '*':
                    // Use the selected 'word' and search forward
                    if ( selection_.isPortion() ) {
                        emit changeQuickFind(
                                selection_.getSelectedText( logData ) );
                        searchNext();
                    }
                    break;
                case '#':
                    // Use the selected 'word' and search backward
                    if ( selection_.isPortion() ) {
                        emit changeQuickFind(
                                selection_.getSelectedText( logData ) );
                        searchPrevious();
                    }
                    break;
                default:
                    keyEvent->ignore();
            }
        }
    }

    if ( !keyEvent->isAccepted() )
        QAbstractScrollArea::keyPressEvent( keyEvent );
}

void AbstractLogView::wheelEvent( QWheelEvent* wheelEvent )
{
    emit followDisabled();

    QAbstractScrollArea::wheelEvent( wheelEvent );
}

void AbstractLogView::resizeEvent( QResizeEvent* )
{
    if ( logData == NULL )
        return;

    LOG(logDEBUG) << "resizeEvent received";

    updateDisplaySize();
}

void AbstractLogView::scrollContentsBy( int dx, int dy )
{
    LOG(logDEBUG4) << "scrollContentsBy received";

    firstLine = (firstLine - dy) > 0 ? firstLine - dy : 0;
    firstCol  = (firstCol - dx) > 0 ? firstCol - dx : 0;
    lastLine = qMin( logData->getNbLine(), firstLine + getNbVisibleLines() );

    // Update the overview if we have one
    if ( overview_ != NULL )
        overview_->updateCurrentPosition( firstLine, lastLine );

    // Redraw
    update();
}

void AbstractLogView::paintEvent( QPaintEvent* paintEvent )
{
    QRect invalidRect = paintEvent->rect();
    if ( (invalidRect.isEmpty()) || (logData == NULL) )
        return;

    LOG(logDEBUG4) << "paintEvent received, firstLine=" << firstLine
        << " lastLine=" << lastLine <<
        " rect: " << invalidRect.topLeft().x() <<
        ", " << invalidRect.topLeft().y() <<
        ", " << invalidRect.bottomRight().x() <<
        ", " << invalidRect.bottomRight().y();

    {
        // Repaint the viewport
        QPainter painter( viewport() );
        const int fontHeight = painter.fontMetrics().height();
        const int fontAscent = painter.fontMetrics().ascent();
        const int nbCols = getNbVisibleCols();
        const QPalette& palette = viewport()->palette();
        const FilterSet& filterSet = Persistent<FilterSet>( "filterSet" );
        QColor foreColor, backColor;

        static const QBrush normalBulletBrush = QBrush( Qt::white );
        static const QBrush matchBulletBrush = QBrush( Qt::red );
        static const QBrush markBrush = QBrush( "dodgerblue" );

        // First check the lines to be drawn are within range (might not be the case if
        // the file has just changed)
        const int nbLines = logData->getNbLine();
        if ( nbLines == 0 ) {
            return;
        }
        else {
            if ( firstLine >= nbLines )
                firstLine = nbLines - 1;
            if ( lastLine >= nbLines )
                lastLine =  nbLines - 1;
        }

        // Lines to write
        const QStringList lines = logData->getExpandedLines( firstLine, lastLine - firstLine + 1 );

        // First draw the bullet left margin
        painter.setPen(palette.color(QPalette::Text));
        painter.drawLine( bulletLineX_, 0, bulletLineX_, viewport()->height() );
        painter.fillRect( 0, 0, bulletLineX_, viewport()->height(), Qt::darkGray );

        // Then draw each line
        for (int i = firstLine; i <= lastLine; i++) {
            // Position in pixel of the base line of the line to print
            const int yPos = (i-firstLine) * fontHeight;
            const int xPos = bulletLineX_ + 2;

            // string to print, cut to fit the length and position of the view
            const QString cutLine = lines[i - firstLine].mid( firstCol, nbCols );

            if ( selection_.isLineSelected( i ) ) {
                // Reverse the selected line
                foreColor = palette.color( QPalette::HighlightedText );
                backColor = palette.color( QPalette::Highlight );
                painter.setPen(palette.color(QPalette::Text));
            }
            else if ( filterSet.matchLine( logData->getLineString( i ),
                        &foreColor, &backColor ) ) {
                // Apply a filter to the line
            }
            else {
                // Use the default colors
                foreColor = palette.color( QPalette::Text );
                backColor = palette.color( QPalette::Base );
            }

            // Is there something selected in the line?
            int sel_start, sel_end;
            bool isSelection =
                selection_.getPortionForLine( i, &sel_start, &sel_end );
            // Has the line got elements to be highlighted
            QList<QuickFindMatch> qfMatchList;
            bool isMatch =
                quickFindPattern_->matchLine( cutLine, qfMatchList );

            if ( isSelection || isMatch ) {
                // We use the LineDrawer and its chunks because the
                // line has to be somehow highlighted
                LineDrawer lineDrawer( backColor );

                // First we create a list of chunks with the highlights
                QList<LineChunk> chunkList;
                int column = 0; // Current column in line space
                foreach( const QuickFindMatch match, qfMatchList ) {
                    int start = match.startColumn();
                    if ( start > column )
                        chunkList << LineChunk( column, start - 1, LineChunk::Normal );
                    column = start + match.length() - 1;
                    chunkList << LineChunk( start, column, LineChunk::Highlighted );
                    column++;
                }
                chunkList << LineChunk( column, cutLine.length() - 1, LineChunk::Normal );

                // Then we add the selection if needed
                QList<LineChunk> newChunkList;
                if ( isSelection ) {
                    sel_start -= firstCol; // coord in line space
                    sel_end   -= firstCol;

                    foreach ( const LineChunk chunk, chunkList ) {
                        newChunkList << chunk.select( sel_start, sel_end );
                    }
                }
                else
                    newChunkList = chunkList;

                foreach ( const LineChunk chunk, newChunkList ) {
                    // Select the colours
                    QColor fore;
                    QColor back;
                    switch ( chunk.type() ) {
                        case LineChunk::Normal:
                            fore = foreColor;
                            back = backColor;
                            break;
                        case LineChunk::Highlighted:
                            fore = QColor( "black" );
                            back = QColor( "yellow" );
                            // fore = highlightForeColor;
                            // back = highlightBackColor;
                            break;
                        case LineChunk::Selected:
                            fore = palette.color( QPalette::HighlightedText ),
                            back = palette.color( QPalette::Highlight );
                            break;
                    }
                    lineDrawer.addChunk ( chunk, fore, back );
                }

                lineDrawer.draw( painter, xPos, yPos,
                        viewport()->width(), cutLine );
            }
            else {
                // Nothing to be highlighted, we print the whole line!
                painter.fillRect( xPos, yPos, viewport()->width(),
                        fontHeight, backColor );
                painter.setPen( foreColor );
                painter.drawText( xPos, yPos + fontAscent, cutLine );
            }

            // Then draw the bullet
            painter.setPen( palette.color( QPalette::Text ) );
            const int circleSize = 3;
            const int arrowHeight = 4;
            const int middleXLine = bulletLineX_ / 2;
            const int middleYLine = yPos + (fontHeight / 2);

            const LineType line_type = lineType( i );
            if ( line_type == Marked ) {
                // A pretty arrow if the line is marked
                const QPoint points[7] = {
                    QPoint(1, middleYLine - 2),
                    QPoint(middleXLine, middleYLine - 2),
                    QPoint(middleXLine, middleYLine - arrowHeight),
                    QPoint(bulletLineX_ - 2, middleYLine),
                    QPoint(middleXLine, middleYLine + arrowHeight),
                    QPoint(middleXLine, middleYLine + 2),
                    QPoint(1, middleYLine + 2 ),
                };

                painter.setBrush( markBrush );
                painter.drawPolygon( points, 7 );
            }
            else {
                if ( lineType( i ) == Match )
                    painter.setBrush( matchBulletBrush );
                else
                    painter.setBrush( normalBulletBrush );
                painter.drawEllipse( middleXLine - circleSize,
                        middleYLine - circleSize,
                        circleSize * 2, circleSize * 2 );
            }
        } // For each line
    }
    LOG(logDEBUG4) << "End of repaint";
}

void AbstractLogView::setOverview( Overview* overview )
{
    overview_ = overview;
    refreshOverview();
    overviewWidget_.setOverview( overview );
}

void AbstractLogView::searchNext()
{
    searchForward();
}

void AbstractLogView::searchPrevious()
{
    searchBackward();
}

void AbstractLogView::searchForward()
{
    emit followDisabled();

    int line = quickFind_.searchForward();
    if ( line >= 0 ) {
        LOG(logDEBUG) << "searchForward " << line;
        displayLine( line );
        emit updateLineNumber( line );
    }
}

void AbstractLogView::searchBackward()
{
    emit followDisabled();

    int line = quickFind_.searchBackward();
    if ( line >= 0 ) {
        LOG(logDEBUG) << "searchBackward " << line;
        displayLine( line );
        emit updateLineNumber( line );
    }
}

void AbstractLogView::followSet( bool checked )
{
    followMode_ = checked;
    if ( checked )
        jumpToBottom();
}

void AbstractLogView::refreshOverview()
{
    // Create space for the Overview if needed
    if ( ( getOverview() != NULL ) && getOverview()->isVisible() ) {
        setViewportMargins( 0, 0, OVERVIEW_WIDTH, 0 );
        overviewWidget_.show();
    }
    else {
        setViewportMargins( 0, 0, 0, 0 );
        overviewWidget_.hide();
    }
}

// Reset the QuickFind when the pattern is changed.
void AbstractLogView::handlePatternUpdated()
{
    LOG(logDEBUG) << "AbstractLogView::handlePatternUpdated()";

    quickFind_.resetLimits();
    update();
}

//
// Public functions
//

void AbstractLogView::updateData()
{
    LOG(logDEBUG) << "AbstractLogView::updateData";

    // Check the top Line is within range
    if ( firstLine >= logData->getNbLine() ) {
        firstLine = 0;
        firstCol = 0;
        verticalScrollBar()->setValue( 0 );
        horizontalScrollBar()->setValue( 0 );
    }

    // Crop selection if it become out of range
    selection_.crop( logData->getNbLine() - 1 );

    // Adapt the scroll bars to the new content
    verticalScrollBar()->setRange( 0, logData->getNbLine()-1 );
    const int hScrollMaxValue = ( logData->getMaxLength() - getNbVisibleCols() + 1 ) > 0 ?
        ( logData->getMaxLength() - getNbVisibleCols() + 1 ) : 0;
    horizontalScrollBar()->setRange( 0, hScrollMaxValue );

    lastLine = qMin( logData->getNbLine(), firstLine + getNbVisibleLines() );

    // Reset the QuickFind in case we have new stuff to search into
    quickFind_.resetLimits();

    if ( followMode_ )
        jumpToBottom();

    // Update the overview if we have one
    if ( overview_ != NULL )
        overview_->updateCurrentPosition( firstLine, lastLine );

    // Repaint!
    update();
}

void AbstractLogView::updateDisplaySize()
{
    QFontMetrics fm = fontMetrics();

    charHeight_ = fm.height();
    // Determine if the font is monospace (to enable various optimisations)
    useFixedFont_ = true;
    charWidth_ = fm.width('i');
    for ( int i = 0x20; i < 0x7F; i++ )
        if ( fm.width( QLatin1Char( i ) ) != charWidth_ ) {
            useFixedFont_ = false;
            break;
        }
    // FIXME: seems to be wrong on Qt/Mac
    LOG(logDEBUG) << "useFixedFont_=" << useFixedFont_;

    // Calculate the index of the last line shown
    lastLine = qMin( logData->getNbLine(), firstLine + getNbVisibleLines() );

    // Update the scroll bars
    verticalScrollBar()->setPageStep( getNbVisibleLines() );

    const int hScrollMaxValue = ( logData->getMaxLength() - getNbVisibleCols() + 1 ) > 0 ?
        ( logData->getMaxLength() - getNbVisibleCols() + 1 ) : 0;
    horizontalScrollBar()->setRange( 0, hScrollMaxValue );

    LOG(logDEBUG) << "viewport.width()=" << viewport()->width();
    LOG(logDEBUG) << "viewport.height()=" << viewport()->height();
    LOG(logDEBUG) << "width()=" << width();
    LOG(logDEBUG) << "height()=" << height();
    overviewWidget_.setGeometry( viewport()->width() + 2, 1,
            OVERVIEW_WIDTH - 1, viewport()->height() );
}

int AbstractLogView::getTopLine() const
{
    return firstLine;
}

QString AbstractLogView::getSelection() const
{
    return selection_.getSelectedText( logData );
}

void AbstractLogView::selectAndDisplayLine( int line )
{
    emit followDisabled();
    selection_.selectLine( line );
    displayLine( line );
    emit updateLineNumber( line );
}

// The difference between this function and displayLine() is quite
// subtle: this one always jump, even if the line passed is visible.
void AbstractLogView::jumpToLine( int line )
{
    // Put the selected line in the middle if possible
    int newTopLine = line - ( getNbVisibleLines() / 2 );
    if ( newTopLine < 0 )
        newTopLine = 0;

    // This will also trigger a scrollContents event
    verticalScrollBar()->setValue( newTopLine );
}

//
// Private functions
//

// Returns the number of lines visible in the viewport
int AbstractLogView::getNbVisibleLines() const
{
    return viewport()->height() / charHeight_ + 1;
}

// Returns the number of columns visible in the viewport
int AbstractLogView::getNbVisibleCols() const
{
    return ( viewport()->width() - leftMarginPx_ ) / charWidth_ + 1;
}

// Converts the mouse x, y coordinates to the line number in the file
int AbstractLogView::convertCoordToLine(int yPos) const
{
    QFontMetrics fm = fontMetrics();
    int line = firstLine + yPos/fm.height();

    return line;
}

// Converts the mouse x, y coordinates to the char coordinates (in the file)
// This function ensure the pos exists in the file.
QPoint AbstractLogView::convertCoordToFilePos( const QPoint& pos ) const
{
    int line = firstLine + pos.y() / charHeight_;
    if ( line >= logData->getNbLine() )
        line = logData->getNbLine() - 1;
    if ( line < 0 )
        line = 0;

    int column = 0;
    // Determine column in screen space
    QFontMetrics fm = fontMetrics();
    QString this_line = logData->getExpandedLineString( line );
    const int length = this_line.length();
    for ( ; column < length; column++ ) {
        if ( ( fm.width( this_line.mid(firstCol, column) )
                    + leftMarginPx_ ) > pos.x() ) {
            column--;
            break;
        }
    }

    // Now convert it to file space
    column += firstCol;

    if ( column >= length )
        column = length - 1;
    if ( column < 0 )
        column = 0;

    LOG(logDEBUG) << "AbstractLogView::convertCoordToFilePos col="
        << column << " line=" << line;
    QPoint point( column, line );

    return point;
}

// Makes the widget adjust itself to display the passed line.
// Doing so, it will throw itself a scrollContents event.
void AbstractLogView::displayLine( int line )
{
    // If the line is already the screen
    if ( ( line >= firstLine ) &&
         ( line < ( firstLine + getNbVisibleLines() ) ) ) {
        // ... don't scroll and just repaint
        update();
    } else {
        jumpToLine( line );
    }
}

// Move the selection up and down by the passed number of lines
void AbstractLogView::moveSelection( int delta )
{
    LOG(logDEBUG) << "AbstractLogView::moveSelection delta=" << delta;

    QList<int> selection = selection_.getLines();
    int new_line;

    // If nothing is selected, do as if line -1 was.
    if ( selection.isEmpty() )
        selection.append( -1 );

    if ( delta < 0 )
        new_line = selection.first() + delta;
    else
        new_line = selection.last() + delta;

    if ( new_line < 0 )
        new_line = 0;
    else if ( new_line >= logData->getNbLine() )
        new_line = logData->getNbLine() - 1;

    // Select and display the new line
    selection_.selectLine( new_line );
    displayLine( new_line );
    emit updateLineNumber( new_line );
}

// Make the start of the lines visible
void AbstractLogView::jumpToStartOfLine()
{
    horizontalScrollBar()->setValue( 0 );
}

// Make the end of the lines in the selection visible
void AbstractLogView::jumpToEndOfLine()
{
    QList<int> selection = selection_.getLines();

    // Search the longest line in the selection
    int max_length = 0;
    foreach ( int line, selection ) {
        int length = logData->getLineLength( line );
        if ( length > max_length )
            max_length = length;
    }

    horizontalScrollBar()->setValue( max_length - getNbVisibleCols() );
}

// Make the end of the lines on the screen visible
void AbstractLogView::jumpToRightOfScreen()
{
    QList<int> selection = selection_.getLines();

    // Search the longest line on screen
    int max_length = 0;
    for ( int i = firstLine; i <= ( firstLine + getNbVisibleLines() ); i++ ) {
        int length = logData->getLineLength( i );
        if ( length > max_length )
            max_length = length;
    }

    horizontalScrollBar()->setValue( max_length - getNbVisibleCols() );
}

// Jump to the first line
void AbstractLogView::jumpToTop()
{
    // This will also trigger a scrollContents event
    verticalScrollBar()->setValue( 0 );
    update();       // in case the screen hasn't moved
}

// Jump to the last line
void AbstractLogView::jumpToBottom()
{
    const int new_top_line =
        qMax( logData->getNbLine() - getNbVisibleLines() + 1, 0LL );

    // This will also trigger a scrollContents event
    verticalScrollBar()->setValue( new_top_line );
    update();       // in case the screen hasn't moved
}

// Returns whether the character passed is a 'word' character
inline bool AbstractLogView::isCharWord( char c )
{
    if ( ( ( c >= 'A' ) && ( c <= 'Z' ) ) ||
         ( ( c >= 'a' ) && ( c <= 'z' ) ) ||
         ( ( c >= '0' ) && ( c <= '9' ) ) ||
         ( ( c == '_' ) ) )
        return true;
    else
        return false;
}

// Select the word under the given position
void AbstractLogView::selectWordAtPosition( const QPoint& pos )
{
    const int x = pos.x();
    const QString line = logData->getExpandedLineString( pos.y() );

    if ( isCharWord( line[x].toLatin1() ) ) {
        // Search backward for the first character in the word
        int currentPos = x;
        for ( ; currentPos > 0; currentPos-- )
            if ( ! isCharWord( line[currentPos].toLatin1() ) )
                break;
        // Exclude the first char of the line if needed
        if ( ! isCharWord( line[currentPos].toLatin1() ) )
            currentPos++;
        int start = currentPos;

        // Now search for the end
        currentPos = x;
        for ( ; currentPos < line.length() - 1; currentPos++ )
            if ( ! isCharWord( line[currentPos].toLatin1() ) )
                break;
        // Exclude the last char of the line if needed
        if ( ! isCharWord( line[currentPos].toLatin1() ) )
            currentPos--;
        int end = currentPos;

        selection_.selectPortion( pos.y(), start, end );
        updateGlobalSelection();
        update();
    }
}

// Update the system global (middle click) selection (X11 only)
void AbstractLogView::updateGlobalSelection()
{
    static QClipboard* const clipboard = QApplication::clipboard();

    // Updating it only for "non-trivial" (range or portion) selections
    if ( ! selection_.isSingleLine() )
        clipboard->setText( selection_.getSelectedText( logData ),
                QClipboard::Selection );
}