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