xref: /glogg/src/crawlerwidget.cpp (revision f049f87fc315bc7e68fc0a52b15c5b79496761d2)
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Nicolas Bonnefon and other contributors
3  *
4  * This file is part of glogg.
5  *
6  * glogg is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * glogg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with glogg.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 // This file implements the CrawlerWidget class.
21 // It is responsible for creating and managing the two views and all
22 // the UI elements.  It implements the connection between the UI elements.
23 // It also interacts with the sets of data (full and filtered).
24 
25 #include "log.h"
26 
27 #include <cassert>
28 
29 #include <Qt>
30 #include <QApplication>
31 #include <QFile>
32 #include <QLineEdit>
33 #include <QFileInfo>
34 #include <QKeyEvent>
35 #include <QStandardItemModel>
36 #include <QHeaderView>
37 #include <QListView>
38 
39 #include "crawlerwidget.h"
40 
41 #include "quickfindpattern.h"
42 #include "overview.h"
43 #include "infoline.h"
44 #include "savedsearches.h"
45 #include "quickfindwidget.h"
46 #include "persistentinfo.h"
47 #include "configuration.h"
48 
49 // Palette for error signaling (yellow background)
50 const QPalette CrawlerWidget::errorPalette( QColor( "yellow" ) );
51 
52 // Implementation of the view context for the CrawlerWidget
53 class CrawlerWidgetContext : public ViewContextInterface {
54   public:
55     // Construct from the stored string representation
56     CrawlerWidgetContext( const char* string );
57     // Construct from the value passsed
58     CrawlerWidgetContext( QList<int> sizes,
59            bool ignore_case,
60            bool auto_refresh )
61         : sizes_( sizes ),
62           ignore_case_( ignore_case ),
63           auto_refresh_( auto_refresh ) {}
64 
65     // Implementation of the ViewContextInterface function
66     std::string toString() const;
67 
68     // Access the Qt sizes array for the QSplitter
69     QList<int> sizes() const { return sizes_; }
70 
71     bool ignoreCase() const { return ignore_case_; }
72     bool autoRefresh() const { return auto_refresh_; }
73 
74   private:
75     QList<int> sizes_;
76 
77     bool ignore_case_;
78     bool auto_refresh_;
79 };
80 
81 // Constructor only does trivial construction. The real work is done once
82 // the data is attached.
83 CrawlerWidget::CrawlerWidget( QWidget *parent )
84         : QSplitter( parent ), overview_()
85 {
86     logData_         = nullptr;
87     logFilteredData_ = nullptr;
88 
89     quickFindPattern_ = nullptr;
90     savedSearches_   = nullptr;
91     qfSavedFocus_    = nullptr;
92 
93     // Until we have received confirmation loading is finished, we
94     // should consider we are loading something.
95     loadingInProgress_ = true;
96 
97     currentLineNumber_ = 0;
98 }
99 
100 // The top line is first one on the main display
101 int CrawlerWidget::getTopLine() const
102 {
103     return logMainView->getTopLine();
104 }
105 
106 QString CrawlerWidget::getSelectedText() const
107 {
108     if ( filteredView->hasFocus() )
109         return filteredView->getSelection();
110     else
111         return logMainView->getSelection();
112 }
113 
114 void CrawlerWidget::selectAll()
115 {
116     activeView()->selectAll();
117 }
118 
119 // Return a pointer to the view in which we should do the QuickFind
120 SearchableWidgetInterface* CrawlerWidget::doGetActiveSearchable() const
121 {
122     return activeView();
123 }
124 
125 // Return all the searchable widgets (views)
126 std::vector<QObject*> CrawlerWidget::doGetAllSearchables() const
127 {
128     std::vector<QObject*> searchables =
129     { logMainView, filteredView };
130 
131     return searchables;
132 }
133 
134 // Update the state of the parent
135 void CrawlerWidget::doSendAllStateSignals()
136 {
137     emit updateLineNumber( currentLineNumber_ );
138     if ( !loadingInProgress_ )
139         emit loadingFinished( LoadingStatus::Successful );
140 }
141 
142 //
143 // Public slots
144 //
145 
146 void CrawlerWidget::stopLoading()
147 {
148     logFilteredData_->interruptSearch();
149     logData_->interruptLoading();
150 }
151 
152 void CrawlerWidget::reload()
153 {
154     searchState_.resetState();
155     logFilteredData_->clearSearch();
156     filteredView->updateData();
157     printSearchInfoMessage();
158 
159     logData_->reload();
160 }
161 
162 //
163 // Protected functions
164 //
165 void CrawlerWidget::doSetData(
166         std::shared_ptr<LogData> log_data,
167         std::shared_ptr<LogFilteredData> filtered_data )
168 {
169     logData_         = log_data.get();
170     logFilteredData_ = filtered_data.get();
171 }
172 
173 void CrawlerWidget::doSetQuickFindPattern(
174         std::shared_ptr<QuickFindPattern> qfp )
175 {
176     quickFindPattern_ = qfp;
177 }
178 
179 void CrawlerWidget::doSetSavedSearches(
180         std::shared_ptr<SavedSearches> saved_searches )
181 {
182     savedSearches_ = saved_searches;
183 
184     // We do setup now, assuming doSetData has been called before
185     // us, that's not great really...
186     setup();
187 }
188 
189 void CrawlerWidget::doSetViewContext(
190         const char* view_context )
191 {
192     LOG(logDEBUG) << "CrawlerWidget::doSetViewContext: " << view_context;
193 
194     CrawlerWidgetContext context = { view_context };
195 
196     setSizes( context.sizes() );
197     ignoreCaseCheck->setCheckState( context.ignoreCase() ? Qt::Checked : Qt::Unchecked );
198 
199     auto auto_refresh_check_state = context.autoRefresh() ? Qt::Checked : Qt::Unchecked;
200     searchRefreshCheck->setCheckState( auto_refresh_check_state );
201     // Manually call the handler as it is not called when changing the state programmatically
202     searchRefreshChangedHandler( auto_refresh_check_state );
203 }
204 
205 std::shared_ptr<const ViewContextInterface>
206 CrawlerWidget::doGetViewContext() const
207 {
208     auto context = std::make_shared<const CrawlerWidgetContext>(
209             sizes(),
210             ( ignoreCaseCheck->checkState() == Qt::Checked ),
211             ( searchRefreshCheck->checkState() == Qt::Checked ) );
212 
213     return static_cast<std::shared_ptr<const ViewContextInterface>>( context );
214 }
215 
216 //
217 // Slots
218 //
219 
220 void CrawlerWidget::startNewSearch()
221 {
222     // Record the search line in the recent list
223     // (reload the list first in case another glogg changed it)
224     GetPersistentInfo().retrieve( "savedSearches" );
225     savedSearches_->addRecent( searchLineEdit->currentText() );
226     GetPersistentInfo().save( "savedSearches" );
227 
228     // Update the SearchLine (history)
229     updateSearchCombo();
230     // Call the private function to do the search
231     replaceCurrentSearch( searchLineEdit->currentText() );
232 }
233 
234 void CrawlerWidget::stopSearch()
235 {
236     logFilteredData_->interruptSearch();
237     searchState_.stopSearch();
238     printSearchInfoMessage();
239 }
240 
241 // When receiving the 'newDataAvailable' signal from LogFilteredData
242 void CrawlerWidget::updateFilteredView( int nbMatches, int progress )
243 {
244     LOG(logDEBUG) << "updateFilteredView received.";
245 
246     if ( progress == 100 ) {
247         // Searching done
248         printSearchInfoMessage( nbMatches );
249         searchInfoLine->hideGauge();
250         // De-activate the stop button
251         stopButton->setEnabled( false );
252     }
253     else {
254         // Search in progress
255         // We ignore 0% and 100% to avoid a flash when the search is very short
256         if ( progress > 0 ) {
257             searchInfoLine->setText(
258                     tr("Search in progress (%1 %)... %2 match%3 found so far.")
259                     .arg( progress )
260                     .arg( nbMatches )
261                     .arg( nbMatches > 1 ? "es" : "" ) );
262             searchInfoLine->displayGauge( progress );
263         }
264     }
265 
266     // Recompute the content of the filtered window.
267     filteredView->updateData();
268 
269     // Update the match overview
270     overview_.updateData( logData_->getNbLine() );
271 
272     // Also update the top window for the coloured bullets.
273     update();
274 }
275 
276 void CrawlerWidget::jumpToMatchingLine(int filteredLineNb)
277 {
278     int mainViewLine = logFilteredData_->getMatchingLineNumber(filteredLineNb);
279     logMainView->selectAndDisplayLine(mainViewLine);  // FIXME: should be done with a signal.
280 }
281 
282 void CrawlerWidget::updateLineNumberHandler( int line )
283 {
284     currentLineNumber_ = line;
285     emit updateLineNumber( line );
286 }
287 
288 void CrawlerWidget::markLineFromMain( qint64 line )
289 {
290     if ( logFilteredData_->isLineMarked( line ) )
291         logFilteredData_->deleteMark( line );
292     else
293         logFilteredData_->addMark( line );
294 
295     // Recompute the content of the filtered window.
296     filteredView->updateData();
297 
298     // Update the match overview
299     overview_.updateData( logData_->getNbLine() );
300 
301     // Also update the top window for the coloured bullets.
302     update();
303 }
304 
305 void CrawlerWidget::markLineFromFiltered( qint64 line )
306 {
307     qint64 line_in_file = logFilteredData_->getMatchingLineNumber( line );
308     if ( logFilteredData_->filteredLineTypeByIndex( line )
309             == LogFilteredData::Mark )
310         logFilteredData_->deleteMark( line_in_file );
311     else
312         logFilteredData_->addMark( line_in_file );
313 
314     // Recompute the content of the filtered window.
315     filteredView->updateData();
316 
317     // Update the match overview
318     overview_.updateData( logData_->getNbLine() );
319 
320     // Also update the top window for the coloured bullets.
321     update();
322 }
323 
324 void CrawlerWidget::applyConfiguration()
325 {
326     std::shared_ptr<Configuration> config =
327         Persistent<Configuration>( "settings" );
328     QFont font = config->mainFont();
329 
330     LOG(logDEBUG) << "CrawlerWidget::applyConfiguration";
331 
332     // Whatever font we use, we should NOT use kerning
333     font.setKerning( false );
334     font.setFixedPitch( true );
335 #if QT_VERSION > 0x040700
336     // Necessary on systems doing subpixel positionning (e.g. Ubuntu 12.04)
337     font.setStyleStrategy( QFont::ForceIntegerMetrics );
338 #endif
339     logMainView->setFont(font);
340     filteredView->setFont(font);
341 
342     logMainView->setLineNumbersVisible( config->mainLineNumbersVisible() );
343     filteredView->setLineNumbersVisible( config->filteredLineNumbersVisible() );
344 
345     overview_.setVisible( config->isOverviewVisible() );
346     logMainView->refreshOverview();
347 
348     logMainView->updateDisplaySize();
349     logMainView->update();
350     filteredView->updateDisplaySize();
351     filteredView->update();
352 
353     // Update the SearchLine (history)
354     updateSearchCombo();
355 }
356 
357 void CrawlerWidget::enteringQuickFind()
358 {
359     LOG(logDEBUG) << "CrawlerWidget::enteringQuickFind";
360 
361     // Remember who had the focus (only if it is one of our views)
362     QWidget* focus_widget =  QApplication::focusWidget();
363 
364     if ( ( focus_widget == logMainView ) || ( focus_widget == filteredView ) )
365         qfSavedFocus_ = focus_widget;
366     else
367         qfSavedFocus_ = nullptr;
368 }
369 
370 void CrawlerWidget::exitingQuickFind()
371 {
372     // Restore the focus once the QFBar has been hidden
373     if ( qfSavedFocus_ )
374         qfSavedFocus_->setFocus();
375 }
376 
377 void CrawlerWidget::loadingFinishedHandler( LoadingStatus status )
378 {
379     loadingInProgress_ = false;
380 
381     // We need to refresh the main window because the view lines on the
382     // overview have probably changed.
383     overview_.updateData( logData_->getNbLine() );
384 
385     // FIXME, handle topLine
386     // logMainView->updateData( logData_, topLine );
387     logMainView->updateData();
388 
389         // Shall we Forbid starting a search when loading in progress?
390         // searchButton->setEnabled( false );
391 
392     // searchButton->setEnabled( true );
393 
394     // See if we need to auto-refresh the search
395     if ( searchState_.isAutorefreshAllowed() ) {
396         if ( searchState_.isFileTruncated() )
397             // We need to restart the search
398             replaceCurrentSearch( searchLineEdit->currentText() );
399         else
400             logFilteredData_->updateSearch();
401     }
402 
403     emit loadingFinished( status );
404 }
405 
406 void CrawlerWidget::fileChangedHandler( LogData::MonitoredFileStatus status )
407 {
408     // Handle the case where the file has been truncated
409     if ( status == LogData::Truncated ) {
410         // Clear all marks (TODO offer the option to keep them)
411         logFilteredData_->clearMarks();
412         if ( ! searchInfoLine->text().isEmpty() ) {
413             // Invalidate the search
414             logFilteredData_->clearSearch();
415             filteredView->updateData();
416             searchState_.truncateFile();
417             printSearchInfoMessage();
418         }
419     }
420 }
421 
422 // Returns a pointer to the window in which the search should be done
423 AbstractLogView* CrawlerWidget::activeView() const
424 {
425     QWidget* activeView;
426 
427     // Search in the window that has focus, or the window where 'Find' was
428     // called from, or the main window.
429     if ( filteredView->hasFocus() || logMainView->hasFocus() )
430         activeView = QApplication::focusWidget();
431     else
432         activeView = qfSavedFocus_;
433 
434     if ( activeView ) {
435         AbstractLogView* view = qobject_cast<AbstractLogView*>( activeView );
436         return view;
437     }
438     else {
439         LOG(logWARNING) << "No active view, defaulting to logMainView";
440         return logMainView;
441     }
442 }
443 
444 void CrawlerWidget::searchForward()
445 {
446     LOG(logDEBUG) << "CrawlerWidget::searchForward";
447 
448     activeView()->searchForward();
449 }
450 
451 void CrawlerWidget::searchBackward()
452 {
453     LOG(logDEBUG) << "CrawlerWidget::searchBackward";
454 
455     activeView()->searchBackward();
456 }
457 
458 void CrawlerWidget::searchRefreshChangedHandler( int state )
459 {
460     searchState_.setAutorefresh( state == Qt::Checked );
461     printSearchInfoMessage( logFilteredData_->getNbMatches() );
462 }
463 
464 void CrawlerWidget::searchTextChangeHandler()
465 {
466     // We suspend auto-refresh
467     searchState_.changeExpression();
468     printSearchInfoMessage( logFilteredData_->getNbMatches() );
469 }
470 
471 void CrawlerWidget::changeFilteredViewVisibility( int index )
472 {
473     QStandardItem* item = visibilityModel_->item( index );
474     FilteredView::Visibility visibility =
475         static_cast< FilteredView::Visibility>( item->data().toInt() );
476 
477     filteredView->setVisibility( visibility );
478 }
479 
480 void CrawlerWidget::addToSearch( const QString& string )
481 {
482     QString text = searchLineEdit->currentText();
483 
484     if ( text.isEmpty() )
485         text = string;
486     else {
487         // Escape the regexp chars from the string before adding it.
488         text += ( '|' + QRegExp::escape( string ) );
489     }
490 
491     searchLineEdit->setEditText( text );
492 
493     // Set the focus to lineEdit so that the user can press 'Return' immediately
494     searchLineEdit->lineEdit()->setFocus();
495 }
496 
497 void CrawlerWidget::mouseHoveredOverMatch( qint64 line )
498 {
499     qint64 line_in_mainview = logFilteredData_->getMatchingLineNumber( line );
500 
501     overviewWidget_->highlightLine( line_in_mainview );
502 }
503 
504 //
505 // Private functions
506 //
507 
508 // Build the widget and connect all the signals, this must be done once
509 // the data are attached.
510 void CrawlerWidget::setup()
511 {
512     setOrientation(Qt::Vertical);
513 
514     assert( logData_ );
515     assert( logFilteredData_ );
516 
517     // The views
518     bottomWindow = new QWidget;
519     overviewWidget_ = new OverviewWidget();
520     logMainView     = new LogMainView(
521             logData_, quickFindPattern_.get(), &overview_, overviewWidget_ );
522     filteredView    = new FilteredView(
523             logFilteredData_, quickFindPattern_.get() );
524 
525     overviewWidget_->setOverview( &overview_ );
526     overviewWidget_->setParent( logMainView );
527 
528     // Construct the visibility button
529     visibilityModel_ = new QStandardItemModel( this );
530 
531     QStandardItem *marksAndMatchesItem = new QStandardItem( tr( "Marks and matches" ) );
532     QPixmap marksAndMatchesPixmap( 16, 10 );
533     marksAndMatchesPixmap.fill( Qt::gray );
534     marksAndMatchesItem->setIcon( QIcon( marksAndMatchesPixmap ) );
535     marksAndMatchesItem->setData( FilteredView::MarksAndMatches );
536     visibilityModel_->appendRow( marksAndMatchesItem );
537 
538     QStandardItem *marksItem = new QStandardItem( tr( "Marks" ) );
539     QPixmap marksPixmap( 16, 10 );
540     marksPixmap.fill( Qt::blue );
541     marksItem->setIcon( QIcon( marksPixmap ) );
542     marksItem->setData( FilteredView::MarksOnly );
543     visibilityModel_->appendRow( marksItem );
544 
545     QStandardItem *matchesItem = new QStandardItem( tr( "Matches" ) );
546     QPixmap matchesPixmap( 16, 10 );
547     matchesPixmap.fill( Qt::red );
548     matchesItem->setIcon( QIcon( matchesPixmap ) );
549     matchesItem->setData( FilteredView::MatchesOnly );
550     visibilityModel_->appendRow( matchesItem );
551 
552     QListView *visibilityView = new QListView( this );
553     visibilityView->setMovement( QListView::Static );
554     visibilityView->setMinimumWidth( 170 ); // Only needed with custom style-sheet
555 
556     visibilityBox = new QComboBox();
557     visibilityBox->setModel( visibilityModel_ );
558     visibilityBox->setView( visibilityView );
559 
560     // Select "Marks and matches" by default (same default as the filtered view)
561     visibilityBox->setCurrentIndex( 0 );
562 
563     // TODO: Maybe there is some way to set the popup width to be
564     // sized-to-content (as it is when the stylesheet is not overriden) in the
565     // stylesheet as opposed to setting a hard min-width on the view above.
566     visibilityBox->setStyleSheet( " \
567         QComboBox:on {\
568             padding: 1px 2px 1px 6px;\
569             width: 19px;\
570         } \
571         QComboBox:!on {\
572             padding: 1px 2px 1px 7px;\
573             width: 19px;\
574             height: 16px;\
575             border: 1px solid gray;\
576         } \
577         QComboBox::drop-down::down-arrow {\
578             width: 0px;\
579             border-width: 0px;\
580         } \
581 " );
582 
583     // Construct the Search Info line
584     searchInfoLine = new InfoLine();
585     searchInfoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
586     searchInfoLine->setLineWidth( 1 );
587     searchInfoLineDefaultPalette = searchInfoLine->palette();
588 
589     ignoreCaseCheck = new QCheckBox( "Ignore &case" );
590     searchRefreshCheck = new QCheckBox( "Auto-&refresh" );
591 
592     // Construct the Search line
593     searchLabel = new QLabel(tr("&Text: "));
594     searchLineEdit = new QComboBox;
595     searchLineEdit->setEditable( true );
596     searchLineEdit->setCompleter( 0 );
597     searchLineEdit->addItems( savedSearches_->recentSearches() );
598     searchLineEdit->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum );
599     searchLineEdit->setSizeAdjustPolicy( QComboBox::AdjustToMinimumContentsLengthWithIcon );
600 
601     searchLabel->setBuddy( searchLineEdit );
602 
603     searchButton = new QToolButton();
604     searchButton->setText( tr("&Search") );
605     searchButton->setAutoRaise( true );
606 
607     stopButton = new QToolButton();
608     stopButton->setIcon( QIcon(":/images/stop16.png") );
609     stopButton->setAutoRaise( true );
610     stopButton->setEnabled( false );
611 
612     QHBoxLayout* searchLineLayout = new QHBoxLayout;
613     searchLineLayout->addWidget(searchLabel);
614     searchLineLayout->addWidget(searchLineEdit);
615     searchLineLayout->addWidget(searchButton);
616     searchLineLayout->addWidget(stopButton);
617     searchLineLayout->setContentsMargins(6, 0, 6, 0);
618     stopButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
619     searchButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
620 
621     QHBoxLayout* searchInfoLineLayout = new QHBoxLayout;
622     searchInfoLineLayout->addWidget( visibilityBox );
623     searchInfoLineLayout->addWidget( searchInfoLine );
624     searchInfoLineLayout->addWidget( ignoreCaseCheck );
625     searchInfoLineLayout->addWidget( searchRefreshCheck );
626 
627     // Construct the bottom window
628     QVBoxLayout* bottomMainLayout = new QVBoxLayout;
629     bottomMainLayout->addLayout(searchLineLayout);
630     bottomMainLayout->addLayout(searchInfoLineLayout);
631     bottomMainLayout->addWidget(filteredView);
632     bottomMainLayout->setContentsMargins(2, 1, 2, 1);
633     bottomWindow->setLayout(bottomMainLayout);
634 
635     addWidget( logMainView );
636     addWidget( bottomWindow );
637 
638     // Default splitter position (usually overridden by the config file)
639     QList<int> splitterSizes;
640     splitterSizes += 400;
641     splitterSizes += 100;
642     setSizes( splitterSizes );
643 
644     // Default search checkboxes
645     auto config = Persistent<Configuration>( "settings" );
646     searchRefreshCheck->setCheckState( config->isSearchAutoRefreshDefault() ?
647             Qt::Checked : Qt::Unchecked );
648     ignoreCaseCheck->setCheckState( config->isSearchIgnoreCaseDefault() ?
649             Qt::Checked : Qt::Unchecked );
650 
651     // Connect the signals
652     connect(searchLineEdit->lineEdit(), SIGNAL( returnPressed() ),
653             searchButton, SIGNAL( clicked() ));
654     connect(searchLineEdit->lineEdit(), SIGNAL( textEdited( const QString& ) ),
655             this, SLOT( searchTextChangeHandler() ));
656     connect(searchButton, SIGNAL( clicked() ),
657             this, SLOT( startNewSearch() ) );
658     connect(stopButton, SIGNAL( clicked() ),
659             this, SLOT( stopSearch() ) );
660 
661     connect(visibilityBox, SIGNAL( currentIndexChanged( int ) ),
662             this, SLOT( changeFilteredViewVisibility( int ) ) );
663 
664     connect(logMainView, SIGNAL( newSelection( int ) ),
665             logMainView, SLOT( update() ) );
666     connect(filteredView, SIGNAL( newSelection( int ) ),
667             this, SLOT( jumpToMatchingLine( int ) ) );
668     connect(filteredView, SIGNAL( newSelection( int ) ),
669             filteredView, SLOT( update() ) );
670     connect(logMainView, SIGNAL( updateLineNumber( int ) ),
671             this, SLOT( updateLineNumberHandler( int ) ) );
672     connect(logMainView, SIGNAL( markLine( qint64 ) ),
673             this, SLOT( markLineFromMain( qint64 ) ) );
674     connect(filteredView, SIGNAL( markLine( qint64 ) ),
675             this, SLOT( markLineFromFiltered( qint64 ) ) );
676 
677     connect(logMainView, SIGNAL( addToSearch( const QString& ) ),
678             this, SLOT( addToSearch( const QString& ) ) );
679     connect(filteredView, SIGNAL( addToSearch( const QString& ) ),
680             this, SLOT( addToSearch( const QString& ) ) );
681 
682     connect(filteredView, SIGNAL( mouseHoveredOverLine( qint64 ) ),
683             this, SLOT( mouseHoveredOverMatch( qint64 ) ) );
684     connect(filteredView, SIGNAL( mouseLeftHoveringZone() ),
685             overviewWidget_, SLOT( removeHighlight() ) );
686 
687     // Follow option (up and down)
688     connect(this, SIGNAL( followSet( bool ) ),
689             logMainView, SLOT( followSet( bool ) ) );
690     connect(this, SIGNAL( followSet( bool ) ),
691             filteredView, SLOT( followSet( bool ) ) );
692     connect(logMainView, SIGNAL( followDisabled() ),
693             this, SIGNAL( followDisabled() ) );
694     connect(filteredView, SIGNAL( followDisabled() ),
695             this, SIGNAL( followDisabled() ) );
696 
697     connect( logFilteredData_, SIGNAL( searchProgressed( int, int ) ),
698             this, SLOT( updateFilteredView( int, int ) ) );
699 
700     // Sent load file update to MainWindow (for status update)
701     connect( logData_, SIGNAL( loadingProgressed( int ) ),
702             this, SIGNAL( loadingProgressed( int ) ) );
703     connect( logData_, SIGNAL( loadingFinished( LoadingStatus ) ),
704             this, SLOT( loadingFinishedHandler( LoadingStatus ) ) );
705     connect( logData_, SIGNAL( fileChanged( LogData::MonitoredFileStatus ) ),
706             this, SLOT( fileChangedHandler( LogData::MonitoredFileStatus ) ) );
707 
708     // Search auto-refresh
709     connect( searchRefreshCheck, SIGNAL( stateChanged( int ) ),
710             this, SLOT( searchRefreshChangedHandler( int ) ) );
711 
712     // Advise the parent the checkboxes have been changed
713     // (for maintaining default config)
714     connect( searchRefreshCheck, SIGNAL( stateChanged( int ) ),
715             this, SIGNAL( searchRefreshChanged( int ) ) );
716     connect( ignoreCaseCheck, SIGNAL( stateChanged( int ) ),
717             this, SIGNAL( ignoreCaseChanged( int ) ) );
718 }
719 
720 // Create a new search using the text passed, replace the currently
721 // used one and destroy the old one.
722 void CrawlerWidget::replaceCurrentSearch( const QString& searchText )
723 {
724     // Interrupt the search if it's ongoing
725     logFilteredData_->interruptSearch();
726 
727     // We have to wait for the last search update (100%)
728     // before clearing/restarting to avoid having remaining results.
729 
730     // FIXME: this is a bit of a hack, we call processEvents
731     // for Qt to empty its event queue, including (hopefully)
732     // the search update event sent by logFilteredData_. It saves
733     // us the overhead of having proper sync.
734     QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
735 
736     if ( !searchText.isEmpty() ) {
737         // Determine the type of regexp depending on the config
738         QRegExp::PatternSyntax syntax;
739         static std::shared_ptr<Configuration> config =
740             Persistent<Configuration>( "settings" );
741         switch ( config->mainRegexpType() ) {
742             case Wildcard:
743                 syntax = QRegExp::Wildcard;
744                 break;
745             case FixedString:
746                 syntax = QRegExp::FixedString;
747                 break;
748             default:
749                 syntax = QRegExp::RegExp2;
750                 break;
751         }
752 
753         // Set the pattern case insensitive if needed
754         Qt::CaseSensitivity case_sensitivity = Qt::CaseSensitive;
755         if ( ignoreCaseCheck->checkState() == Qt::Checked )
756             case_sensitivity = Qt::CaseInsensitive;
757 
758         // Constructs the regexp
759         QRegExp regexp( searchText, case_sensitivity, syntax );
760 
761         if ( regexp.isValid() ) {
762             // Activate the stop button
763             stopButton->setEnabled( true );
764             // Start a new asynchronous search
765             logFilteredData_->runSearch( regexp );
766             // Accept auto-refresh of the search
767             searchState_.startSearch();
768         }
769         else {
770             // The regexp is wrong
771             logFilteredData_->clearSearch();
772             filteredView->updateData();
773             searchState_.resetState();
774 
775             // Inform the user
776             QString errorMessage = tr("Error in expression: ");
777             errorMessage += regexp.errorString();
778             searchInfoLine->setPalette( errorPalette );
779             searchInfoLine->setText( errorMessage );
780         }
781     }
782     else {
783         logFilteredData_->clearSearch();
784         filteredView->updateData();
785         searchState_.resetState();
786         printSearchInfoMessage();
787     }
788     // Connect the search to the top view
789     logMainView->useNewFiltering( logFilteredData_ );
790 }
791 
792 // Updates the content of the drop down list for the saved searches,
793 // called when the SavedSearch has been changed.
794 void CrawlerWidget::updateSearchCombo()
795 {
796     const QString text = searchLineEdit->lineEdit()->text();
797     searchLineEdit->clear();
798     searchLineEdit->addItems( savedSearches_->recentSearches() );
799     // In case we had something that wasn't added to the list (blank...):
800     searchLineEdit->lineEdit()->setText( text );
801 }
802 
803 // Print the search info message.
804 void CrawlerWidget::printSearchInfoMessage( int nbMatches )
805 {
806     QString text;
807 
808     switch ( searchState_.getState() ) {
809         case SearchState::NoSearch:
810             // Blank text is fine
811             break;
812         case SearchState::Static:
813             text = tr("%1 match%2 found.").arg( nbMatches )
814                 .arg( nbMatches > 1 ? "es" : "" );
815             break;
816         case SearchState::Autorefreshing:
817             text = tr("%1 match%2 found. Search is auto-refreshing...").arg( nbMatches )
818                 .arg( nbMatches > 1 ? "es" : "" );
819             break;
820         case SearchState::FileTruncated:
821         case SearchState::TruncatedAutorefreshing:
822             text = tr("File truncated on disk, previous search results are not valid anymore.");
823             break;
824     }
825 
826     searchInfoLine->setPalette( searchInfoLineDefaultPalette );
827     searchInfoLine->setText( text );
828 }
829 
830 //
831 // SearchState implementation
832 //
833 void CrawlerWidget::SearchState::resetState()
834 {
835     state_ = NoSearch;
836 }
837 
838 void CrawlerWidget::SearchState::setAutorefresh( bool refresh )
839 {
840     autoRefreshRequested_ = refresh;
841 
842     if ( refresh ) {
843         if ( state_ == Static )
844             state_ = Autorefreshing;
845         /*
846         else if ( state_ == FileTruncated )
847             state_ = TruncatedAutorefreshing;
848         */
849     }
850     else {
851         if ( state_ == Autorefreshing )
852             state_ = Static;
853         else if ( state_ == TruncatedAutorefreshing )
854             state_ = FileTruncated;
855     }
856 }
857 
858 void CrawlerWidget::SearchState::truncateFile()
859 {
860     if ( state_ == Autorefreshing || state_ == TruncatedAutorefreshing ) {
861         state_ = TruncatedAutorefreshing;
862     }
863     else {
864         state_ = FileTruncated;
865     }
866 }
867 
868 void CrawlerWidget::SearchState::changeExpression()
869 {
870     if ( state_ == Autorefreshing )
871         state_ = Static;
872 }
873 
874 void CrawlerWidget::SearchState::stopSearch()
875 {
876     if ( state_ == Autorefreshing )
877         state_ = Static;
878 }
879 
880 void CrawlerWidget::SearchState::startSearch()
881 {
882     if ( autoRefreshRequested_ )
883         state_ = Autorefreshing;
884     else
885         state_ = Static;
886 }
887 
888 /*
889  * CrawlerWidgetContext
890  */
891 CrawlerWidgetContext::CrawlerWidgetContext( const char* string )
892 {
893     QRegExp regex = QRegExp( "S(\\d+):(\\d+)" );
894 
895     if ( regex.indexIn( string ) > -1 ) {
896         sizes_ = { regex.cap(1).toInt(), regex.cap(2).toInt() };
897         LOG(logDEBUG) << "sizes_: " << sizes_[0] << " " << sizes_[1];
898     }
899     else {
900         LOG(logWARNING) << "Unrecognised view size: " << string;
901 
902         // Default values;
903         sizes_ = { 100, 400 };
904     }
905 
906     QRegExp case_refresh_regex = QRegExp( "IC(\\d+):AR(\\d+)" );
907 
908     if ( case_refresh_regex.indexIn( string ) > -1 ) {
909         ignore_case_ = ( case_refresh_regex.cap(1).toInt() == 1 );
910         auto_refresh_ = ( case_refresh_regex.cap(2).toInt() == 1 );
911 
912         LOG(logDEBUG) << "ignore_case_: " << ignore_case_ << " auto_refresh_: "
913             << auto_refresh_;
914     }
915     else {
916         LOG(logWARNING) << "Unrecognised case/refresh: " << string;
917         ignore_case_ = false;
918         auto_refresh_ = false;
919     }
920 }
921 
922 std::string CrawlerWidgetContext::toString() const
923 {
924     char string[160];
925 
926     snprintf( string, sizeof string, "S%d:%d:IC%d:AR%d",
927             sizes_[0], sizes_[1],
928             ignore_case_, auto_refresh_ );
929 
930     return { string };
931 }
932