xref: /glogg/src/crawlerwidget.cpp (revision af94bdd678467b70a2d698f66e393a9458fb2f97)
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 <QStandardItemModel>
35 #include <QHeaderView>
36 #include <QListView>
37 
38 #include "crawlerwidget.h"
39 
40 #include "quickfindpattern.h"
41 #include "overview.h"
42 #include "infoline.h"
43 #include "savedsearches.h"
44 #include "quickfindwidget.h"
45 #include "persistentinfo.h"
46 #include "configuration.h"
47 
48 // Palette for error signaling (yellow background)
49 const QPalette CrawlerWidget::errorPalette( QColor( "yellow" ) );
50 
51 // Implementation of the view context for the CrawlerWidget
52 class CrawlerWidgetContext : public ViewContextInterface {
53   public:
54     // Construct from the stored string representation
55     CrawlerWidgetContext( const char* string );
56     // Construct from the value passsed
57     CrawlerWidgetContext( QList<int> sizes,
58            bool ignore_case,
59            bool auto_refresh,
60            bool follow_file )
61         : sizes_( sizes ),
62           ignore_case_( ignore_case ),
63           auto_refresh_( auto_refresh ),
64           follow_file_( follow_file ) {}
65 
66     // Implementation of the ViewContextInterface function
67     std::string toString() const;
68 
69     // Access the Qt sizes array for the QSplitter
70     QList<int> sizes() const { return sizes_; }
71 
72     bool ignoreCase() const { return ignore_case_; }
73     bool autoRefresh() const { return auto_refresh_; }
74     bool followFile() const { return follow_file_; }
75 
76   private:
77     QList<int> sizes_;
78 
79     bool ignore_case_;
80     bool auto_refresh_;
81     bool follow_file_;
82 };
83 
84 // Constructor only does trivial construction. The real work is done once
85 // the data is attached.
86 CrawlerWidget::CrawlerWidget( QWidget *parent )
87         : QSplitter( parent ), overview_()
88 {
89     logData_         = nullptr;
90     logFilteredData_ = nullptr;
91 
92     quickFindPattern_ = nullptr;
93     savedSearches_   = nullptr;
94     qfSavedFocus_    = nullptr;
95 
96     // Until we have received confirmation loading is finished, we
97     // should consider we are loading something.
98     loadingInProgress_ = true;
99     // and it's the first time
100     firstLoadDone_     = false;
101     nbMatches_         = 0;
102     dataStatus_        = DataStatus::OLD_DATA;
103 
104     currentLineNumber_ = 0;
105 }
106 
107 // The top line is first one on the main display
108 int CrawlerWidget::getTopLine() const
109 {
110     return logMainView->getTopLine();
111 }
112 
113 QString CrawlerWidget::getSelectedText() const
114 {
115     if ( filteredView->hasFocus() )
116         return filteredView->getSelection();
117     else
118         return logMainView->getSelection();
119 }
120 
121 void CrawlerWidget::selectAll()
122 {
123     activeView()->selectAll();
124 }
125 
126 Encoding CrawlerWidget::encodingSetting() const
127 {
128     return encodingSetting_;
129 }
130 
131 bool CrawlerWidget::isFollowEnabled() const
132 {
133     return logMainView->isFollowEnabled();
134 }
135 
136 QString CrawlerWidget::encodingText() const
137 {
138     return encoding_text_;
139 }
140 
141 // Return a pointer to the view in which we should do the QuickFind
142 SearchableWidgetInterface* CrawlerWidget::doGetActiveSearchable() const
143 {
144     return activeView();
145 }
146 
147 // Return all the searchable widgets (views)
148 std::vector<QObject*> CrawlerWidget::doGetAllSearchables() const
149 {
150     std::vector<QObject*> searchables =
151     { logMainView, filteredView };
152 
153     return searchables;
154 }
155 
156 // Update the state of the parent
157 void CrawlerWidget::doSendAllStateSignals()
158 {
159     emit updateLineNumber( currentLineNumber_ );
160     if ( !loadingInProgress_ )
161         emit loadingFinished( LoadingStatus::Successful );
162 }
163 
164 void CrawlerWidget::keyPressEvent( QKeyEvent* keyEvent )
165 {
166     bool noModifier = keyEvent->modifiers() == Qt::NoModifier;
167 
168     if ( keyEvent->key() == Qt::Key_V && noModifier )
169         visibilityBox->setCurrentIndex(
170                 ( visibilityBox->currentIndex() + 1 ) % visibilityBox->count() );
171     else {
172         const char character = (keyEvent->text())[0].toLatin1();
173 
174         if ( character == '+' )
175             changeTopViewSize( 1 );
176         else if ( character == '-' )
177             changeTopViewSize( -1 );
178         else
179             QSplitter::keyPressEvent( keyEvent );
180     }
181 }
182 
183 //
184 // Public slots
185 //
186 
187 void CrawlerWidget::stopLoading()
188 {
189     logFilteredData_->interruptSearch();
190     logData_->interruptLoading();
191 }
192 
193 void CrawlerWidget::reload()
194 {
195     searchState_.resetState();
196     logFilteredData_->clearSearch();
197     logFilteredData_->clearMarks();
198     filteredView->updateData();
199     printSearchInfoMessage();
200 
201     logData_->reload();
202 
203     // A reload is considered as a first load,
204     // this is to prevent the "new data" icon to be triggered.
205     firstLoadDone_ = false;
206 }
207 
208 void CrawlerWidget::setEncoding( Encoding encoding )
209 {
210     encodingSetting_ = encoding;
211     updateEncoding();
212 
213     update();
214 }
215 
216 //
217 // Protected functions
218 //
219 void CrawlerWidget::doSetData(
220         std::shared_ptr<LogData> log_data,
221         std::shared_ptr<LogFilteredData> filtered_data )
222 {
223     logData_         = log_data.get();
224     logFilteredData_ = filtered_data.get();
225 }
226 
227 void CrawlerWidget::doSetQuickFindPattern(
228         std::shared_ptr<QuickFindPattern> qfp )
229 {
230     quickFindPattern_ = qfp;
231 }
232 
233 void CrawlerWidget::doSetSavedSearches(
234         std::shared_ptr<SavedSearches> saved_searches )
235 {
236     savedSearches_ = saved_searches;
237 
238     // We do setup now, assuming doSetData has been called before
239     // us, that's not great really...
240     setup();
241 }
242 
243 void CrawlerWidget::doSetViewContext(
244         const char* view_context )
245 {
246     LOG(logDEBUG) << "CrawlerWidget::doSetViewContext: " << view_context;
247 
248     CrawlerWidgetContext context = { view_context };
249 
250     setSizes( context.sizes() );
251     ignoreCaseCheck->setCheckState( context.ignoreCase() ? Qt::Checked : Qt::Unchecked );
252 
253     auto auto_refresh_check_state = context.autoRefresh() ? Qt::Checked : Qt::Unchecked;
254     searchRefreshCheck->setCheckState( auto_refresh_check_state );
255     // Manually call the handler as it is not called when changing the state programmatically
256     searchRefreshChangedHandler( auto_refresh_check_state );
257 
258     emit followSet( context.followFile() );
259 }
260 
261 std::shared_ptr<const ViewContextInterface>
262 CrawlerWidget::doGetViewContext() const
263 {
264     auto context = std::make_shared<const CrawlerWidgetContext>(
265             sizes(),
266             ( ignoreCaseCheck->checkState() == Qt::Checked ),
267             ( searchRefreshCheck->checkState() == Qt::Checked ),
268             logMainView->isFollowEnabled() );
269 
270     return static_cast<std::shared_ptr<const ViewContextInterface>>( context );
271 }
272 
273 //
274 // Slots
275 //
276 
277 void CrawlerWidget::startNewSearch()
278 {
279     // Record the search line in the recent list
280     // (reload the list first in case another glogg changed it)
281     GetPersistentInfo().retrieve( "savedSearches" );
282     savedSearches_->addRecent( searchLineEdit->currentText() );
283     GetPersistentInfo().save( "savedSearches" );
284 
285     // Update the SearchLine (history)
286     updateSearchCombo();
287     // Call the private function to do the search
288     replaceCurrentSearch( searchLineEdit->currentText() );
289 }
290 
291 void CrawlerWidget::stopSearch()
292 {
293     logFilteredData_->interruptSearch();
294     searchState_.stopSearch();
295     printSearchInfoMessage();
296 }
297 
298 // When receiving the 'newDataAvailable' signal from LogFilteredData
299 void CrawlerWidget::updateFilteredView( int nbMatches, int progress )
300 {
301     LOG(logDEBUG) << "updateFilteredView received.";
302 
303     if ( progress == 100 ) {
304         // Searching done
305         printSearchInfoMessage( nbMatches );
306         searchInfoLine->hideGauge();
307         // De-activate the stop button
308         stopButton->setEnabled( false );
309     }
310     else {
311         // Search in progress
312         // We ignore 0% and 100% to avoid a flash when the search is very short
313         if ( progress > 0 ) {
314             searchInfoLine->setText(
315                     tr("Search in progress (%1 %)... %2 match%3 found so far.")
316                     .arg( progress )
317                     .arg( nbMatches )
318                     .arg( nbMatches > 1 ? "es" : "" ) );
319             searchInfoLine->displayGauge( progress );
320         }
321     }
322 
323     // If more (or less, e.g. come back to 0) matches have been found
324     if ( nbMatches != nbMatches_ ) {
325         nbMatches_ = nbMatches;
326 
327         // Recompute the content of the filtered window.
328         filteredView->updateData();
329 
330         // Update the match overview
331         overview_.updateData( logData_->getNbLine() );
332 
333         // New data found icon
334         changeDataStatus( DataStatus::NEW_FILTERED_DATA );
335 
336         // Also update the top window for the coloured bullets.
337         update();
338     }
339 
340     if ( progress == 100 ) {
341         const int currenLineIndex = logFilteredData_->getLineIndexNumber(currentLineNumber_);
342         LOG(logDEBUG) << "updateFilteredView: restoring selection: "
343                       << " absolute line number (0based) " << currentLineNumber_
344                       << " index " << currenLineIndex;
345         filteredView->selectAndDisplayLine(currenLineIndex);
346     }
347 }
348 
349 void CrawlerWidget::jumpToMatchingLine(int filteredLineNb)
350 {
351     int mainViewLine = logFilteredData_->getMatchingLineNumber(filteredLineNb);
352     logMainView->selectAndDisplayLine(mainViewLine);  // FIXME: should be done with a signal.
353 }
354 
355 void CrawlerWidget::updateLineNumberHandler( int line )
356 {
357     currentLineNumber_ = line;
358     emit updateLineNumber( line );
359 }
360 
361 void CrawlerWidget::markLineFromMain( qint64 line )
362 {
363     if ( line < logData_->getNbLine() ) {
364         if ( logFilteredData_->isLineMarked( line ) )
365             logFilteredData_->deleteMark( line );
366         else
367             logFilteredData_->addMark( line );
368 
369         // Recompute the content of both window.
370         filteredView->updateData();
371         logMainView->updateData();
372 
373         // Update the match overview
374         overview_.updateData( logData_->getNbLine() );
375 
376         // Also update the top window for the coloured bullets.
377         update();
378     }
379 }
380 
381 void CrawlerWidget::markLineFromFiltered( qint64 line )
382 {
383     if ( line < logFilteredData_->getNbLine() ) {
384         qint64 line_in_file = logFilteredData_->getMatchingLineNumber( line );
385         if ( logFilteredData_->filteredLineTypeByIndex( line )
386                 == LogFilteredData::Mark )
387             logFilteredData_->deleteMark( line_in_file );
388         else
389             logFilteredData_->addMark( line_in_file );
390 
391         // Recompute the content of both window.
392         filteredView->updateData();
393         logMainView->updateData();
394 
395         // Update the match overview
396         overview_.updateData( logData_->getNbLine() );
397 
398         // Also update the top window for the coloured bullets.
399         update();
400     }
401 }
402 
403 void CrawlerWidget::applyConfiguration()
404 {
405     std::shared_ptr<Configuration> config =
406         Persistent<Configuration>( "settings" );
407     QFont font = config->mainFont();
408 
409     LOG(logDEBUG) << "CrawlerWidget::applyConfiguration";
410 
411     // Whatever font we use, we should NOT use kerning
412     font.setKerning( false );
413     font.setFixedPitch( true );
414 #if QT_VERSION > 0x040700
415     // Necessary on systems doing subpixel positionning (e.g. Ubuntu 12.04)
416     font.setStyleStrategy( QFont::ForceIntegerMetrics );
417 #endif
418     logMainView->setFont(font);
419     filteredView->setFont(font);
420 
421     logMainView->setLineNumbersVisible( config->mainLineNumbersVisible() );
422     filteredView->setLineNumbersVisible( config->filteredLineNumbersVisible() );
423 
424     overview_.setVisible( config->isOverviewVisible() );
425     logMainView->refreshOverview();
426 
427     logMainView->updateDisplaySize();
428     logMainView->update();
429     filteredView->updateDisplaySize();
430     filteredView->update();
431 
432     // Polling interval
433     logData_->setPollingInterval(
434             config->pollingEnabled() ? config->pollIntervalMs() : 0 );
435 
436     // Update the SearchLine (history)
437     updateSearchCombo();
438 }
439 
440 void CrawlerWidget::enteringQuickFind()
441 {
442     LOG(logDEBUG) << "CrawlerWidget::enteringQuickFind";
443 
444     // Remember who had the focus (only if it is one of our views)
445     QWidget* focus_widget =  QApplication::focusWidget();
446 
447     if ( ( focus_widget == logMainView ) || ( focus_widget == filteredView ) )
448         qfSavedFocus_ = focus_widget;
449     else
450         qfSavedFocus_ = nullptr;
451 }
452 
453 void CrawlerWidget::exitingQuickFind()
454 {
455     // Restore the focus once the QFBar has been hidden
456     if ( qfSavedFocus_ )
457         qfSavedFocus_->setFocus();
458 }
459 
460 void CrawlerWidget::loadingFinishedHandler( LoadingStatus status )
461 {
462     loadingInProgress_ = false;
463 
464     // We need to refresh the main window because the view lines on the
465     // overview have probably changed.
466     overview_.updateData( logData_->getNbLine() );
467 
468     // FIXME, handle topLine
469     // logMainView->updateData( logData_, topLine );
470     logMainView->updateData();
471 
472         // Shall we Forbid starting a search when loading in progress?
473         // searchButton->setEnabled( false );
474 
475     // searchButton->setEnabled( true );
476 
477     // See if we need to auto-refresh the search
478     if ( searchState_.isAutorefreshAllowed() ) {
479         if ( searchState_.isFileTruncated() )
480             // We need to restart the search
481             replaceCurrentSearch( searchLineEdit->currentText() );
482         else
483             logFilteredData_->updateSearch();
484     }
485 
486     // Set the encoding for the views
487     updateEncoding();
488 
489     emit loadingFinished( status );
490 
491     // Also change the data available icon
492     if ( firstLoadDone_ )
493         changeDataStatus( DataStatus::NEW_DATA );
494     else
495         firstLoadDone_ = true;
496 }
497 
498 void CrawlerWidget::fileChangedHandler( LogData::MonitoredFileStatus status )
499 {
500     // Handle the case where the file has been truncated
501     if ( status == LogData::Truncated ) {
502         // Clear all marks (TODO offer the option to keep them)
503         logFilteredData_->clearMarks();
504         if ( ! searchInfoLine->text().isEmpty() ) {
505             // Invalidate the search
506             logFilteredData_->clearSearch();
507             filteredView->updateData();
508             searchState_.truncateFile();
509             printSearchInfoMessage();
510             nbMatches_ = 0;
511         }
512     }
513 }
514 
515 // Returns a pointer to the window in which the search should be done
516 AbstractLogView* CrawlerWidget::activeView() const
517 {
518     QWidget* activeView;
519 
520     // Search in the window that has focus, or the window where 'Find' was
521     // called from, or the main window.
522     if ( filteredView->hasFocus() || logMainView->hasFocus() )
523         activeView = QApplication::focusWidget();
524     else
525         activeView = qfSavedFocus_;
526 
527     if ( activeView ) {
528         AbstractLogView* view = qobject_cast<AbstractLogView*>( activeView );
529         return view;
530     }
531     else {
532         LOG(logWARNING) << "No active view, defaulting to logMainView";
533         return logMainView;
534     }
535 }
536 
537 void CrawlerWidget::searchForward()
538 {
539     LOG(logDEBUG) << "CrawlerWidget::searchForward";
540 
541     activeView()->searchForward();
542 }
543 
544 void CrawlerWidget::searchBackward()
545 {
546     LOG(logDEBUG) << "CrawlerWidget::searchBackward";
547 
548     activeView()->searchBackward();
549 }
550 
551 void CrawlerWidget::searchRefreshChangedHandler( int state )
552 {
553     searchState_.setAutorefresh( state == Qt::Checked );
554     printSearchInfoMessage( logFilteredData_->getNbMatches() );
555 }
556 
557 void CrawlerWidget::searchTextChangeHandler()
558 {
559     // We suspend auto-refresh
560     searchState_.changeExpression();
561     printSearchInfoMessage( logFilteredData_->getNbMatches() );
562 }
563 
564 void CrawlerWidget::changeFilteredViewVisibility( int index )
565 {
566     QStandardItem* item = visibilityModel_->item( index );
567     FilteredView::Visibility visibility =
568         static_cast< FilteredView::Visibility>( item->data().toInt() );
569 
570     filteredView->setVisibility( visibility );
571 
572     const int lineIndex = logFilteredData_->getLineIndexNumber( currentLineNumber_ );
573     filteredView->selectAndDisplayLine( lineIndex );
574 }
575 
576 void CrawlerWidget::addToSearch( const QString& string )
577 {
578     QString text = searchLineEdit->currentText();
579 
580     if ( text.isEmpty() )
581         text = string;
582     else {
583         // Escape the regexp chars from the string before adding it.
584         text += ( '|' + QRegularExpression::escape( string ) );
585     }
586 
587     searchLineEdit->setEditText( text );
588 
589     // Set the focus to lineEdit so that the user can press 'Return' immediately
590     searchLineEdit->lineEdit()->setFocus();
591 }
592 
593 void CrawlerWidget::mouseHoveredOverMatch( qint64 line )
594 {
595     qint64 line_in_mainview = logFilteredData_->getMatchingLineNumber( line );
596 
597     overviewWidget_->highlightLine( line_in_mainview );
598 }
599 
600 void CrawlerWidget::activityDetected()
601 {
602     changeDataStatus( DataStatus::OLD_DATA );
603 }
604 
605 //
606 // Private functions
607 //
608 
609 // Build the widget and connect all the signals, this must be done once
610 // the data are attached.
611 void CrawlerWidget::setup()
612 {
613     setOrientation(Qt::Vertical);
614 
615     assert( logData_ );
616     assert( logFilteredData_ );
617 
618     // The views
619     bottomWindow = new QWidget;
620     overviewWidget_ = new OverviewWidget();
621     logMainView     = new LogMainView(
622             logData_, quickFindPattern_.get(), &overview_, overviewWidget_ );
623     filteredView    = new FilteredView(
624             logFilteredData_, quickFindPattern_.get() );
625 
626     overviewWidget_->setOverview( &overview_ );
627     overviewWidget_->setParent( logMainView );
628 
629     // Connect the search to the top view
630     logMainView->useNewFiltering( logFilteredData_ );
631 
632     // Construct the visibility button
633     visibilityModel_ = new QStandardItemModel( this );
634 
635     QStandardItem *marksAndMatchesItem = new QStandardItem( tr( "Marks and matches" ) );
636     QPixmap marksAndMatchesPixmap( 16, 10 );
637     marksAndMatchesPixmap.fill( Qt::gray );
638     marksAndMatchesItem->setIcon( QIcon( marksAndMatchesPixmap ) );
639     marksAndMatchesItem->setData( FilteredView::MarksAndMatches );
640     visibilityModel_->appendRow( marksAndMatchesItem );
641 
642     QStandardItem *marksItem = new QStandardItem( tr( "Marks" ) );
643     QPixmap marksPixmap( 16, 10 );
644     marksPixmap.fill( Qt::blue );
645     marksItem->setIcon( QIcon( marksPixmap ) );
646     marksItem->setData( FilteredView::MarksOnly );
647     visibilityModel_->appendRow( marksItem );
648 
649     QStandardItem *matchesItem = new QStandardItem( tr( "Matches" ) );
650     QPixmap matchesPixmap( 16, 10 );
651     matchesPixmap.fill( Qt::red );
652     matchesItem->setIcon( QIcon( matchesPixmap ) );
653     matchesItem->setData( FilteredView::MatchesOnly );
654     visibilityModel_->appendRow( matchesItem );
655 
656     QListView *visibilityView = new QListView( this );
657     visibilityView->setMovement( QListView::Static );
658     visibilityView->setMinimumWidth( 170 ); // Only needed with custom style-sheet
659 
660     visibilityBox = new QComboBox();
661     visibilityBox->setModel( visibilityModel_ );
662     visibilityBox->setView( visibilityView );
663 
664     // Select "Marks and matches" by default (same default as the filtered view)
665     visibilityBox->setCurrentIndex( 0 );
666 
667     // TODO: Maybe there is some way to set the popup width to be
668     // sized-to-content (as it is when the stylesheet is not overriden) in the
669     // stylesheet as opposed to setting a hard min-width on the view above.
670     visibilityBox->setStyleSheet( " \
671         QComboBox:on {\
672             padding: 1px 2px 1px 6px;\
673             width: 19px;\
674         } \
675         QComboBox:!on {\
676             padding: 1px 2px 1px 7px;\
677             width: 19px;\
678             height: 16px;\
679             border: 1px solid gray;\
680         } \
681         QComboBox::drop-down::down-arrow {\
682             width: 0px;\
683             border-width: 0px;\
684         } \
685 " );
686 
687     // Construct the Search Info line
688     searchInfoLine = new InfoLine();
689     searchInfoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
690     searchInfoLine->setLineWidth( 1 );
691     searchInfoLineDefaultPalette = searchInfoLine->palette();
692 
693     ignoreCaseCheck = new QCheckBox( "Ignore &case" );
694     searchRefreshCheck = new QCheckBox( "Auto-&refresh" );
695 
696     // Construct the Search line
697     searchLabel = new QLabel(tr("&Text: "));
698     searchLineEdit = new QComboBox;
699     searchLineEdit->setEditable( true );
700     searchLineEdit->setCompleter( 0 );
701     searchLineEdit->addItems( savedSearches_->recentSearches() );
702     searchLineEdit->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum );
703     searchLineEdit->setSizeAdjustPolicy( QComboBox::AdjustToMinimumContentsLengthWithIcon );
704 
705     searchLabel->setBuddy( searchLineEdit );
706 
707     searchButton = new QToolButton();
708     searchButton->setText( tr("&Search") );
709     searchButton->setAutoRaise( true );
710 
711     stopButton = new QToolButton();
712     stopButton->setIcon( QIcon(":/images/stop14.png") );
713     stopButton->setAutoRaise( true );
714     stopButton->setEnabled( false );
715 
716     QHBoxLayout* searchLineLayout = new QHBoxLayout;
717     searchLineLayout->addWidget(searchLabel);
718     searchLineLayout->addWidget(searchLineEdit);
719     searchLineLayout->addWidget(searchButton);
720     searchLineLayout->addWidget(stopButton);
721     searchLineLayout->setContentsMargins(6, 0, 6, 0);
722     stopButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
723     searchButton->setSizePolicy( QSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ) );
724 
725     QHBoxLayout* searchInfoLineLayout = new QHBoxLayout;
726     searchInfoLineLayout->addWidget( visibilityBox );
727     searchInfoLineLayout->addWidget( searchInfoLine );
728     searchInfoLineLayout->addWidget( ignoreCaseCheck );
729     searchInfoLineLayout->addWidget( searchRefreshCheck );
730 
731     // Construct the bottom window
732     QVBoxLayout* bottomMainLayout = new QVBoxLayout;
733     bottomMainLayout->addLayout(searchLineLayout);
734     bottomMainLayout->addLayout(searchInfoLineLayout);
735     bottomMainLayout->addWidget(filteredView);
736     bottomMainLayout->setContentsMargins(2, 1, 2, 1);
737     bottomWindow->setLayout(bottomMainLayout);
738 
739     addWidget( logMainView );
740     addWidget( bottomWindow );
741 
742     // Default splitter position (usually overridden by the config file)
743     QList<int> splitterSizes;
744     splitterSizes += 400;
745     splitterSizes += 100;
746     setSizes( splitterSizes );
747 
748     // Default search checkboxes
749     auto config = Persistent<Configuration>( "settings" );
750     searchRefreshCheck->setCheckState( config->isSearchAutoRefreshDefault() ?
751             Qt::Checked : Qt::Unchecked );
752     // Manually call the handler as it is not called when changing the state programmatically
753     searchRefreshChangedHandler( searchRefreshCheck->checkState() );
754     ignoreCaseCheck->setCheckState( config->isSearchIgnoreCaseDefault() ?
755             Qt::Checked : Qt::Unchecked );
756 
757     // Connect the signals
758     connect(searchLineEdit->lineEdit(), SIGNAL( returnPressed() ),
759             searchButton, SIGNAL( clicked() ));
760     connect(searchLineEdit->lineEdit(), SIGNAL( textEdited( const QString& ) ),
761             this, SLOT( searchTextChangeHandler() ));
762     connect(searchButton, SIGNAL( clicked() ),
763             this, SLOT( startNewSearch() ) );
764     connect(stopButton, SIGNAL( clicked() ),
765             this, SLOT( stopSearch() ) );
766 
767     connect(visibilityBox, SIGNAL( currentIndexChanged( int ) ),
768             this, SLOT( changeFilteredViewVisibility( int ) ) );
769 
770     connect(logMainView, SIGNAL( newSelection( int ) ),
771             logMainView, SLOT( update() ) );
772     connect(filteredView, SIGNAL( newSelection( int ) ),
773             this, SLOT( jumpToMatchingLine( int ) ) );
774     connect(filteredView, SIGNAL( newSelection( int ) ),
775             filteredView, SLOT( update() ) );
776     connect(logMainView, SIGNAL( updateLineNumber( int ) ),
777             this, SLOT( updateLineNumberHandler( int ) ) );
778     connect(logMainView, SIGNAL( markLine( qint64 ) ),
779             this, SLOT( markLineFromMain( qint64 ) ) );
780     connect(filteredView, SIGNAL( markLine( qint64 ) ),
781             this, SLOT( markLineFromFiltered( qint64 ) ) );
782 
783     connect(logMainView, SIGNAL( addToSearch( const QString& ) ),
784             this, SLOT( addToSearch( const QString& ) ) );
785     connect(filteredView, SIGNAL( addToSearch( const QString& ) ),
786             this, SLOT( addToSearch( const QString& ) ) );
787 
788     connect(filteredView, SIGNAL( mouseHoveredOverLine( qint64 ) ),
789             this, SLOT( mouseHoveredOverMatch( qint64 ) ) );
790     connect(filteredView, SIGNAL( mouseLeftHoveringZone() ),
791             overviewWidget_, SLOT( removeHighlight() ) );
792 
793     // Follow option (up and down)
794     connect(this, SIGNAL( followSet( bool ) ),
795             logMainView, SLOT( followSet( bool ) ) );
796     connect(this, SIGNAL( followSet( bool ) ),
797             filteredView, SLOT( followSet( bool ) ) );
798     connect(logMainView, SIGNAL( followModeChanged( bool ) ),
799             this, SIGNAL( followModeChanged( bool ) ) );
800     connect(filteredView, SIGNAL( followModeChanged( bool ) ),
801             this, SIGNAL( followModeChanged( bool ) ) );
802 
803     // Detect activity in the views
804     connect(logMainView, SIGNAL( activity() ),
805             this, SLOT( activityDetected() ) );
806     connect(filteredView, SIGNAL( activity() ),
807             this, SLOT( activityDetected() ) );
808 
809     connect( logFilteredData_, SIGNAL( searchProgressed( int, int ) ),
810             this, SLOT( updateFilteredView( int, int ) ) );
811 
812     // Sent load file update to MainWindow (for status update)
813     connect( logData_, SIGNAL( loadingProgressed( int ) ),
814             this, SIGNAL( loadingProgressed( int ) ) );
815     connect( logData_, SIGNAL( loadingFinished( LoadingStatus ) ),
816             this, SLOT( loadingFinishedHandler( LoadingStatus ) ) );
817     connect( logData_, SIGNAL( fileChanged( LogData::MonitoredFileStatus ) ),
818             this, SLOT( fileChangedHandler( LogData::MonitoredFileStatus ) ) );
819 
820     // Search auto-refresh
821     connect( searchRefreshCheck, SIGNAL( stateChanged( int ) ),
822             this, SLOT( searchRefreshChangedHandler( int ) ) );
823 
824     // Advise the parent the checkboxes have been changed
825     // (for maintaining default config)
826     connect( searchRefreshCheck, SIGNAL( stateChanged( int ) ),
827             this, SIGNAL( searchRefreshChanged( int ) ) );
828     connect( ignoreCaseCheck, SIGNAL( stateChanged( int ) ),
829             this, SIGNAL( ignoreCaseChanged( int ) ) );
830 
831     // Switch between views
832     connect( logMainView, SIGNAL( exitView() ),
833             filteredView, SLOT( setFocus() ) );
834     connect( filteredView, SIGNAL( exitView() ),
835             logMainView, SLOT( setFocus() ) );
836 }
837 
838 // Create a new search using the text passed, replace the currently
839 // used one and destroy the old one.
840 void CrawlerWidget::replaceCurrentSearch( const QString& searchText )
841 {
842     // Interrupt the search if it's ongoing
843     logFilteredData_->interruptSearch();
844 
845     // We have to wait for the last search update (100%)
846     // before clearing/restarting to avoid having remaining results.
847 
848     // FIXME: this is a bit of a hack, we call processEvents
849     // for Qt to empty its event queue, including (hopefully)
850     // the search update event sent by logFilteredData_. It saves
851     // us the overhead of having proper sync.
852     QApplication::processEvents( QEventLoop::ExcludeUserInputEvents );
853 
854     nbMatches_ = 0;
855 
856     // Clear and recompute the content of the filtered window.
857     logFilteredData_->clearSearch();
858     filteredView->updateData();
859 
860     // Update the match overview
861     overview_.updateData( logData_->getNbLine() );
862 
863     if ( !searchText.isEmpty() ) {
864 
865         QString pattern;
866 
867         // Determine the type of regexp depending on the config
868         static std::shared_ptr<Configuration> config =
869             Persistent<Configuration>( "settings" );
870         switch ( config->mainRegexpType() ) {
871             case FixedString:
872                 pattern = QRegularExpression::escape(searchText);
873                 break;
874             default:
875                 pattern = searchText;
876                 break;
877         }
878 
879         // Set the pattern case insensitive if needed
880         QRegularExpression::PatternOptions patternOptions =
881                 QRegularExpression::UseUnicodePropertiesOption
882                 | QRegularExpression::OptimizeOnFirstUsageOption;
883 
884         if ( ignoreCaseCheck->checkState() == Qt::Checked )
885             patternOptions |= QRegularExpression::CaseInsensitiveOption;
886 
887         // Constructs the regexp
888         QRegularExpression regexp( pattern, patternOptions );
889 
890         if ( regexp.isValid() ) {
891             // Activate the stop button
892             stopButton->setEnabled( true );
893             // Start a new asynchronous search
894             logFilteredData_->runSearch( regexp );
895             // Accept auto-refresh of the search
896             searchState_.startSearch();
897         }
898         else {
899             // The regexp is wrong
900             logFilteredData_->clearSearch();
901             filteredView->updateData();
902             searchState_.resetState();
903 
904             // Inform the user
905             QString errorMessage = tr("Error in expression");
906             const int offset = regexp.patternErrorOffset();
907             if (offset != -1) {
908                 errorMessage += " at position ";
909                 errorMessage += QString::number(offset);
910             }
911             errorMessage += ": ";
912             errorMessage += regexp.errorString();
913             searchInfoLine->setPalette( errorPalette );
914             searchInfoLine->setText( errorMessage );
915         }
916     }
917     else {
918         searchState_.resetState();
919         printSearchInfoMessage();
920     }
921 }
922 
923 // Updates the content of the drop down list for the saved searches,
924 // called when the SavedSearch has been changed.
925 void CrawlerWidget::updateSearchCombo()
926 {
927     const QString text = searchLineEdit->lineEdit()->text();
928     searchLineEdit->clear();
929     searchLineEdit->addItems( savedSearches_->recentSearches() );
930     // In case we had something that wasn't added to the list (blank...):
931     searchLineEdit->lineEdit()->setText( text );
932 }
933 
934 // Print the search info message.
935 void CrawlerWidget::printSearchInfoMessage( int nbMatches )
936 {
937     QString text;
938 
939     switch ( searchState_.getState() ) {
940         case SearchState::NoSearch:
941             // Blank text is fine
942             break;
943         case SearchState::Static:
944             text = tr("%1 match%2 found.").arg( nbMatches )
945                 .arg( nbMatches > 1 ? "es" : "" );
946             break;
947         case SearchState::Autorefreshing:
948             text = tr("%1 match%2 found. Search is auto-refreshing...").arg( nbMatches )
949                 .arg( nbMatches > 1 ? "es" : "" );
950             break;
951         case SearchState::FileTruncated:
952         case SearchState::TruncatedAutorefreshing:
953             text = tr("File truncated on disk, previous search results are not valid anymore.");
954             break;
955     }
956 
957     searchInfoLine->setPalette( searchInfoLineDefaultPalette );
958     searchInfoLine->setText( text );
959 }
960 
961 // Change the data status and, if needed, advise upstream.
962 void CrawlerWidget::changeDataStatus( DataStatus status )
963 {
964     if ( ( status != dataStatus_ )
965             && (! ( dataStatus_ == DataStatus::NEW_FILTERED_DATA
966                     && status == DataStatus::NEW_DATA ) ) ) {
967         dataStatus_ = status;
968         emit dataStatusChanged( dataStatus_ );
969     }
970 }
971 
972 // Determine the right encoding and set the views.
973 void CrawlerWidget::updateEncoding()
974 {
975     Encoding encoding = Encoding::ENCODING_MAX;
976 
977     switch ( encodingSetting_ ) {
978         case Encoding::ENCODING_AUTO:
979             switch ( logData_->getDetectedEncoding() ) {
980                 case EncodingSpeculator::Encoding::ASCII7:
981                     encoding = Encoding::ENCODING_ISO_8859_1;
982                     encoding_text_ = tr( "US-ASCII" );
983                     break;
984                 case EncodingSpeculator::Encoding::ASCII8:
985                     encoding = Encoding::ENCODING_ISO_8859_1;
986                     encoding_text_ = tr( "ISO-8859-1" );
987                     break;
988                 case EncodingSpeculator::Encoding::UTF8:
989                     encoding = Encoding::ENCODING_UTF8;
990                     encoding_text_ = tr( "UTF-8" );
991                     break;
992                 case EncodingSpeculator::Encoding::UTF16LE:
993                     encoding = Encoding::ENCODING_UTF16LE;
994                     encoding_text_ = tr( "UTF-16LE" );
995                     break;
996                 case EncodingSpeculator::Encoding::UTF16BE:
997                     encoding = Encoding::ENCODING_UTF16BE;
998                     encoding_text_ = tr( "UTF-16BE" );
999                     break;
1000             }
1001             break;
1002         case Encoding::ENCODING_UTF8:
1003             encoding = encodingSetting_;
1004             encoding_text_ = tr( "Displayed as UTF-8" );
1005             break;
1006         case Encoding::ENCODING_UTF16LE:
1007             encoding = encodingSetting_;
1008             encoding_text_ = tr( "Displayed as UTF-16LE" );
1009             break;
1010         case Encoding::ENCODING_UTF16BE:
1011             encoding = encodingSetting_;
1012             encoding_text_ = tr( "Displayed as UTF-16BE" );
1013             break;
1014         case Encoding::ENCODING_CP1251:
1015             encoding = encodingSetting_;
1016             encoding_text_ = tr( "Displayed as CP1251" );
1017             break;
1018         case Encoding::ENCODING_CP1252:
1019             encoding = encodingSetting_;
1020             encoding_text_ = tr( "Displayed as CP1252" );
1021             break;
1022         case Encoding::ENCODING_ISO_8859_1:
1023         default:
1024             encoding = Encoding::ENCODING_ISO_8859_1;
1025             encoding_text_ = tr( "Displayed as ISO-8859-1" );
1026             break;
1027     }
1028 
1029     logData_->setDisplayEncoding( encoding );
1030     logMainView->forceRefresh();
1031     logFilteredData_->setDisplayEncoding( encoding );
1032     filteredView->forceRefresh();
1033 }
1034 
1035 // Change the respective size of the two views
1036 void CrawlerWidget::changeTopViewSize( int32_t delta )
1037 {
1038     int min, max;
1039     getRange( 1, &min, &max );
1040     LOG(logDEBUG) << "CrawlerWidget::changeTopViewSize " << sizes()[0] << " " << min << " " << max;
1041     moveSplitter( closestLegalPosition( sizes()[0] + ( delta * 10 ), 1 ), 1 );
1042     LOG(logDEBUG) << "CrawlerWidget::changeTopViewSize " << sizes()[0];
1043 }
1044 
1045 //
1046 // SearchState implementation
1047 //
1048 void CrawlerWidget::SearchState::resetState()
1049 {
1050     state_ = NoSearch;
1051 }
1052 
1053 void CrawlerWidget::SearchState::setAutorefresh( bool refresh )
1054 {
1055     autoRefreshRequested_ = refresh;
1056 
1057     if ( refresh ) {
1058         if ( state_ == Static )
1059             state_ = Autorefreshing;
1060         /*
1061         else if ( state_ == FileTruncated )
1062             state_ = TruncatedAutorefreshing;
1063         */
1064     }
1065     else {
1066         if ( state_ == Autorefreshing )
1067             state_ = Static;
1068         else if ( state_ == TruncatedAutorefreshing )
1069             state_ = FileTruncated;
1070     }
1071 }
1072 
1073 void CrawlerWidget::SearchState::truncateFile()
1074 {
1075     if ( state_ == Autorefreshing || state_ == TruncatedAutorefreshing ) {
1076         state_ = TruncatedAutorefreshing;
1077     }
1078     else {
1079         state_ = FileTruncated;
1080     }
1081 }
1082 
1083 void CrawlerWidget::SearchState::changeExpression()
1084 {
1085     if ( state_ == Autorefreshing )
1086         state_ = Static;
1087 }
1088 
1089 void CrawlerWidget::SearchState::stopSearch()
1090 {
1091     if ( state_ == Autorefreshing )
1092         state_ = Static;
1093 }
1094 
1095 void CrawlerWidget::SearchState::startSearch()
1096 {
1097     if ( autoRefreshRequested_ )
1098         state_ = Autorefreshing;
1099     else
1100         state_ = Static;
1101 }
1102 
1103 /*
1104  * CrawlerWidgetContext
1105  */
1106 CrawlerWidgetContext::CrawlerWidgetContext( const char* string )
1107 {
1108     QRegularExpression regex( "S(\\d+):(\\d+)" );
1109     QRegularExpressionMatch match = regex.match( string );
1110     if ( match.hasMatch() ) {
1111         sizes_ = { match.captured(1).toInt(), match.captured(2).toInt() };
1112         LOG(logDEBUG) << "sizes_: " << sizes_[0] << " " << sizes_[1];
1113     }
1114     else {
1115         LOG(logWARNING) << "Unrecognised view size: " << string;
1116 
1117         // Default values;
1118         sizes_ = { 100, 400 };
1119     }
1120 
1121     QRegularExpression case_refresh_regex( "IC(\\d+):AR(\\d+)" );
1122     match = case_refresh_regex.match( string );
1123     if ( match.hasMatch() ) {
1124         ignore_case_ = ( match.captured(1).toInt() == 1 );
1125         auto_refresh_ = ( match.captured(2).toInt() == 1 );
1126 
1127         LOG(logDEBUG) << "ignore_case_: " << ignore_case_ << " auto_refresh_: "
1128             << auto_refresh_;
1129     }
1130     else {
1131         LOG(logWARNING) << "Unrecognised case/refresh: " << string;
1132         ignore_case_ = false;
1133         auto_refresh_ = false;
1134     }
1135 
1136     QRegularExpression follow_regex( "FF(\\d+)" );
1137     match = follow_regex.match( string );
1138     if ( match.hasMatch() ) {
1139         follow_file_ = ( match.captured(1).toInt() == 1 );
1140 
1141         LOG(logDEBUG) << "follow_file_: " << follow_file_;
1142     }
1143     else {
1144         LOG(logWARNING) << "Unrecognised follow: " << string;
1145         follow_file_ = false;
1146     }
1147 }
1148 
1149 std::string CrawlerWidgetContext::toString() const
1150 {
1151     char string[160];
1152 
1153     snprintf( string, sizeof string, "S%d:%d:IC%d:AR%d:FF%d",
1154             sizes_[0], sizes_[1],
1155             ignore_case_, auto_refresh_, follow_file_ );
1156 
1157     return { string };
1158 }
1159