xref: /glogg/src/crawlerwidget.cpp (revision a44d09bc709514bfc9e2b6b4e435e83e8a36868a)
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         LOG(logDEBUG) << "Refreshing the search";
377         logFilteredData_->updateSearch();
378     }
379 
380     emit loadingFinished( status );
381 }
382 
383 void CrawlerWidget::fileChangedHandler( LogData::MonitoredFileStatus status )
384 {
385     // Handle the case where the file has been truncated
386     if ( status == LogData::Truncated ) {
387         // Clear all marks (TODO offer the option to keep them)
388         logFilteredData_->clearMarks();
389         if ( ! searchInfoLine->text().isEmpty() ) {
390             // Invalidate the search
391             logFilteredData_->clearSearch();
392             filteredView->updateData();
393             searchState_.truncateFile();
394             printSearchInfoMessage();
395         }
396     }
397 }
398 
399 // Returns a pointer to the window in which the search should be done
400 AbstractLogView* CrawlerWidget::activeView() const
401 {
402     QWidget* activeView;
403 
404     // Search in the window that has focus, or the window where 'Find' was
405     // called from, or the main window.
406     if ( filteredView->hasFocus() || logMainView->hasFocus() )
407         activeView = QApplication::focusWidget();
408     else
409         activeView = qfSavedFocus_;
410 
411     if ( activeView ) {
412         AbstractLogView* view = qobject_cast<AbstractLogView*>( activeView );
413         return view;
414     }
415     else {
416         LOG(logWARNING) << "No active view, defaulting to logMainView";
417         return logMainView;
418     }
419 }
420 
421 void CrawlerWidget::searchForward()
422 {
423     LOG(logDEBUG) << "CrawlerWidget::searchForward";
424 
425     activeView()->searchForward();
426 }
427 
428 void CrawlerWidget::searchBackward()
429 {
430     LOG(logDEBUG) << "CrawlerWidget::searchBackward";
431 
432     activeView()->searchBackward();
433 }
434 
435 void CrawlerWidget::searchRefreshChangedHandler( int state )
436 {
437     searchState_.setAutorefresh( state == Qt::Checked );
438     printSearchInfoMessage( logFilteredData_->getNbMatches() );
439 }
440 
441 void CrawlerWidget::searchTextChangeHandler()
442 {
443     // We suspend auto-refresh
444     searchState_.changeExpression();
445     printSearchInfoMessage( logFilteredData_->getNbMatches() );
446 }
447 
448 void CrawlerWidget::changeFilteredViewVisibility( int index )
449 {
450     QStandardItem* item = visibilityModel_->item( index );
451     FilteredView::Visibility visibility =
452         static_cast< FilteredView::Visibility>( item->data().toInt() );
453 
454     filteredView->setVisibility( visibility );
455 }
456 
457 void CrawlerWidget::addToSearch( const QString& string )
458 {
459     QString text = searchLineEdit->currentText();
460 
461     if ( text.isEmpty() )
462         text = string;
463     else {
464         // Escape the regexp chars from the string before adding it.
465         text += ( '|' + QRegExp::escape( string ) );
466     }
467 
468     searchLineEdit->setEditText( text );
469 
470     // Set the focus to lineEdit so that the user can press 'Return' immediately
471     searchLineEdit->lineEdit()->setFocus();
472 }
473 
474 void CrawlerWidget::mouseHoveredOverMatch( qint64 line )
475 {
476     qint64 line_in_mainview = logFilteredData_->getMatchingLineNumber( line );
477 
478     overviewWidget_->highlightLine( line_in_mainview );
479 }
480 
481 //
482 // Private functions
483 //
484 
485 // Build the widget and connect all the signals, this must be done once
486 // the data are attached.
487 void CrawlerWidget::setup()
488 {
489     setOrientation(Qt::Vertical);
490 
491     assert( logData_ );
492     assert( logFilteredData_ );
493 
494     // The views
495     bottomWindow = new QWidget;
496     overviewWidget_ = new OverviewWidget();
497     logMainView     = new LogMainView(
498             logData_, quickFindPattern_.get(), &overview_, overviewWidget_ );
499     filteredView    = new FilteredView(
500             logFilteredData_, quickFindPattern_.get() );
501 
502     overviewWidget_->setOverview( &overview_ );
503     overviewWidget_->setParent( logMainView );
504 
505     // Construct the visibility button
506     visibilityModel_ = new QStandardItemModel( this );
507 
508     QStandardItem *marksAndMatchesItem = new QStandardItem( tr( "Marks and matches" ) );
509     QPixmap marksAndMatchesPixmap( 16, 10 );
510     marksAndMatchesPixmap.fill( Qt::gray );
511     marksAndMatchesItem->setIcon( QIcon( marksAndMatchesPixmap ) );
512     marksAndMatchesItem->setData( FilteredView::MarksAndMatches );
513     visibilityModel_->appendRow( marksAndMatchesItem );
514 
515     QStandardItem *marksItem = new QStandardItem( tr( "Marks" ) );
516     QPixmap marksPixmap( 16, 10 );
517     marksPixmap.fill( Qt::blue );
518     marksItem->setIcon( QIcon( marksPixmap ) );
519     marksItem->setData( FilteredView::MarksOnly );
520     visibilityModel_->appendRow( marksItem );
521 
522     QStandardItem *matchesItem = new QStandardItem( tr( "Matches" ) );
523     QPixmap matchesPixmap( 16, 10 );
524     matchesPixmap.fill( Qt::red );
525     matchesItem->setIcon( QIcon( matchesPixmap ) );
526     matchesItem->setData( FilteredView::MatchesOnly );
527     visibilityModel_->appendRow( matchesItem );
528 
529     QListView *visibilityView = new QListView( this );
530     visibilityView->setMovement( QListView::Static );
531     visibilityView->setMinimumWidth( 170 ); // Only needed with custom style-sheet
532 
533     visibilityBox = new QComboBox();
534     visibilityBox->setModel( visibilityModel_ );
535     visibilityBox->setView( visibilityView );
536 
537     // Select "Marks and matches" by default (same default as the filtered view)
538     visibilityBox->setCurrentIndex( 0 );
539 
540     // TODO: Maybe there is some way to set the popup width to be
541     // sized-to-content (as it is when the stylesheet is not overriden) in the
542     // stylesheet as opposed to setting a hard min-width on the view above.
543     visibilityBox->setStyleSheet( " \
544         QComboBox:on {\
545             padding: 1px 2px 1px 6px;\
546             width: 19px;\
547         } \
548         QComboBox:!on {\
549             padding: 1px 2px 1px 7px;\
550             width: 19px;\
551             height: 16px;\
552             border: 1px solid gray;\
553         } \
554         QComboBox::drop-down::down-arrow {\
555             width: 0px;\
556             border-width: 0px;\
557         } \
558 " );
559 
560     // Construct the Search Info line
561     searchInfoLine = new InfoLine();
562     searchInfoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
563     searchInfoLine->setLineWidth( 1 );
564     searchInfoLineDefaultPalette = searchInfoLine->palette();
565 
566     ignoreCaseCheck = new QCheckBox( "Ignore &case" );
567     searchRefreshCheck = new QCheckBox( "Auto-&refresh" );
568 
569     // Construct the Search line
570     searchLabel = new QLabel(tr("&Text: "));
571     searchLineEdit = new QComboBox;
572     searchLineEdit->setEditable( true );
573     searchLineEdit->setCompleter( 0 );
574     searchLineEdit->addItems( savedSearches_->recentSearches() );
575     searchLineEdit->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum );
576     searchLineEdit->setSizeAdjustPolicy( QComboBox::AdjustToMinimumContentsLengthWithIcon );
577 
578     searchLabel->setBuddy( searchLineEdit );
579 
580     searchButton = new QToolButton();
581     searchButton->setText( tr("&Search") );
582     searchButton->setAutoRaise( true );
583 
584     stopButton = new QToolButton();
585     stopButton->setIcon( QIcon(":/images/stop16.png") );
586     stopButton->setAutoRaise( true );
587     stopButton->setEnabled( false );
588 
589     QHBoxLayout* searchLineLayout = new QHBoxLayout;
590     searchLineLayout->addWidget(searchLabel);
591     searchLineLayout->addWidget(searchLineEdit);
592     searchLineLayout->addWidget(searchButton);
593     searchLineLayout->addWidget(stopButton);
594     searchLineLayout->setContentsMargins(6, 0, 6, 0);
595     stopButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
596     searchButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
597 
598     QHBoxLayout* searchInfoLineLayout = new QHBoxLayout;
599     searchInfoLineLayout->addWidget( visibilityBox );
600     searchInfoLineLayout->addWidget( searchInfoLine );
601     searchInfoLineLayout->addWidget( ignoreCaseCheck );
602     searchInfoLineLayout->addWidget( searchRefreshCheck );
603 
604     // Construct the bottom window
605     QVBoxLayout* bottomMainLayout = new QVBoxLayout;
606     bottomMainLayout->addLayout(searchLineLayout);
607     bottomMainLayout->addLayout(searchInfoLineLayout);
608     bottomMainLayout->addWidget(filteredView);
609     bottomMainLayout->setContentsMargins(2, 1, 2, 1);
610     bottomWindow->setLayout(bottomMainLayout);
611 
612     addWidget( logMainView );
613     addWidget( bottomWindow );
614 
615     // Default splitter position (usually overridden by the config file)
616     QList<int> splitterSizes;
617     splitterSizes += 400;
618     splitterSizes += 100;
619     setSizes( splitterSizes );
620 
621     // Connect the signals
622     connect(searchLineEdit->lineEdit(), SIGNAL( returnPressed() ),
623             searchButton, SIGNAL( clicked() ));
624     connect(searchLineEdit->lineEdit(), SIGNAL( textEdited( const QString& ) ),
625             this, SLOT( searchTextChangeHandler() ));
626     connect(searchButton, SIGNAL( clicked() ),
627             this, SLOT( startNewSearch() ) );
628     connect(stopButton, SIGNAL( clicked() ),
629             this, SLOT( stopSearch() ) );
630 
631     connect(visibilityBox, SIGNAL( currentIndexChanged( int ) ),
632             this, SLOT( changeFilteredViewVisibility( int ) ) );
633 
634     connect(logMainView, SIGNAL( newSelection( int ) ),
635             logMainView, SLOT( update() ) );
636     connect(filteredView, SIGNAL( newSelection( int ) ),
637             this, SLOT( jumpToMatchingLine( int ) ) );
638     connect(filteredView, SIGNAL( newSelection( int ) ),
639             filteredView, SLOT( update() ) );
640     connect(logMainView, SIGNAL( updateLineNumber( int ) ),
641             this, SLOT( updateLineNumberHandler( int ) ) );
642     connect(logMainView, SIGNAL( markLine( qint64 ) ),
643             this, SLOT( markLineFromMain( qint64 ) ) );
644     connect(filteredView, SIGNAL( markLine( qint64 ) ),
645             this, SLOT( markLineFromFiltered( qint64 ) ) );
646 
647     connect(logMainView, SIGNAL( addToSearch( const QString& ) ),
648             this, SLOT( addToSearch( const QString& ) ) );
649     connect(filteredView, SIGNAL( addToSearch( const QString& ) ),
650             this, SLOT( addToSearch( const QString& ) ) );
651 
652     connect(filteredView, SIGNAL( mouseHoveredOverLine( qint64 ) ),
653             this, SLOT( mouseHoveredOverMatch( qint64 ) ) );
654     connect(filteredView, SIGNAL( mouseLeftHoveringZone() ),
655             overviewWidget_, SLOT( removeHighlight() ) );
656 
657     // Follow option (up and down)
658     connect(this, SIGNAL( followSet( bool ) ),
659             logMainView, SLOT( followSet( bool ) ) );
660     connect(this, SIGNAL( followSet( bool ) ),
661             filteredView, SLOT( followSet( bool ) ) );
662     connect(logMainView, SIGNAL( followDisabled() ),
663             this, SIGNAL( followDisabled() ) );
664     connect(filteredView, SIGNAL( followDisabled() ),
665             this, SIGNAL( followDisabled() ) );
666 
667     connect( logFilteredData_, SIGNAL( searchProgressed( int, int ) ),
668             this, SLOT( updateFilteredView( int, int ) ) );
669 
670     // Sent load file update to MainWindow (for status update)
671     connect( logData_, SIGNAL( loadingProgressed( int ) ),
672             this, SIGNAL( loadingProgressed( int ) ) );
673     connect( logData_, SIGNAL( loadingFinished( LoadingStatus ) ),
674             this, SLOT( loadingFinishedHandler( LoadingStatus ) ) );
675     connect( logData_, SIGNAL( fileChanged( LogData::MonitoredFileStatus ) ),
676             this, SLOT( fileChangedHandler( LogData::MonitoredFileStatus ) ) );
677 
678     // Search auto-refresh
679     connect( searchRefreshCheck, SIGNAL( stateChanged( int ) ),
680             this, SLOT( searchRefreshChangedHandler( int ) ) );
681 }
682 
683 // Create a new search using the text passed, replace the currently
684 // used one and destroy the old one.
685 void CrawlerWidget::replaceCurrentSearch( const QString& searchText )
686 {
687     // Interrupt the search if it's ongoing
688     logFilteredData_->interruptSearch();
689 
690     // We have to wait for the last search update (100%)
691     // before clearing/restarting to avoid having remaining results.
692 
693     // FIXME: this is a bit of a hack, we call processEvents
694     // for Qt to empty its event queue, including (hopefully)
695     // the search update event sent by logFilteredData_. It saves
696     // us the overhead of having proper sync.
697     QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
698 
699     if ( !searchText.isEmpty() ) {
700         // Determine the type of regexp depending on the config
701         QRegExp::PatternSyntax syntax;
702         static std::shared_ptr<Configuration> config =
703             Persistent<Configuration>( "settings" );
704         switch ( config->mainRegexpType() ) {
705             case Wildcard:
706                 syntax = QRegExp::Wildcard;
707                 break;
708             case FixedString:
709                 syntax = QRegExp::FixedString;
710                 break;
711             default:
712                 syntax = QRegExp::RegExp2;
713                 break;
714         }
715 
716         // Set the pattern case insensitive if needed
717         Qt::CaseSensitivity case_sensitivity = Qt::CaseSensitive;
718         if ( ignoreCaseCheck->checkState() == Qt::Checked )
719             case_sensitivity = Qt::CaseInsensitive;
720 
721         // Constructs the regexp
722         QRegExp regexp( searchText, case_sensitivity, syntax );
723 
724         if ( regexp.isValid() ) {
725             // Activate the stop button
726             stopButton->setEnabled( true );
727             // Start a new asynchronous search
728             logFilteredData_->runSearch( regexp );
729             // Accept auto-refresh of the search
730             searchState_.startSearch();
731         }
732         else {
733             // The regexp is wrong
734             logFilteredData_->clearSearch();
735             filteredView->updateData();
736             searchState_.resetState();
737 
738             // Inform the user
739             QString errorMessage = tr("Error in expression: ");
740             errorMessage += regexp.errorString();
741             searchInfoLine->setPalette( errorPalette );
742             searchInfoLine->setText( errorMessage );
743         }
744     }
745     else {
746         logFilteredData_->clearSearch();
747         filteredView->updateData();
748         searchState_.resetState();
749         printSearchInfoMessage();
750     }
751     // Connect the search to the top view
752     logMainView->useNewFiltering( logFilteredData_ );
753 }
754 
755 // Updates the content of the drop down list for the saved searches,
756 // called when the SavedSearch has been changed.
757 void CrawlerWidget::updateSearchCombo()
758 {
759     const QString text = searchLineEdit->lineEdit()->text();
760     searchLineEdit->clear();
761     searchLineEdit->addItems( savedSearches_->recentSearches() );
762     // In case we had something that wasn't added to the list (blank...):
763     searchLineEdit->lineEdit()->setText( text );
764 }
765 
766 // Print the search info message.
767 void CrawlerWidget::printSearchInfoMessage( int nbMatches )
768 {
769     QString text;
770 
771     switch ( searchState_.getState() ) {
772         case SearchState::NoSearch:
773             // Blank text is fine
774             break;
775         case SearchState::Static:
776             text = tr("%1 match%2 found.").arg( nbMatches )
777                 .arg( nbMatches > 1 ? "es" : "" );
778             break;
779         case SearchState::Autorefreshing:
780             text = tr("%1 match%2 found. Search is auto-refreshing...").arg( nbMatches )
781                 .arg( nbMatches > 1 ? "es" : "" );
782             break;
783         case SearchState::FileTruncated:
784             text = tr("File truncated on disk, previous search results are not valid anymore.");
785             break;
786     }
787 
788     searchInfoLine->setPalette( searchInfoLineDefaultPalette );
789     searchInfoLine->setText( text );
790 }
791 
792 //
793 // SearchState implementation
794 //
795 void CrawlerWidget::SearchState::resetState()
796 {
797     state_ = NoSearch;
798 }
799 
800 void CrawlerWidget::SearchState::setAutorefresh( bool refresh )
801 {
802     autoRefreshRequested_ = refresh;
803 
804     if ( refresh ) {
805         if ( state_ == Static )
806             state_ = Autorefreshing;
807     }
808     else {
809         if ( state_ == Autorefreshing )
810             state_ = Static;
811     }
812 }
813 
814 void CrawlerWidget::SearchState::truncateFile()
815 {
816     state_ = FileTruncated;
817 }
818 
819 void CrawlerWidget::SearchState::changeExpression()
820 {
821     if ( state_ == Autorefreshing )
822         state_ = Static;
823 }
824 
825 void CrawlerWidget::SearchState::stopSearch()
826 {
827     if ( state_ == Autorefreshing )
828         state_ = Static;
829 }
830 
831 void CrawlerWidget::SearchState::startSearch()
832 {
833     if ( autoRefreshRequested_ )
834         state_ = Autorefreshing;
835     else
836         state_ = Static;
837 }
838 
839 /*
840  * CrawlerWidgetContext
841  */
842 CrawlerWidgetContext::CrawlerWidgetContext( const char* string )
843 {
844     QRegExp regex = QRegExp( "S(\\d+):(\\d+)" );
845 
846     if ( regex.indexIn( string ) > -1 )
847     {
848         sizes_ = { regex.cap(1).toInt(), regex.cap(2).toInt() };
849         LOG(logDEBUG) << "sizes_: " << sizes_[0] << " " << sizes_[1];
850     }
851     else
852     {
853         LOG(logWARNING) << "Unrecognised view context: " << string;
854 
855         // Default values;
856         sizes_ = { 100, 400 };
857     }
858 }
859 
860 std::string CrawlerWidgetContext::toString() const
861 {
862     char string[160];
863 
864     snprintf( string, sizeof string, "S%d:%d", sizes_[0], sizes_[1] );
865 
866     return string;
867 }
868