xref: /glogg/src/abstractlogview.cpp (revision fcf40f1761134a69881dfa6f1d28d01064374a37)
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Nicolas Bonnefon
3  * and other contributors
4  *
5  * This file is part of glogg.
6  *
7  * glogg is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * glogg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with glogg.  If not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 // This file implements the AbstractLogView base class.
22 // Most of the actual drawing and event management common to the two views
23 // is implemented in this class.  The class only calls protected virtual
24 // functions when view specific behaviour is desired, using the template
25 // pattern.
26 
27 #include <iostream>
28 #include <cassert>
29 
30 #include <QApplication>
31 #include <QClipboard>
32 #include <QFile>
33 #include <QRect>
34 #include <QPaintEvent>
35 #include <QPainter>
36 #include <QFontMetrics>
37 #include <QScrollBar>
38 #include <QMenu>
39 #include <QAction>
40 #include <QtCore>
41 #include <QGestureEvent>
42 
43 #include "log.h"
44 
45 #include "persistentinfo.h"
46 #include "filterset.h"
47 #include "logmainview.h"
48 #include "quickfind.h"
49 #include "quickfindpattern.h"
50 #include "overview.h"
51 #include "configuration.h"
52 
53 namespace {
54 int mapPullToFollowLength( int length );
55 };
56 
57 namespace {
58 
59 int countDigits( quint64 n )
60 {
61     if (n == 0)
62         return 1;
63 
64     // We must force the compiler to not store intermediate results
65     // in registers because this causes incorrect result on some
66     // systems under optimizations level >0. For the skeptical:
67     //
68     // #include <math.h>
69     // #include <stdlib.h>
70     // int main(int argc, char **argv) {
71     //     (void)argc;
72     //     long long int n = atoll(argv[1]);
73     //     return floor( log( n ) / log( 10 ) + 1 );
74     // }
75     //
76     // This is on Thinkpad T60 (Genuine Intel(R) CPU T2300).
77     // $ g++ --version
78     // g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
79     // $ g++ -O0 -Wall -W -o math math.cpp -lm; ./math 10; echo $?
80     // 2
81     // $ g++ -O1 -Wall -W -o math math.cpp -lm; ./math 10; echo $?
82     // 1
83     //
84     // A fix is to (1) explicitly place intermediate results in
85     // variables *and* (2) [A] mark them as 'volatile', or [B] pass
86     // -ffloat-store to g++ (note that approach [A] is more portable).
87 
88     volatile qreal ln_n  = qLn( n );
89     volatile qreal ln_10 = qLn( 10 );
90     volatile qreal lg_n = ln_n / ln_10;
91     volatile qreal lg_n_1 = lg_n + 1;
92     volatile qreal fl_lg_n_1 = qFloor( lg_n_1 );
93 
94     return fl_lg_n_1;
95 }
96 
97 } // anon namespace
98 
99 
100 LineChunk::LineChunk( int first_col, int last_col, ChunkType type )
101 {
102     // LOG(logDEBUG) << "new LineChunk: " << first_col << " " << last_col;
103 
104     start_ = first_col;
105     end_   = last_col;
106     type_  = type;
107 }
108 
109 QList<LineChunk> LineChunk::select( int sel_start, int sel_end ) const
110 {
111     QList<LineChunk> list;
112 
113     if ( ( sel_start < start_ ) && ( sel_end < start_ ) ) {
114         // Selection BEFORE this chunk: no change
115         list << LineChunk( *this );
116     }
117     else if ( sel_start > end_ ) {
118         // Selection AFTER this chunk: no change
119         list << LineChunk( *this );
120     }
121     else /* if ( ( sel_start >= start_ ) && ( sel_end <= end_ ) ) */
122     {
123         // We only want to consider what's inside THIS chunk
124         sel_start = qMax( sel_start, start_ );
125         sel_end   = qMin( sel_end, end_ );
126 
127         if ( sel_start > start_ )
128             list << LineChunk( start_, sel_start - 1, type_ );
129         list << LineChunk( sel_start, sel_end, Selected );
130         if ( sel_end < end_ )
131             list << LineChunk( sel_end + 1, end_, type_ );
132     }
133 
134     return list;
135 }
136 
137 inline void LineDrawer::addChunk( int first_col, int last_col,
138         QColor fore, QColor back )
139 {
140     if ( first_col < 0 )
141         first_col = 0;
142     int length = last_col - first_col + 1;
143     if ( length > 0 ) {
144         list << Chunk ( first_col, length, fore, back );
145     }
146 }
147 
148 inline void LineDrawer::addChunk( const LineChunk& chunk,
149         QColor fore, QColor back )
150 {
151     int first_col = chunk.start();
152     int last_col  = chunk.end();
153 
154     addChunk( first_col, last_col, fore, back );
155 }
156 
157 inline void LineDrawer::draw( QPainter& painter,
158         int initialXPos, int initialYPos,
159         int line_width, const QString& line,
160         int leftExtraBackgroundPx )
161 {
162     QFontMetrics fm = painter.fontMetrics();
163     const int fontHeight = fm.height();
164     const int fontAscent = fm.ascent();
165     // For some reason on Qt 4.8.2 for Win, maxWidth() is wrong but the
166     // following give the right result, not sure why:
167     const int fontWidth = fm.width( QChar('a') );
168 
169     int xPos = initialXPos;
170     int yPos = initialYPos;
171 
172     foreach ( Chunk chunk, list ) {
173         // Draw each chunk
174         // LOG(logDEBUG) << "Chunk: " << chunk.start() << " " << chunk.length();
175         QString cutline = line.mid( chunk.start(), chunk.length() );
176         const int chunk_width = cutline.length() * fontWidth;
177         if ( xPos == initialXPos ) {
178             // First chunk, we extend the left background a bit,
179             // it looks prettier.
180             painter.fillRect( xPos - leftExtraBackgroundPx, yPos,
181                     chunk_width + leftExtraBackgroundPx,
182                     fontHeight, chunk.backColor() );
183         }
184         else {
185             // other chunks...
186             painter.fillRect( xPos, yPos, chunk_width,
187                     fontHeight, chunk.backColor() );
188         }
189         painter.setPen( chunk.foreColor() );
190         painter.drawText( xPos, yPos + fontAscent, cutline );
191         xPos += chunk_width;
192     }
193 
194     // Draw the empty block at the end of the line
195     int blank_width = line_width - xPos;
196 
197     if ( blank_width > 0 )
198         painter.fillRect( xPos, yPos, blank_width, fontHeight, backColor_ );
199 }
200 
201 const int DigitsBuffer::timeout_ = 2000;
202 
203 DigitsBuffer::DigitsBuffer() : QObject()
204 {
205 }
206 
207 void DigitsBuffer::reset()
208 {
209     LOG(logDEBUG) << "DigitsBuffer::reset()";
210 
211     timer_.stop();
212     digits_.clear();
213 }
214 
215 void DigitsBuffer::add( char character )
216 {
217     LOG(logDEBUG) << "DigitsBuffer::add()";
218 
219     digits_.append( QChar( character ) );
220     timer_.start( timeout_ , this );
221 }
222 
223 int DigitsBuffer::content()
224 {
225     int result = digits_.toInt();
226     reset();
227 
228     return result;
229 }
230 
231 void DigitsBuffer::timerEvent( QTimerEvent* event )
232 {
233     if ( event->timerId() == timer_.timerId() ) {
234         reset();
235     }
236     else {
237         QObject::timerEvent( event );
238     }
239 }
240 
241 AbstractLogView::AbstractLogView(const AbstractLogData* newLogData,
242         const QuickFindPattern* const quickFindPattern, QWidget* parent) :
243     QAbstractScrollArea( parent ),
244     followElasticHook_( HOOK_THRESHOLD ),
245     lineNumbersVisible_( false ),
246     selectionStartPos_(),
247     selectionCurrentEndPos_(),
248     autoScrollTimer_(),
249     selection_(),
250     quickFindPattern_( quickFindPattern ),
251     quickFind_( newLogData, &selection_, quickFindPattern )
252 {
253     logData = newLogData;
254 
255     followMode_ = false;
256 
257     selectionStarted_ = false;
258     markingClickInitiated_ = false;
259 
260     firstLine = 0;
261     lastLineAligned = false;
262     firstCol = 0;
263 
264     overview_ = NULL;
265     overviewWidget_ = NULL;
266 
267     // Display
268     leftMarginPx_ = 0;
269 
270     // Fonts (sensible default for overview widget)
271     charWidth_ = 1;
272     charHeight_ = 10;
273 
274     // Create the viewport QWidget
275     setViewport( 0 );
276 
277     // Hovering
278     setMouseTracking( true );
279     lastHoveredLine_ = -1;
280 
281     // Init the popup menu
282     createMenu();
283 
284     // Signals
285     connect( quickFindPattern_, SIGNAL( patternUpdated() ),
286             this, SLOT ( handlePatternUpdated() ) );
287     connect( &quickFind_, SIGNAL( notify( const QFNotification& ) ),
288             this, SIGNAL( notifyQuickFind( const QFNotification& ) ) );
289     connect( &quickFind_, SIGNAL( clearNotification() ),
290             this, SIGNAL( clearQuickFindNotification() ) );
291     connect( &followElasticHook_, SIGNAL( lengthChanged() ),
292             this, SLOT( repaint() ) );
293     connect( &followElasticHook_, SIGNAL( hooked( bool ) ),
294             this, SIGNAL( followModeChanged( bool ) ) );
295 }
296 
297 AbstractLogView::~AbstractLogView()
298 {
299 }
300 
301 
302 //
303 // Received events
304 //
305 
306 void AbstractLogView::changeEvent( QEvent* changeEvent )
307 {
308     QAbstractScrollArea::changeEvent( changeEvent );
309 
310     // Stop the timer if the widget becomes inactive
311     if ( changeEvent->type() == QEvent::ActivationChange ) {
312         if ( ! isActiveWindow() )
313             autoScrollTimer_.stop();
314     }
315     viewport()->update();
316 }
317 
318 void AbstractLogView::mousePressEvent( QMouseEvent* mouseEvent )
319 {
320     static std::shared_ptr<Configuration> config =
321         Persistent<Configuration>( "settings" );
322 
323     if ( mouseEvent->button() == Qt::LeftButton )
324     {
325         int line = convertCoordToLine( mouseEvent->y() );
326 
327         if ( mouseEvent->modifiers() & Qt::ShiftModifier )
328         {
329             selection_.selectRangeFromPrevious( line );
330             emit updateLineNumber( line );
331             update();
332         }
333         else
334         {
335             if ( mouseEvent->x() < bulletZoneWidthPx_ ) {
336                 // Mark a line if it is clicked in the left margin
337                 // (only if click and release in the same area)
338                 markingClickInitiated_ = true;
339                 markingClickLine_ = line;
340             }
341             else {
342                 // Select the line, and start a selection
343                 if ( line < logData->getNbLine() ) {
344                     selection_.selectLine( line );
345                     emit updateLineNumber( line );
346                     emit newSelection( line );
347                 }
348 
349                 // Remember the click in case we're starting a selection
350                 selectionStarted_ = true;
351                 selectionStartPos_ = convertCoordToFilePos( mouseEvent->pos() );
352                 selectionCurrentEndPos_ = selectionStartPos_;
353             }
354         }
355 
356         // Invalidate our cache
357         textAreaCache_.invalid_ = true;
358     }
359     else if ( mouseEvent->button() == Qt::RightButton )
360     {
361         // Prepare the popup depending on selection type
362         if ( selection_.isSingleLine() ) {
363             copyAction_->setText( "&Copy this line" );
364         }
365         else {
366             copyAction_->setText( "&Copy" );
367             copyAction_->setStatusTip( tr("Copy the selection") );
368         }
369 
370         if ( selection_.isPortion() ) {
371             findNextAction_->setEnabled( true );
372             findPreviousAction_->setEnabled( true );
373             addToSearchAction_->setEnabled( true );
374         }
375         else {
376             findNextAction_->setEnabled( false );
377             findPreviousAction_->setEnabled( false );
378             addToSearchAction_->setEnabled( false );
379         }
380 
381         // "Add to search" only makes sense in regexp mode
382         if ( config->mainRegexpType() != ExtendedRegexp )
383             addToSearchAction_->setEnabled( false );
384 
385         // Display the popup (blocking)
386         popupMenu_->exec( QCursor::pos() );
387     }
388 
389     emit activity();
390 }
391 
392 void AbstractLogView::mouseMoveEvent( QMouseEvent* mouseEvent )
393 {
394     // Selection implementation
395     if ( selectionStarted_ )
396     {
397         // Invalidate our cache
398         textAreaCache_.invalid_ = true;
399 
400         QPoint thisEndPos = convertCoordToFilePos( mouseEvent->pos() );
401         if ( thisEndPos != selectionCurrentEndPos_ )
402         {
403             // Are we on a different line?
404             if ( selectionStartPos_.y() != thisEndPos.y() )
405             {
406                 if ( thisEndPos.y() != selectionCurrentEndPos_.y() )
407                 {
408                     // This is a 'range' selection
409                     selection_.selectRange( selectionStartPos_.y(),
410                             thisEndPos.y() );
411                     emit updateLineNumber( thisEndPos.y() );
412                     update();
413                 }
414             }
415             // So we are on the same line. Are we moving horizontaly?
416             else if ( thisEndPos.x() != selectionCurrentEndPos_.x() )
417             {
418                 // This is a 'portion' selection
419                 selection_.selectPortion( thisEndPos.y(),
420                         selectionStartPos_.x(), thisEndPos.x() );
421                 update();
422             }
423             // On the same line, and moving vertically then
424             else
425             {
426                 // This is a 'line' selection
427                 selection_.selectLine( thisEndPos.y() );
428                 emit updateLineNumber( thisEndPos.y() );
429                 update();
430             }
431             selectionCurrentEndPos_ = thisEndPos;
432 
433             // Do we need to scroll while extending the selection?
434             QRect visible = viewport()->rect();
435             if ( visible.contains( mouseEvent->pos() ) )
436                 autoScrollTimer_.stop();
437             else if ( ! autoScrollTimer_.isActive() )
438                 autoScrollTimer_.start( 100, this );
439         }
440     }
441     else {
442         considerMouseHovering( mouseEvent->x(), mouseEvent->y() );
443     }
444 }
445 
446 void AbstractLogView::mouseReleaseEvent( QMouseEvent* mouseEvent )
447 {
448     if ( markingClickInitiated_ ) {
449         markingClickInitiated_ = false;
450         int line = convertCoordToLine( mouseEvent->y() );
451         if ( line == markingClickLine_ ) {
452             // Invalidate our cache
453             textAreaCache_.invalid_ = true;
454 
455             emit markLine( line );
456         }
457     }
458     else {
459         selectionStarted_ = false;
460         if ( autoScrollTimer_.isActive() )
461             autoScrollTimer_.stop();
462         updateGlobalSelection();
463     }
464 }
465 
466 void AbstractLogView::mouseDoubleClickEvent( QMouseEvent* mouseEvent )
467 {
468     if ( mouseEvent->button() == Qt::LeftButton )
469     {
470         // Invalidate our cache
471         textAreaCache_.invalid_ = true;
472 
473         const QPoint pos = convertCoordToFilePos( mouseEvent->pos() );
474         selectWordAtPosition( pos );
475     }
476 
477     emit activity();
478 }
479 
480 void AbstractLogView::timerEvent( QTimerEvent* timerEvent )
481 {
482     if ( timerEvent->timerId() == autoScrollTimer_.timerId() ) {
483         QRect visible = viewport()->rect();
484         const QPoint globalPos = QCursor::pos();
485         const QPoint pos = viewport()->mapFromGlobal( globalPos );
486         QMouseEvent ev( QEvent::MouseMove, pos, globalPos, Qt::LeftButton,
487                 Qt::LeftButton, Qt::NoModifier );
488         mouseMoveEvent( &ev );
489         int deltaX = qMax( pos.x() - visible.left(),
490                 visible.right() - pos.x() ) - visible.width();
491         int deltaY = qMax( pos.y() - visible.top(),
492                 visible.bottom() - pos.y() ) - visible.height();
493         int delta = qMax( deltaX, deltaY );
494 
495         if ( delta >= 0 ) {
496             if ( delta < 7 )
497                 delta = 7;
498             int timeout = 4900 / ( delta * delta );
499             autoScrollTimer_.start( timeout, this );
500 
501             if ( deltaX > 0 )
502                 horizontalScrollBar()->triggerAction(
503                         pos.x() <visible.center().x() ?
504                         QAbstractSlider::SliderSingleStepSub :
505                         QAbstractSlider::SliderSingleStepAdd );
506 
507             if ( deltaY > 0 )
508                 verticalScrollBar()->triggerAction(
509                         pos.y() <visible.center().y() ?
510                         QAbstractSlider::SliderSingleStepSub :
511                         QAbstractSlider::SliderSingleStepAdd );
512         }
513     }
514     QAbstractScrollArea::timerEvent( timerEvent );
515 }
516 
517 void AbstractLogView::keyPressEvent( QKeyEvent* keyEvent )
518 {
519     LOG(logDEBUG4) << "keyPressEvent received";
520     bool controlModifier = (keyEvent->modifiers() & Qt::ControlModifier) == Qt::ControlModifier;
521     bool shiftModifier = (keyEvent->modifiers() & Qt::ShiftModifier) == Qt::ShiftModifier;
522 
523     if ( keyEvent->key() == Qt::Key_Left )
524         horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);
525     else if ( keyEvent->key() == Qt::Key_Right )
526         horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);
527     else if ( keyEvent->key() == Qt::Key_Home && !controlModifier)
528         jumpToStartOfLine();
529     else if ( keyEvent->key() == Qt::Key_End  && !controlModifier)
530         jumpToRightOfScreen();
531     else if ( (keyEvent->key() == Qt::Key_PageDown && controlModifier)
532            || (keyEvent->key() == Qt::Key_End && controlModifier) )
533     {
534         disableFollow(); // duplicate of 'G' action.
535         selection_.selectLine( logData->getNbLine() - 1 );
536         emit updateLineNumber( logData->getNbLine() - 1 );
537         jumpToBottom();
538     }
539     else if ( (keyEvent->key() == Qt::Key_PageUp && controlModifier)
540            || (keyEvent->key() == Qt::Key_Home && controlModifier) )
541     {
542         disableFollow(); // like 'g' but 0 input first line action.
543         selectAndDisplayLine( 0 );
544         emit updateLineNumber( 0 );
545     }
546     else if ( keyEvent->key() == Qt::Key_F3 && !shiftModifier )
547         searchNext(); // duplicate of 'n' action.
548     else if ( keyEvent->key() == Qt::Key_F3 && shiftModifier )
549         searchPrevious(); // duplicate of 'N' action.
550     else {
551         const char character = (keyEvent->text())[0].toLatin1();
552 
553         if ( keyEvent->modifiers() == Qt::NoModifier &&
554                 ( character >= '0' ) && ( character <= '9' ) ) {
555             // Adds the digit to the timed buffer
556             digitsBuffer_.add( character );
557         }
558         else {
559             switch ( (keyEvent->text())[0].toLatin1() ) {
560                 case 'j':
561                     {
562                         int delta = qMax( 1, digitsBuffer_.content() );
563                         disableFollow();
564                         //verticalScrollBar()->triggerAction(
565                         //QScrollBar::SliderSingleStepAdd);
566                         moveSelection( delta );
567                         break;
568                     }
569                 case 'k':
570                     {
571                         int delta = qMin( -1, - digitsBuffer_.content() );
572                         disableFollow();
573                         //verticalScrollBar()->triggerAction(
574                         //QScrollBar::SliderSingleStepSub);
575                         moveSelection( delta );
576                         break;
577                     }
578                 case 'h':
579                     horizontalScrollBar()->triggerAction(
580                             QScrollBar::SliderSingleStepSub);
581                     break;
582                 case 'l':
583                     horizontalScrollBar()->triggerAction(
584                             QScrollBar::SliderSingleStepAdd);
585                     break;
586                 case '0':
587                     jumpToStartOfLine();
588                     break;
589                 case '$':
590                     jumpToEndOfLine();
591                     break;
592                 case 'g':
593                     {
594                         int newLine = qMax( 0, digitsBuffer_.content() - 1 );
595                         if ( newLine >= logData->getNbLine() )
596                             newLine = logData->getNbLine() - 1;
597                         disableFollow();
598                         selectAndDisplayLine( newLine );
599                         emit updateLineNumber( newLine );
600                         break;
601                     }
602                 case 'G':
603                     disableFollow();
604                     selection_.selectLine( logData->getNbLine() - 1 );
605                     emit updateLineNumber( logData->getNbLine() - 1 );
606                     jumpToBottom();
607                     break;
608                 case 'n':
609                     emit searchNext();
610                     break;
611                 case 'N':
612                     emit searchPrevious();
613                     break;
614                 case '*':
615                     // Use the selected 'word' and search forward
616                     findNextSelected();
617                     break;
618                 case '#':
619                     // Use the selected 'word' and search backward
620                     findPreviousSelected();
621                     break;
622                 default:
623                     keyEvent->ignore();
624             }
625         }
626     }
627 
628     if ( keyEvent->isAccepted() ) {
629         emit activity();
630     }
631     else {
632         QAbstractScrollArea::keyPressEvent( keyEvent );
633     }
634 }
635 
636 void AbstractLogView::wheelEvent( QWheelEvent* wheelEvent )
637 {
638     emit activity();
639 
640     // LOG(logDEBUG) << "wheelEvent";
641 
642     // This is to handle the case where follow mode is on, but the user
643     // has moved using the scroll bar. We take them back to the bottom.
644     if ( followMode_ )
645         jumpToBottom();
646 
647     int y_delta = 0;
648     if ( verticalScrollBar()->value() == verticalScrollBar()->maximum() ) {
649         // First see if we need to block the elastic (on Mac)
650         if ( wheelEvent->phase() == Qt::ScrollBegin )
651             followElasticHook_.hold();
652         else if ( wheelEvent->phase() == Qt::ScrollEnd )
653             followElasticHook_.release();
654 
655         auto pixel_delta = wheelEvent->pixelDelta();
656 
657         if ( pixel_delta.isNull() ) {
658             y_delta = wheelEvent->angleDelta().y() / 0.7;
659         }
660         else {
661             y_delta = pixel_delta.y();
662         }
663 
664         // LOG(logDEBUG) << "Elastic " << y_delta;
665         followElasticHook_.move( - y_delta );
666     }
667 
668     // LOG(logDEBUG) << "Length = " << followElasticHook_.length();
669     if ( followElasticHook_.length() == 0 && !followElasticHook_.isHooked() ) {
670         QAbstractScrollArea::wheelEvent( wheelEvent );
671     }
672 }
673 
674 void AbstractLogView::resizeEvent( QResizeEvent* )
675 {
676     if ( logData == NULL )
677         return;
678 
679     LOG(logDEBUG) << "resizeEvent received";
680 
681     updateDisplaySize();
682 }
683 
684 bool AbstractLogView::event( QEvent* e )
685 {
686     LOG(logDEBUG4) << "Event! Type: " << e->type();
687 
688     // Make sure we ignore the gesture events as
689     // they seem to be accepted by default.
690     if ( e->type() == QEvent::Gesture ) {
691         auto gesture_event = dynamic_cast<QGestureEvent*>( e );
692         if ( gesture_event ) {
693             foreach( QGesture* gesture, gesture_event->gestures() ) {
694                 LOG(logDEBUG4) << "Gesture: " << gesture->gestureType();
695                 gesture_event->ignore( gesture );
696             }
697 
698             // Ensure the event is sent up to parents who might care
699             return false;
700         }
701     }
702 
703     return QAbstractScrollArea::event( e );
704 }
705 
706 void AbstractLogView::scrollContentsBy( int dx, int dy )
707 {
708     LOG(logDEBUG) << "scrollContentsBy received " << dy
709         << "position " << verticalScrollBar()->value();
710 
711     int32_t last_top_line = ( logData->getNbLine() - getNbVisibleLines() );
712     if ( ( last_top_line > 0 ) && verticalScrollBar()->value() > last_top_line ) {
713         // The user is going further than the last line, we need to lock the last line at the bottom
714         LOG(logDEBUG) << "scrollContentsBy beyond!";
715         firstLine = last_top_line;
716         lastLineAligned = true;
717     }
718     else {
719         firstLine = verticalScrollBar()->value();
720         lastLineAligned = false;
721     }
722 
723     firstCol  = (firstCol - dx) > 0 ? firstCol - dx : 0;
724     LineNumber last_line  = firstLine + getNbVisibleLines();
725 
726     // Update the overview if we have one
727     if ( overview_ != NULL )
728         overview_->updateCurrentPosition( firstLine, last_line );
729 
730     // Are we hovering over a new line?
731     const QPoint mouse_pos = mapFromGlobal( QCursor::pos() );
732     considerMouseHovering( mouse_pos.x(), mouse_pos.y() );
733 
734     // Redraw
735     update();
736 }
737 
738 void AbstractLogView::paintEvent( QPaintEvent* paintEvent )
739 {
740     const QRect invalidRect = paintEvent->rect();
741     if ( (invalidRect.isEmpty()) || (logData == NULL) )
742         return;
743 
744     LOG(logDEBUG4) << "paintEvent received, firstLine=" << firstLine
745         << " lastLineAligned=" << lastLineAligned
746         << " rect: " << invalidRect.topLeft().x() <<
747         ", " << invalidRect.topLeft().y() <<
748         ", " << invalidRect.bottomRight().x() <<
749         ", " << invalidRect.bottomRight().y();
750 
751 #ifdef GLOGG_PERF_MEASURE_FPS
752     static uint32_t maxline = logData->getNbLine();
753     if ( ! perfCounter_.addEvent() && logData->getNbLine() > maxline ) {
754         LOG(logWARNING) << "Redraw per second: " << perfCounter_.readAndReset()
755             << " lines: " << logData->getNbLine();
756         perfCounter_.addEvent();
757         maxline = logData->getNbLine();
758     }
759 #endif
760 
761     auto start = std::chrono::system_clock::now();
762 
763     // Can we use our cache?
764     int32_t delta_y = textAreaCache_.first_line_ - firstLine;
765 
766     if ( textAreaCache_.invalid_ || ( textAreaCache_.first_column_ != firstCol ) ) {
767         // Force a full redraw
768         delta_y = INT32_MAX;
769     }
770 
771     if ( delta_y != 0 ) {
772         // Full or partial redraw
773         drawTextArea( &textAreaCache_.pixmap_, delta_y );
774 
775         textAreaCache_.invalid_      = false;
776         textAreaCache_.first_line_   = firstLine;
777         textAreaCache_.first_column_ = firstCol;
778 
779         LOG(logDEBUG) << "End of writing " <<
780             std::chrono::duration_cast<std::chrono::microseconds>
781             ( std::chrono::system_clock::now() - start ).count();
782     }
783     else {
784         // Use the cache as is: nothing to do!
785     }
786 
787     // Height including the potentially invisible last line
788     const int whole_height = getNbVisibleLines() * charHeight_;
789     // Height in pixels of the "pull to follow" bottom bar.
790     int pullToFollowHeight = mapPullToFollowLength( followElasticHook_.length() )
791         + ( followElasticHook_.isHooked() ?
792                 ( whole_height - viewport()->height() ) + PULL_TO_FOLLOW_HOOKED_HEIGHT : 0 );
793 
794     if ( pullToFollowHeight
795             && ( pullToFollowCache_.nb_columns_ != getNbVisibleCols() ) ) {
796         LOG(logDEBUG) << "Drawing pull to follow bar";
797         pullToFollowCache_.pixmap_ = drawPullToFollowBar(
798                 viewport()->width(), viewport()->devicePixelRatio() );
799         pullToFollowCache_.nb_columns_ = getNbVisibleCols();
800     }
801 
802     QPainter devicePainter( viewport() );
803     int drawingTopPosition = - pullToFollowHeight;
804     int drawingPullToFollowTopPosition = drawingTopPosition + whole_height;
805 
806     // This is to cover the special case where there is less than a screenful
807     // worth of data, we want to see the document from the top, rather than
808     // pushing the first couple of lines above the viewport.
809     if ( followElasticHook_.isHooked() && ( logData->getNbLine() < getNbVisibleLines() ) ) {
810         drawingTopOffset_ = 0;
811         drawingTopPosition += ( whole_height - viewport()->height() ) + PULL_TO_FOLLOW_HOOKED_HEIGHT;
812         drawingPullToFollowTopPosition = drawingTopPosition + viewport()->height() - PULL_TO_FOLLOW_HOOKED_HEIGHT;
813     }
814     // This is the case where the user is on the 'extra' slot at the end
815     // and is aligned on the last line (but no elastic shown)
816     else if ( lastLineAligned && !followElasticHook_.isHooked() ) {
817         drawingTopOffset_ = - ( whole_height - viewport()->height() );
818         drawingTopPosition += drawingTopOffset_;
819         drawingPullToFollowTopPosition = drawingTopPosition + whole_height;
820     }
821     else {
822         drawingTopOffset_ = - pullToFollowHeight;
823     }
824 
825     devicePainter.drawPixmap( 0, drawingTopPosition, textAreaCache_.pixmap_ );
826 
827     // Draw the "pull to follow" zone if needed
828     if ( pullToFollowHeight ) {
829         devicePainter.drawPixmap( 0,
830                 drawingPullToFollowTopPosition,
831                 pullToFollowCache_.pixmap_ );
832     }
833 
834     LOG(logDEBUG) << "End of repaint " <<
835         std::chrono::duration_cast<std::chrono::microseconds>
836         ( std::chrono::system_clock::now() - start ).count();
837 }
838 
839 // These two functions are virtual and this implementation is clearly
840 // only valid for a non-filtered display.
841 // We count on the 'filtered' derived classes to override them.
842 qint64 AbstractLogView::displayLineNumber( int lineNumber ) const
843 {
844     return lineNumber + 1; // show a 1-based index
845 }
846 
847 qint64 AbstractLogView::maxDisplayLineNumber() const
848 {
849     return logData->getNbLine();
850 }
851 
852 void AbstractLogView::setOverview( Overview* overview,
853        OverviewWidget* overview_widget )
854 {
855     overview_ = overview;
856     overviewWidget_ = overview_widget;
857 
858     if ( overviewWidget_ ) {
859         connect( overviewWidget_, SIGNAL( lineClicked ( int ) ),
860                 this, SIGNAL( followDisabled() ) );
861         connect( overviewWidget_, SIGNAL( lineClicked ( int ) ),
862                 this, SLOT( jumpToLine( int ) ) );
863     }
864     refreshOverview();
865 }
866 
867 void AbstractLogView::searchUsingFunction(
868         qint64 (QuickFind::*search_function)() )
869 {
870     disableFollow();
871 
872     int line = (quickFind_.*search_function)();
873     if ( line >= 0 ) {
874         LOG(logDEBUG) << "search " << line;
875         displayLine( line );
876         emit updateLineNumber( line );
877     }
878 }
879 
880 void AbstractLogView::searchForward()
881 {
882     searchUsingFunction( &QuickFind::searchForward );
883 }
884 
885 void AbstractLogView::searchBackward()
886 {
887     searchUsingFunction( &QuickFind::searchBackward );
888 }
889 
890 void AbstractLogView::incrementallySearchForward()
891 {
892     searchUsingFunction( &QuickFind::incrementallySearchForward );
893 }
894 
895 void AbstractLogView::incrementallySearchBackward()
896 {
897     searchUsingFunction( &QuickFind::incrementallySearchBackward );
898 }
899 
900 void AbstractLogView::incrementalSearchAbort()
901 {
902     quickFind_.incrementalSearchAbort();
903     emit changeQuickFind(
904             "",
905             QuickFindMux::Forward );
906 }
907 
908 void AbstractLogView::incrementalSearchStop()
909 {
910     quickFind_.incrementalSearchStop();
911 }
912 
913 void AbstractLogView::followSet( bool checked )
914 {
915     followMode_ = checked;
916     followElasticHook_.hook( checked );
917     update();
918     if ( checked )
919         jumpToBottom();
920 }
921 
922 void AbstractLogView::refreshOverview()
923 {
924     assert( overviewWidget_ );
925 
926     // Create space for the Overview if needed
927     if ( ( getOverview() != NULL ) && getOverview()->isVisible() ) {
928         setViewportMargins( 0, 0, OVERVIEW_WIDTH, 0 );
929         overviewWidget_->show();
930     }
931     else {
932         setViewportMargins( 0, 0, 0, 0 );
933         overviewWidget_->hide();
934     }
935 }
936 
937 // Reset the QuickFind when the pattern is changed.
938 void AbstractLogView::handlePatternUpdated()
939 {
940     LOG(logDEBUG) << "AbstractLogView::handlePatternUpdated()";
941 
942     quickFind_.resetLimits();
943     update();
944 }
945 
946 // OR the current with the current search expression
947 void AbstractLogView::addToSearch()
948 {
949     if ( selection_.isPortion() ) {
950         LOG(logDEBUG) << "AbstractLogView::addToSearch()";
951         emit addToSearch( selection_.getSelectedText( logData ) );
952     }
953     else {
954         LOG(logERROR) << "AbstractLogView::addToSearch called for a wrong type of selection";
955     }
956 }
957 
958 // Find next occurence of the selected text (*)
959 void AbstractLogView::findNextSelected()
960 {
961     // Use the selected 'word' and search forward
962     if ( selection_.isPortion() ) {
963         emit changeQuickFind(
964                 selection_.getSelectedText( logData ),
965                 QuickFindMux::Forward );
966         emit searchNext();
967     }
968 }
969 
970 // Find next previous of the selected text (#)
971 void AbstractLogView::findPreviousSelected()
972 {
973     if ( selection_.isPortion() ) {
974         emit changeQuickFind(
975                 selection_.getSelectedText( logData ),
976                 QuickFindMux::Backward );
977         emit searchNext();
978     }
979 }
980 
981 // Copy the selection to the clipboard
982 void AbstractLogView::copy()
983 {
984     static QClipboard* clipboard = QApplication::clipboard();
985 
986     clipboard->setText( selection_.getSelectedText( logData ) );
987 }
988 
989 //
990 // Public functions
991 //
992 
993 void AbstractLogView::updateData()
994 {
995     LOG(logDEBUG) << "AbstractLogView::updateData";
996 
997     // Check the top Line is within range
998     if ( firstLine >= logData->getNbLine() ) {
999         firstLine = 0;
1000         firstCol = 0;
1001         verticalScrollBar()->setValue( 0 );
1002         horizontalScrollBar()->setValue( 0 );
1003     }
1004 
1005     // Crop selection if it become out of range
1006     selection_.crop( logData->getNbLine() - 1 );
1007 
1008     // Adapt the scroll bars to the new content
1009     updateScrollBars();
1010 
1011     // Calculate the index of the last line shown
1012     LineNumber last_line = std::min( static_cast<int64_t>( logData->getNbLine() ),
1013             static_cast<int64_t>( firstLine + getNbVisibleLines() ) );
1014 
1015     // Reset the QuickFind in case we have new stuff to search into
1016     quickFind_.resetLimits();
1017 
1018     if ( followMode_ )
1019         jumpToBottom();
1020 
1021     // Update the overview if we have one
1022     if ( overview_ != NULL )
1023         overview_->updateCurrentPosition( firstLine, last_line );
1024 
1025     // Invalidate our cache
1026     textAreaCache_.invalid_ = true;
1027 
1028     // Repaint!
1029     update();
1030 }
1031 
1032 void AbstractLogView::updateDisplaySize()
1033 {
1034     // Font is assumed to be mono-space (is restricted by options dialog)
1035     QFontMetrics fm = fontMetrics();
1036     charHeight_ = fm.height();
1037     // For some reason on Qt 4.8.2 for Win, maxWidth() is wrong but the
1038     // following give the right result, not sure why:
1039     charWidth_ = fm.width( QChar('a') );
1040 
1041     // Update the scroll bars
1042     updateScrollBars();
1043     verticalScrollBar()->setPageStep( getNbVisibleLines() );
1044 
1045     if ( followMode_ )
1046         jumpToBottom();
1047 
1048     LOG(logDEBUG) << "viewport.width()=" << viewport()->width();
1049     LOG(logDEBUG) << "viewport.height()=" << viewport()->height();
1050     LOG(logDEBUG) << "width()=" << width();
1051     LOG(logDEBUG) << "height()=" << height();
1052 
1053     if ( overviewWidget_ )
1054         overviewWidget_->setGeometry( viewport()->width() + 2, 1,
1055                 OVERVIEW_WIDTH - 1, viewport()->height() );
1056 
1057     // Our text area cache is now invalid
1058     textAreaCache_.invalid_ = true;
1059     textAreaCache_.pixmap_  = QPixmap {
1060         viewport()->width() * viewport()->devicePixelRatio(),
1061         static_cast<int32_t>( getNbVisibleLines() ) * charHeight_ * viewport()->devicePixelRatio() };
1062     textAreaCache_.pixmap_.setDevicePixelRatio( viewport()->devicePixelRatio() );
1063 }
1064 
1065 int AbstractLogView::getTopLine() const
1066 {
1067     return firstLine;
1068 }
1069 
1070 QString AbstractLogView::getSelection() const
1071 {
1072     return selection_.getSelectedText( logData );
1073 }
1074 
1075 void AbstractLogView::selectAll()
1076 {
1077     selection_.selectRange( 0, logData->getNbLine() - 1 );
1078     textAreaCache_.invalid_ = true;
1079     update();
1080 }
1081 
1082 void AbstractLogView::selectAndDisplayLine( int line )
1083 {
1084     disableFollow();
1085     selection_.selectLine( line );
1086     displayLine( line );
1087     emit updateLineNumber( line );
1088 }
1089 
1090 // The difference between this function and displayLine() is quite
1091 // subtle: this one always jump, even if the line passed is visible.
1092 void AbstractLogView::jumpToLine( int line )
1093 {
1094     // Put the selected line in the middle if possible
1095     int newTopLine = line - ( getNbVisibleLines() / 2 );
1096     if ( newTopLine < 0 )
1097         newTopLine = 0;
1098 
1099     // This will also trigger a scrollContents event
1100     verticalScrollBar()->setValue( newTopLine );
1101 }
1102 
1103 void AbstractLogView::setLineNumbersVisible( bool lineNumbersVisible )
1104 {
1105     lineNumbersVisible_ = lineNumbersVisible;
1106 }
1107 
1108 void AbstractLogView::forceRefresh()
1109 {
1110     // Invalidate our cache
1111     textAreaCache_.invalid_ = true;
1112 }
1113 
1114 //
1115 // Private functions
1116 //
1117 
1118 // Returns the number of lines visible in the viewport
1119 LineNumber AbstractLogView::getNbVisibleLines() const
1120 {
1121     return static_cast<LineNumber>( viewport()->height() / charHeight_ + 1 );
1122 }
1123 
1124 // Returns the number of columns visible in the viewport
1125 int AbstractLogView::getNbVisibleCols() const
1126 {
1127     return ( viewport()->width() - leftMarginPx_ ) / charWidth_ + 1;
1128 }
1129 
1130 // Converts the mouse x, y coordinates to the line number in the file
1131 int AbstractLogView::convertCoordToLine(int yPos) const
1132 {
1133     int line = firstLine + ( yPos - drawingTopOffset_ ) / charHeight_;
1134 
1135     return line;
1136 }
1137 
1138 // Converts the mouse x, y coordinates to the char coordinates (in the file)
1139 // This function ensure the pos exists in the file.
1140 QPoint AbstractLogView::convertCoordToFilePos( const QPoint& pos ) const
1141 {
1142     int line = convertCoordToLine( pos.y() );
1143     if ( line >= logData->getNbLine() )
1144         line = logData->getNbLine() - 1;
1145     if ( line < 0 )
1146         line = 0;
1147 
1148     // Determine column in screen space and convert it to file space
1149     int column = firstCol + ( pos.x() - leftMarginPx_ ) / charWidth_;
1150 
1151     QString this_line = logData->getExpandedLineString( line );
1152     const int length = this_line.length();
1153 
1154     if ( column >= length )
1155         column = length - 1;
1156     if ( column < 0 )
1157         column = 0;
1158 
1159     LOG(logDEBUG4) << "AbstractLogView::convertCoordToFilePos col="
1160         << column << " line=" << line;
1161     QPoint point( column, line );
1162 
1163     return point;
1164 }
1165 
1166 // Makes the widget adjust itself to display the passed line.
1167 // Doing so, it will throw itself a scrollContents event.
1168 void AbstractLogView::displayLine( LineNumber line )
1169 {
1170     // If the line is already the screen
1171     if ( ( line >= firstLine ) &&
1172          ( line < ( firstLine + getNbVisibleLines() ) ) ) {
1173         // Invalidate our cache
1174         textAreaCache_.invalid_ = true;
1175 
1176         // ... don't scroll and just repaint
1177         update();
1178     } else {
1179         jumpToLine( line );
1180     }
1181 }
1182 
1183 // Move the selection up and down by the passed number of lines
1184 void AbstractLogView::moveSelection( int delta )
1185 {
1186     LOG(logDEBUG) << "AbstractLogView::moveSelection delta=" << delta;
1187 
1188     QList<int> selection = selection_.getLines();
1189     int new_line;
1190 
1191     // If nothing is selected, do as if line -1 was.
1192     if ( selection.isEmpty() )
1193         selection.append( -1 );
1194 
1195     if ( delta < 0 )
1196         new_line = selection.first() + delta;
1197     else
1198         new_line = selection.last() + delta;
1199 
1200     if ( new_line < 0 )
1201         new_line = 0;
1202     else if ( new_line >= logData->getNbLine() )
1203         new_line = logData->getNbLine() - 1;
1204 
1205     // Select and display the new line
1206     selection_.selectLine( new_line );
1207     displayLine( new_line );
1208     emit updateLineNumber( new_line );
1209     emit newSelection( new_line );
1210 }
1211 
1212 // Make the start of the lines visible
1213 void AbstractLogView::jumpToStartOfLine()
1214 {
1215     horizontalScrollBar()->setValue( 0 );
1216 }
1217 
1218 // Make the end of the lines in the selection visible
1219 void AbstractLogView::jumpToEndOfLine()
1220 {
1221     QList<int> selection = selection_.getLines();
1222 
1223     // Search the longest line in the selection
1224     int max_length = 0;
1225     foreach ( int line, selection ) {
1226         int length = logData->getLineLength( line );
1227         if ( length > max_length )
1228             max_length = length;
1229     }
1230 
1231     horizontalScrollBar()->setValue( max_length - getNbVisibleCols() );
1232 }
1233 
1234 // Make the end of the lines on the screen visible
1235 void AbstractLogView::jumpToRightOfScreen()
1236 {
1237     QList<int> selection = selection_.getLines();
1238 
1239     // Search the longest line on screen
1240     int max_length = 0;
1241     for ( auto i = firstLine; i <= ( firstLine + getNbVisibleLines() ); i++ ) {
1242         int length = logData->getLineLength( i );
1243         if ( length > max_length )
1244             max_length = length;
1245     }
1246 
1247     horizontalScrollBar()->setValue( max_length - getNbVisibleCols() );
1248 }
1249 
1250 // Jump to the first line
1251 void AbstractLogView::jumpToTop()
1252 {
1253     // This will also trigger a scrollContents event
1254     verticalScrollBar()->setValue( 0 );
1255     update();       // in case the screen hasn't moved
1256 }
1257 
1258 // Jump to the last line
1259 void AbstractLogView::jumpToBottom()
1260 {
1261     const int new_top_line =
1262         qMax( logData->getNbLine() - getNbVisibleLines() + 1, 0LL );
1263 
1264     // This will also trigger a scrollContents event
1265     verticalScrollBar()->setValue( new_top_line );
1266     update();       // in case the screen hasn't moved
1267 }
1268 
1269 // Returns whether the character passed is a 'word' character
1270 inline bool AbstractLogView::isCharWord( char c )
1271 {
1272     if ( ( ( c >= 'A' ) && ( c <= 'Z' ) ) ||
1273          ( ( c >= 'a' ) && ( c <= 'z' ) ) ||
1274          ( ( c >= '0' ) && ( c <= '9' ) ) ||
1275          ( ( c == '_' ) ) )
1276         return true;
1277     else
1278         return false;
1279 }
1280 
1281 // Select the word under the given position
1282 void AbstractLogView::selectWordAtPosition( const QPoint& pos )
1283 {
1284     const int x = pos.x();
1285     const QString line = logData->getExpandedLineString( pos.y() );
1286 
1287     if ( isCharWord( line[x].toLatin1() ) ) {
1288         // Search backward for the first character in the word
1289         int currentPos = x;
1290         for ( ; currentPos > 0; currentPos-- )
1291             if ( ! isCharWord( line[currentPos].toLatin1() ) )
1292                 break;
1293         // Exclude the first char of the line if needed
1294         if ( ! isCharWord( line[currentPos].toLatin1() ) )
1295             currentPos++;
1296         int start = currentPos;
1297 
1298         // Now search for the end
1299         currentPos = x;
1300         for ( ; currentPos < line.length() - 1; currentPos++ )
1301             if ( ! isCharWord( line[currentPos].toLatin1() ) )
1302                 break;
1303         // Exclude the last char of the line if needed
1304         if ( ! isCharWord( line[currentPos].toLatin1() ) )
1305             currentPos--;
1306         int end = currentPos;
1307 
1308         selection_.selectPortion( pos.y(), start, end );
1309         updateGlobalSelection();
1310         update();
1311     }
1312 }
1313 
1314 // Update the system global (middle click) selection (X11 only)
1315 void AbstractLogView::updateGlobalSelection()
1316 {
1317     static QClipboard* const clipboard = QApplication::clipboard();
1318 
1319     // Updating it only for "non-trivial" (range or portion) selections
1320     if ( ! selection_.isSingleLine() )
1321         clipboard->setText( selection_.getSelectedText( logData ),
1322                 QClipboard::Selection );
1323 }
1324 
1325 // Create the pop-up menu
1326 void AbstractLogView::createMenu()
1327 {
1328     copyAction_ = new QAction( tr("&Copy"), this );
1329     // No text as this action title depends on the type of selection
1330     connect( copyAction_, SIGNAL(triggered()), this, SLOT(copy()) );
1331 
1332     // For '#' and '*', shortcuts doesn't seem to work but
1333     // at least it displays them in the menu, we manually handle those keys
1334     // as keys event anyway (in keyPressEvent).
1335     findNextAction_ = new QAction(tr("Find &next"), this);
1336     findNextAction_->setShortcut( Qt::Key_Asterisk );
1337     findNextAction_->setStatusTip( tr("Find the next occurence") );
1338     connect( findNextAction_, SIGNAL(triggered()),
1339             this, SLOT( findNextSelected() ) );
1340 
1341     findPreviousAction_ = new QAction( tr("Find &previous"), this );
1342     findPreviousAction_->setShortcut( tr("#")  );
1343     findPreviousAction_->setStatusTip( tr("Find the previous occurence") );
1344     connect( findPreviousAction_, SIGNAL(triggered()),
1345             this, SLOT( findPreviousSelected() ) );
1346 
1347     addToSearchAction_ = new QAction( tr("&Add to search"), this );
1348     addToSearchAction_->setStatusTip(
1349             tr("Add the selection to the current search") );
1350     connect( addToSearchAction_, SIGNAL( triggered() ),
1351             this, SLOT( addToSearch() ) );
1352 
1353     popupMenu_ = new QMenu( this );
1354     popupMenu_->addAction( copyAction_ );
1355     popupMenu_->addSeparator();
1356     popupMenu_->addAction( findNextAction_ );
1357     popupMenu_->addAction( findPreviousAction_ );
1358     popupMenu_->addAction( addToSearchAction_ );
1359 }
1360 
1361 void AbstractLogView::considerMouseHovering( int x_pos, int y_pos )
1362 {
1363     int line = convertCoordToLine( y_pos );
1364     if ( ( x_pos < leftMarginPx_ )
1365             && ( line >= 0 )
1366             && ( line < logData->getNbLine() ) ) {
1367         // Mouse moved in the margin, send event up
1368         // (possibly to highlight the overview)
1369         if ( line != lastHoveredLine_ ) {
1370             LOG(logDEBUG) << "Mouse moved in margin line: " << line;
1371             emit mouseHoveredOverLine( line );
1372             lastHoveredLine_ = line;
1373         }
1374     }
1375     else {
1376         if ( lastHoveredLine_ != -1 ) {
1377             emit mouseLeftHoveringZone();
1378             lastHoveredLine_ = -1;
1379         }
1380     }
1381 }
1382 
1383 void AbstractLogView::updateScrollBars()
1384 {
1385     verticalScrollBar()->setRange( 0, std::max( 0LL,
1386             logData->getNbLine() - getNbVisibleLines() + 1 ) );
1387 
1388     const int hScrollMaxValue = std::max( 0,
1389             logData->getMaxLength() - getNbVisibleCols() + 1 );
1390     horizontalScrollBar()->setRange( 0, hScrollMaxValue );
1391 }
1392 
1393 void AbstractLogView::drawTextArea( QPaintDevice* paint_device, int32_t delta_y )
1394 {
1395     // LOG( logDEBUG ) << "devicePixelRatio: " << viewport()->devicePixelRatio();
1396     // LOG( logDEBUG ) << "viewport size: " << viewport()->size().width();
1397     // LOG( logDEBUG ) << "pixmap size: " << textPixmap.width();
1398     // Repaint the viewport
1399     QPainter painter( paint_device );
1400     // LOG( logDEBUG ) << "font: " << viewport()->font().family().toStdString();
1401     // LOG( logDEBUG ) << "font painter: " << painter.font().family().toStdString();
1402 
1403     painter.setFont( this->font() );
1404 
1405     const int fontHeight = charHeight_;
1406     const int fontAscent = painter.fontMetrics().ascent();
1407     const int nbCols = getNbVisibleCols();
1408     const int paintDeviceHeight = paint_device->height() / viewport()->devicePixelRatio();
1409     const int paintDeviceWidth = paint_device->width() / viewport()->devicePixelRatio();
1410     const QPalette& palette = viewport()->palette();
1411     std::shared_ptr<const FilterSet> filterSet =
1412         Persistent<FilterSet>( "filterSet" );
1413     QColor foreColor, backColor;
1414 
1415     static const QBrush normalBulletBrush = QBrush( Qt::white );
1416     static const QBrush matchBulletBrush = QBrush( Qt::red );
1417     static const QBrush markBrush = QBrush( "dodgerblue" );
1418 
1419     static const int SEPARATOR_WIDTH = 1;
1420     static const qreal BULLET_AREA_WIDTH = 11;
1421     static const int CONTENT_MARGIN_WIDTH = 1;
1422     static const int LINE_NUMBER_PADDING = 3;
1423 
1424     // First check the lines to be drawn are within range (might not be the case if
1425     // the file has just changed)
1426     const int64_t lines_in_file = logData->getNbLine();
1427 
1428     if ( firstLine > lines_in_file )
1429         firstLine = lines_in_file ? lines_in_file - 1 : 0;
1430 
1431     const int64_t nbLines = std::min(
1432             static_cast<int64_t>( getNbVisibleLines() ), lines_in_file - firstLine );
1433 
1434     const int bottomOfTextPx = nbLines * fontHeight;
1435 
1436     LOG(logDEBUG) << "drawing lines from " << firstLine << " (" << nbLines << " lines)";
1437     LOG(logDEBUG) << "bottomOfTextPx: " << bottomOfTextPx;
1438     LOG(logDEBUG) << "Height: " << paintDeviceHeight;
1439 
1440     // Lines to write
1441     const QStringList lines = logData->getExpandedLines( firstLine, nbLines );
1442 
1443     // First draw the bullet left margin
1444     painter.setPen(palette.color(QPalette::Text));
1445     painter.fillRect( 0, 0,
1446                       BULLET_AREA_WIDTH, paintDeviceHeight,
1447                       Qt::darkGray );
1448 
1449     // Column at which the content should start (pixels)
1450     qreal contentStartPosX = BULLET_AREA_WIDTH + SEPARATOR_WIDTH;
1451 
1452     // This is also the bullet zone width, used for marking clicks
1453     bulletZoneWidthPx_ = contentStartPosX;
1454 
1455     // Update the length of line numbers
1456     const int nbDigitsInLineNumber = countDigits( maxDisplayLineNumber() );
1457 
1458     // Draw the line numbers area
1459     int lineNumberAreaStartX = 0;
1460     if ( lineNumbersVisible_ ) {
1461         int lineNumberWidth = charWidth_ * nbDigitsInLineNumber;
1462         int lineNumberAreaWidth =
1463             2 * LINE_NUMBER_PADDING + lineNumberWidth;
1464         lineNumberAreaStartX = contentStartPosX;
1465 
1466         painter.setPen(palette.color(QPalette::Text));
1467         /* Not sure if it looks good...
1468         painter.drawLine( contentStartPosX + lineNumberAreaWidth,
1469                           0,
1470                           contentStartPosX + lineNumberAreaWidth,
1471                           viewport()->height() );
1472         */
1473         painter.fillRect( contentStartPosX - SEPARATOR_WIDTH, 0,
1474                           lineNumberAreaWidth + SEPARATOR_WIDTH, paintDeviceHeight,
1475                           Qt::lightGray );
1476 
1477         // Update for drawing the actual text
1478         contentStartPosX += lineNumberAreaWidth;
1479     }
1480     else {
1481         painter.fillRect( contentStartPosX - SEPARATOR_WIDTH, 0,
1482                           SEPARATOR_WIDTH + 1, paintDeviceHeight,
1483                           Qt::lightGray );
1484         // contentStartPosX += SEPARATOR_WIDTH;
1485     }
1486 
1487     painter.drawLine( BULLET_AREA_WIDTH, 0,
1488                       BULLET_AREA_WIDTH, paintDeviceHeight - 1 );
1489 
1490     // This is the total width of the 'margin' (including line number if any)
1491     // used for mouse calculation etc...
1492     leftMarginPx_ = contentStartPosX + SEPARATOR_WIDTH;
1493 
1494     // Then draw each line
1495     for (int i = 0; i < nbLines; i++) {
1496         const LineNumber line_index = i + firstLine;
1497 
1498         // Position in pixel of the base line of the line to print
1499         const int yPos = i * fontHeight;
1500         const int xPos = contentStartPosX + CONTENT_MARGIN_WIDTH;
1501 
1502         // string to print, cut to fit the length and position of the view
1503         const QString line = lines[i];
1504         const QString cutLine = line.mid( firstCol, nbCols );
1505 
1506         if ( selection_.isLineSelected( line_index ) ) {
1507             // Reverse the selected line
1508             foreColor = palette.color( QPalette::HighlightedText );
1509             backColor = palette.color( QPalette::Highlight );
1510             painter.setPen(palette.color(QPalette::Text));
1511         }
1512         else if ( filterSet->matchLine( logData->getLineString( line_index ),
1513                     &foreColor, &backColor ) ) {
1514             // Apply a filter to the line
1515         }
1516         else {
1517             // Use the default colors
1518             foreColor = palette.color( QPalette::Text );
1519             backColor = palette.color( QPalette::Base );
1520         }
1521 
1522         // Is there something selected in the line?
1523         int sel_start, sel_end;
1524         bool isSelection =
1525             selection_.getPortionForLine( line_index, &sel_start, &sel_end );
1526         // Has the line got elements to be highlighted
1527         QList<QuickFindMatch> qfMatchList;
1528         bool isMatch =
1529             quickFindPattern_->matchLine( line, qfMatchList );
1530 
1531         if ( isSelection || isMatch ) {
1532             // We use the LineDrawer and its chunks because the
1533             // line has to be somehow highlighted
1534             LineDrawer lineDrawer( backColor );
1535 
1536             // First we create a list of chunks with the highlights
1537             QList<LineChunk> chunkList;
1538             int column = 0; // Current column in line space
1539             foreach( const QuickFindMatch match, qfMatchList ) {
1540                 int start = match.startColumn() - firstCol;
1541                 int end = start + match.length();
1542                 // Ignore matches that are *completely* outside view area
1543                 if ( ( start < 0 && end < 0 ) || start >= nbCols )
1544                     continue;
1545                 if ( start > column )
1546                     chunkList << LineChunk( column, start - 1, LineChunk::Normal );
1547                 column = qMin( start + match.length() - 1, nbCols );
1548                 chunkList << LineChunk( qMax( start, 0 ), column,
1549                         LineChunk::Highlighted );
1550                 column++;
1551             }
1552             if ( column <= cutLine.length() - 1 )
1553                 chunkList << LineChunk( column, cutLine.length() - 1, LineChunk::Normal );
1554 
1555             // Then we add the selection if needed
1556             QList<LineChunk> newChunkList;
1557             if ( isSelection ) {
1558                 sel_start -= firstCol; // coord in line space
1559                 sel_end   -= firstCol;
1560 
1561                 foreach ( const LineChunk chunk, chunkList ) {
1562                     newChunkList << chunk.select( sel_start, sel_end );
1563                 }
1564             }
1565             else
1566                 newChunkList = chunkList;
1567 
1568             foreach ( const LineChunk chunk, newChunkList ) {
1569                 // Select the colours
1570                 QColor fore;
1571                 QColor back;
1572                 switch ( chunk.type() ) {
1573                     case LineChunk::Normal:
1574                         fore = foreColor;
1575                         back = backColor;
1576                         break;
1577                     case LineChunk::Highlighted:
1578                         fore = QColor( "black" );
1579                         back = QColor( "yellow" );
1580                         // fore = highlightForeColor;
1581                         // back = highlightBackColor;
1582                         break;
1583                     case LineChunk::Selected:
1584                         fore = palette.color( QPalette::HighlightedText ),
1585                              back = palette.color( QPalette::Highlight );
1586                         break;
1587                 }
1588                 lineDrawer.addChunk ( chunk, fore, back );
1589             }
1590 
1591             lineDrawer.draw( painter, xPos, yPos,
1592                     viewport()->width(), cutLine,
1593                     CONTENT_MARGIN_WIDTH );
1594         }
1595         else {
1596             // Nothing to be highlighted, we print the whole line!
1597             painter.fillRect( xPos - CONTENT_MARGIN_WIDTH, yPos,
1598                     viewport()->width(), fontHeight, backColor );
1599             // (the rectangle is extended on the left to cover the small
1600             // margin, it looks better (LineDrawer does the same) )
1601             painter.setPen( foreColor );
1602             painter.drawText( xPos, yPos + fontAscent, cutLine );
1603         }
1604 
1605         // Then draw the bullet
1606         painter.setPen( palette.color( QPalette::Text ) );
1607         const qreal circleSize = 3;
1608         const qreal arrowHeight = 4;
1609         const qreal middleXLine = BULLET_AREA_WIDTH / 2;
1610         const qreal middleYLine = yPos + (fontHeight / 2);
1611 
1612         const LineType line_type = lineType( line_index );
1613         if ( line_type == Marked ) {
1614             // A pretty arrow if the line is marked
1615             const QPointF points[7] = {
1616                 QPointF(1, middleYLine - 2),
1617                 QPointF(middleXLine, middleYLine - 2),
1618                 QPointF(middleXLine, middleYLine - arrowHeight),
1619                 QPointF(BULLET_AREA_WIDTH - 1, middleYLine),
1620                 QPointF(middleXLine, middleYLine + arrowHeight),
1621                 QPointF(middleXLine, middleYLine + 2),
1622                 QPointF(1, middleYLine + 2 ),
1623             };
1624 
1625             painter.setBrush( markBrush );
1626             painter.drawPolygon( points, 7 );
1627         }
1628         else {
1629             // For pretty circles
1630             painter.setRenderHint( QPainter::Antialiasing );
1631 
1632             if ( lineType( line_index ) == Match )
1633                 painter.setBrush( matchBulletBrush );
1634             else
1635                 painter.setBrush( normalBulletBrush );
1636             painter.drawEllipse( middleXLine - circleSize,
1637                     middleYLine - circleSize,
1638                     circleSize * 2, circleSize * 2 );
1639         }
1640 
1641         // Draw the line number
1642         if ( lineNumbersVisible_ ) {
1643             static const QString lineNumberFormat( "%1" );
1644             const QString& lineNumberStr =
1645                 lineNumberFormat.arg( displayLineNumber( line_index ),
1646                         nbDigitsInLineNumber );
1647             painter.setPen( palette.color( QPalette::Text ) );
1648             painter.drawText( lineNumberAreaStartX + LINE_NUMBER_PADDING,
1649                     yPos + fontAscent, lineNumberStr );
1650         }
1651     } // For each line
1652 
1653     if ( bottomOfTextPx < paintDeviceHeight ) {
1654         // The lines don't cover the whole device
1655         painter.fillRect( contentStartPosX, bottomOfTextPx,
1656                 paintDeviceWidth - contentStartPosX,
1657                 paintDeviceHeight, palette.color( QPalette::Window ) );
1658     }
1659 }
1660 
1661 // Draw the "pull to follow" bar and return a pixmap.
1662 // The width is passed in "logic" pixels.
1663 QPixmap AbstractLogView::drawPullToFollowBar( int width, float pixel_ratio )
1664 {
1665     static constexpr int barWidth = 40;
1666     QPixmap pixmap ( static_cast<float>( width ) * pixel_ratio, barWidth * 6.0 );
1667     pixmap.setDevicePixelRatio( pixel_ratio );
1668     pixmap.fill( this->palette().color( this->backgroundRole() ) );
1669     const int nbBars = width / (barWidth * 2) + 1;
1670 
1671     QPainter painter( &pixmap );
1672     painter.setPen( QPen( QColor( 0, 0, 0, 0 ) ) );
1673     painter.setBrush( QBrush( QColor( "lightyellow" ) ) );
1674 
1675     for ( int i = 0; i < nbBars; ++i ) {
1676         QPoint points[4] = {
1677             { (i*2+1)*barWidth, 0 },
1678             { 0, (i*2+1)*barWidth },
1679             { 0, (i+1)*2*barWidth },
1680             { (i+1)*2*barWidth, 0 }
1681         };
1682         painter.drawConvexPolygon( points, 4 );
1683     }
1684 
1685     return pixmap;
1686 }
1687 
1688 void AbstractLogView::disableFollow()
1689 {
1690     emit followModeChanged( false );
1691     followElasticHook_.hook( false );
1692 }
1693 
1694 namespace {
1695 
1696 // Convert the length of the pull to follow bar to pixels
1697 int mapPullToFollowLength( int length )
1698 {
1699     return length / 14;
1700 }
1701 
1702 };
1703