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