xref: /glogg/src/mainwindow.cpp (revision f25e35f2304d4fe5dd984cd59b86e6255c85ffe4) !
1 /*
2  * Copyright (C) 2009, 2010, 2011, 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 MainWindow. It is responsible for creating and
21 // managing the menus, the toolbar, and the CrawlerWidget. It also
22 // load/save the settings on opening/closing of the app
23 
24 #include <iostream>
25 #include <cassert>
26 
27 #include <QAction>
28 #include <QDesktopWidget>
29 #include <QMenuBar>
30 #include <QToolBar>
31 #include <QFileInfo>
32 #include <QFileDialog>
33 #include <QClipboard>
34 #include <QMessageBox>
35 #include <QCloseEvent>
36 #include <QDragEnterEvent>
37 #include <QMimeData>
38 #include <QUrl>
39 
40 #include "log.h"
41 
42 #include "mainwindow.h"
43 
44 #include "sessioninfo.h"
45 #include "recentfiles.h"
46 #include "crawlerwidget.h"
47 #include "filtersdialog.h"
48 #include "optionsdialog.h"
49 #include "persistentinfo.h"
50 #include "menuactiontooltipbehavior.h"
51 #include "tabbedcrawlerwidget.h"
52 #include "externalcom.h"
53 
54 // Returns the size in human readable format
55 static QString readableSize( qint64 size );
56 
57 MainWindow::MainWindow( std::unique_ptr<Session> session,
58         std::shared_ptr<ExternalCommunicator> external_communicator ) :
59     session_( std::move( session )  ),
60     externalCommunicator_( external_communicator ),
61     recentFiles_( Persistent<RecentFiles>( "recentFiles" ) ),
62     mainIcon_(),
63     signalMux_(),
64     quickFindMux_( session_->getQuickFindPattern() ),
65     mainTabWidget_()
66 #ifdef GLOGG_SUPPORTS_VERSION_CHECKING
67     ,versionChecker_()
68 #endif
69 {
70     createActions();
71     createMenus();
72     createToolBars();
73     // createStatusBar();
74 
75     setAcceptDrops( true );
76 
77     // Default geometry
78     const QRect geometry = QApplication::desktop()->availableGeometry( this );
79     setGeometry( geometry.x() + 20, geometry.y() + 40,
80             geometry.width() - 140, geometry.height() - 140 );
81 
82     mainIcon_.addFile( ":/images/hicolor/16x16/glogg.png" );
83     mainIcon_.addFile( ":/images/hicolor/24x24/glogg.png" );
84     mainIcon_.addFile( ":/images/hicolor/32x32/glogg.png" );
85     mainIcon_.addFile( ":/images/hicolor/48x48/glogg.png" );
86 
87     setWindowIcon( mainIcon_ );
88 
89     readSettings();
90 
91     // Connect the signals to the mux (they will be forwarded to the
92     // "current" crawlerwidget
93 
94     // Send actions to the crawlerwidget
95     signalMux_.connect( this, SIGNAL( followSet( bool ) ),
96             SIGNAL( followSet( bool ) ) );
97     signalMux_.connect( this, SIGNAL( optionsChanged() ),
98             SLOT( applyConfiguration() ) );
99     signalMux_.connect( this, SIGNAL( enteringQuickFind() ),
100             SLOT( enteringQuickFind() ) );
101     signalMux_.connect( &quickFindWidget_, SIGNAL( close() ),
102             SLOT( exitingQuickFind() ) );
103 
104     // Actions from the CrawlerWidget
105     signalMux_.connect( SIGNAL( followModeChanged( bool ) ),
106             this, SLOT( changeFollowMode( bool ) ) );
107     signalMux_.connect( SIGNAL( updateLineNumber( int ) ),
108             this, SLOT( lineNumberHandler( int ) ) );
109 
110     // Register for progress status bar
111     signalMux_.connect( SIGNAL( loadingProgressed( int ) ),
112             this, SLOT( updateLoadingProgress( int ) ) );
113     signalMux_.connect( SIGNAL( loadingFinished( LoadingStatus ) ),
114             this, SLOT( handleLoadingFinished( LoadingStatus ) ) );
115 
116     // Register for checkbox changes
117     signalMux_.connect( SIGNAL( searchRefreshChanged( int ) ),
118             this, SLOT( handleSearchRefreshChanged( int ) ) );
119     signalMux_.connect( SIGNAL( ignoreCaseChanged( int ) ),
120             this, SLOT( handleIgnoreCaseChanged( int ) ) );
121 
122     // Configure the main tabbed widget
123     mainTabWidget_.setDocumentMode( true );
124     mainTabWidget_.setMovable( true );
125     //mainTabWidget_.setTabShape( QTabWidget::Triangular );
126     mainTabWidget_.setTabsClosable( true );
127 
128     connect( &mainTabWidget_, SIGNAL( tabCloseRequested( int ) ),
129             this, SLOT( closeTab( int ) ) );
130     connect( &mainTabWidget_, SIGNAL( currentChanged( int ) ),
131             this, SLOT( currentTabChanged( int ) ) );
132 
133     // Establish the QuickFindWidget and mux ( to send requests from the
134     // QFWidget to the right window )
135     connect( &quickFindWidget_, SIGNAL( patternConfirmed( const QString&, bool ) ),
136              &quickFindMux_, SLOT( confirmPattern( const QString&, bool ) ) );
137     connect( &quickFindWidget_, SIGNAL( patternUpdated( const QString&, bool ) ),
138              &quickFindMux_, SLOT( setNewPattern( const QString&, bool ) ) );
139     connect( &quickFindWidget_, SIGNAL( cancelSearch() ),
140              &quickFindMux_, SLOT( cancelSearch() ) );
141     connect( &quickFindWidget_, SIGNAL( searchForward() ),
142              &quickFindMux_, SLOT( searchForward() ) );
143     connect( &quickFindWidget_, SIGNAL( searchBackward() ),
144              &quickFindMux_, SLOT( searchBackward() ) );
145     connect( &quickFindWidget_, SIGNAL( searchNext() ),
146              &quickFindMux_, SLOT( searchNext() ) );
147 
148     // QuickFind changes coming from the views
149     connect( &quickFindMux_, SIGNAL( patternChanged( const QString& ) ),
150              this, SLOT( changeQFPattern( const QString& ) ) );
151     connect( &quickFindMux_, SIGNAL( notify( const QFNotification& ) ),
152              &quickFindWidget_, SLOT( notify( const QFNotification& ) ) );
153     connect( &quickFindMux_, SIGNAL( clearNotification() ),
154              &quickFindWidget_, SLOT( clearNotification() ) );
155 
156     // Actions from external instances
157     connect( externalCommunicator_.get(), SIGNAL( loadFile( const QString& ) ),
158              this, SLOT( loadFileNonInteractive( const QString& ) ) );
159 
160 #ifdef GLOGG_SUPPORTS_VERSION_CHECKING
161     // Version checker notification
162     connect( &versionChecker_, SIGNAL( newVersionFound( const QString& ) ),
163             this, SLOT( newVersionNotification( const QString& ) ) );
164 #endif
165 
166     // Construct the QuickFind bar
167     quickFindWidget_.hide();
168 
169     QWidget* central_widget = new QWidget();
170     QVBoxLayout* main_layout = new QVBoxLayout();
171     main_layout->setContentsMargins( 0, 0, 0, 0 );
172     main_layout->addWidget( &mainTabWidget_ );
173     main_layout->addWidget( &quickFindWidget_ );
174     central_widget->setLayout( main_layout );
175 
176     setCentralWidget( central_widget );
177 }
178 
179 void MainWindow::reloadGeometry()
180 {
181     QByteArray geometry;
182 
183     session_->storedGeometry( &geometry );
184     restoreGeometry( geometry );
185 }
186 
187 void MainWindow::reloadSession()
188 {
189     int current_file_index = -1;
190 
191     for ( auto open_file: session_->restore(
192                []() { return new CrawlerWidget(); },
193                &current_file_index ) )
194     {
195         QString file_name = { open_file.first.c_str() };
196         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
197                 open_file.second );
198 
199         assert( crawler_widget );
200 
201         mainTabWidget_.addTab( crawler_widget, strippedName( file_name ) );
202     }
203 
204     if ( current_file_index >= 0 )
205         mainTabWidget_.setCurrentIndex( current_file_index );
206 }
207 
208 void MainWindow::loadInitialFile( QString fileName )
209 {
210     LOG(logDEBUG) << "loadInitialFile";
211 
212     // Is there a file passed as argument?
213     if ( !fileName.isEmpty() )
214         loadFile( fileName );
215 }
216 
217 void MainWindow::startBackgroundTasks()
218 {
219     LOG(logDEBUG) << "startBackgroundTasks";
220 
221 #ifdef GLOGG_SUPPORTS_VERSION_CHECKING
222     versionChecker_.startCheck();
223 #endif
224 }
225 
226 //
227 // Private functions
228 //
229 
230 const MainWindow::EncodingList MainWindow::encoding_list[] = {
231     { "&Auto" },
232     { "ASCII / &ISO-8859-1" },
233     { "&UTF-8" },
234     { "UTF-16LE" },
235     { "UTF-16BE" },
236     { "CP1251" },
237     { "CP1252" },
238 };
239 
240 // Menu actions
241 void MainWindow::createActions()
242 {
243     std::shared_ptr<Configuration> config =
244         Persistent<Configuration>( "settings" );
245 
246     openAction = new QAction(tr("&Open..."), this);
247     openAction->setShortcut(QKeySequence::Open);
248     openAction->setIcon( QIcon( ":/images/open14.png" ) );
249     openAction->setStatusTip(tr("Open a file"));
250     connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
251 
252     closeAction = new QAction(tr("&Close"), this);
253     closeAction->setShortcut(tr("Ctrl+W"));
254     closeAction->setStatusTip(tr("Close document"));
255     connect(closeAction, SIGNAL(triggered()), this, SLOT(closeTab()));
256 
257     closeAllAction = new QAction(tr("Close &All"), this);
258     closeAllAction->setStatusTip(tr("Close all documents"));
259     connect(closeAllAction, SIGNAL(triggered()), this, SLOT(closeAll()));
260 
261     // Recent files
262     for (int i = 0; i < MaxRecentFiles; ++i) {
263         recentFileActions[i] = new QAction(this);
264         recentFileActions[i]->setVisible(false);
265         connect(recentFileActions[i], SIGNAL(triggered()),
266                 this, SLOT(openRecentFile()));
267     }
268 
269     exitAction = new QAction(tr("E&xit"), this);
270     exitAction->setShortcut(tr("Ctrl+Q"));
271     exitAction->setStatusTip(tr("Exit the application"));
272     connect( exitAction, SIGNAL(triggered()), this, SLOT(close()) );
273 
274     copyAction = new QAction(tr("&Copy"), this);
275     copyAction->setShortcut(QKeySequence::Copy);
276     copyAction->setStatusTip(tr("Copy the selection"));
277     connect( copyAction, SIGNAL(triggered()), this, SLOT(copy()) );
278 
279     selectAllAction = new QAction(tr("Select &All"), this);
280     selectAllAction->setShortcut(tr("Ctrl+A"));
281     selectAllAction->setStatusTip(tr("Select all the text"));
282     connect( selectAllAction, SIGNAL(triggered()),
283              this, SLOT( selectAll() ) );
284 
285     findAction = new QAction(tr("&Find..."), this);
286     findAction->setShortcut(QKeySequence::Find);
287     findAction->setStatusTip(tr("Find the text"));
288     connect( findAction, SIGNAL(triggered()),
289             this, SLOT( find() ) );
290 
291     overviewVisibleAction = new QAction( tr("Matches &overview"), this );
292     overviewVisibleAction->setCheckable( true );
293     overviewVisibleAction->setChecked( config->isOverviewVisible() );
294     connect( overviewVisibleAction, SIGNAL( toggled( bool ) ),
295             this, SLOT( toggleOverviewVisibility( bool )) );
296 
297     lineNumbersVisibleInMainAction =
298         new QAction( tr("Line &numbers in main view"), this );
299     lineNumbersVisibleInMainAction->setCheckable( true );
300     lineNumbersVisibleInMainAction->setChecked( config->mainLineNumbersVisible() );
301     connect( lineNumbersVisibleInMainAction, SIGNAL( toggled( bool ) ),
302             this, SLOT( toggleMainLineNumbersVisibility( bool )) );
303 
304     lineNumbersVisibleInFilteredAction =
305         new QAction( tr("Line &numbers in filtered view"), this );
306     lineNumbersVisibleInFilteredAction->setCheckable( true );
307     lineNumbersVisibleInFilteredAction->setChecked( config->filteredLineNumbersVisible() );
308     connect( lineNumbersVisibleInFilteredAction, SIGNAL( toggled( bool ) ),
309             this, SLOT( toggleFilteredLineNumbersVisibility( bool )) );
310 
311     followAction = new QAction( tr("&Follow File"), this );
312     followAction->setShortcut(Qt::Key_F);
313     followAction->setCheckable(true);
314     connect( followAction, SIGNAL(toggled( bool )),
315             this, SIGNAL(followSet( bool )) );
316 
317     reloadAction = new QAction( tr("&Reload"), this );
318     reloadAction->setShortcut(QKeySequence::Refresh);
319     reloadAction->setIcon( QIcon(":/images/reload14.png") );
320     signalMux_.connect( reloadAction, SIGNAL(triggered()), SLOT(reload()) );
321 
322     stopAction = new QAction( tr("&Stop"), this );
323     stopAction->setIcon( QIcon(":/images/stop14.png") );
324     stopAction->setEnabled( true );
325     signalMux_.connect( stopAction, SIGNAL(triggered()), SLOT(stopLoading()) );
326 
327     filtersAction = new QAction(tr("&Filters..."), this);
328     filtersAction->setStatusTip(tr("Show the Filters box"));
329     connect( filtersAction, SIGNAL(triggered()), this, SLOT(filters()) );
330 
331     optionsAction = new QAction(tr("&Options..."), this);
332     optionsAction->setStatusTip(tr("Show the Options box"));
333     connect( optionsAction, SIGNAL(triggered()), this, SLOT(options()) );
334 
335     aboutAction = new QAction(tr("&About"), this);
336     aboutAction->setStatusTip(tr("Show the About box"));
337     connect( aboutAction, SIGNAL(triggered()), this, SLOT(about()) );
338 
339     aboutQtAction = new QAction(tr("About &Qt"), this);
340     aboutQtAction->setStatusTip(tr("Show the Qt library's About box"));
341     connect( aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()) );
342 
343     encodingGroup = new QActionGroup( this );
344 
345     for ( int i = 0; i < CrawlerWidget::ENCODING_MAX; ++i ) {
346         encodingAction[i] = new QAction( tr( encoding_list[i].name ), this );
347         encodingAction[i]->setCheckable( true );
348         encodingGroup->addAction( encodingAction[i] );
349     }
350 
351     encodingAction[0]->setStatusTip(tr("Automatically detect the file's encoding"));
352     encodingAction[0]->setChecked( true );
353 
354     connect( encodingGroup, SIGNAL( triggered( QAction* ) ),
355             this, SLOT( encodingChanged( QAction* ) ) );
356 }
357 
358 void MainWindow::createMenus()
359 {
360     fileMenu = menuBar()->addMenu( tr("&File") );
361     fileMenu->addAction( openAction );
362     fileMenu->addAction( closeAction );
363     fileMenu->addAction( closeAllAction );
364     fileMenu->addSeparator();
365     for (int i = 0; i < MaxRecentFiles; ++i) {
366         fileMenu->addAction( recentFileActions[i] );
367         recentFileActionBehaviors[i] =
368             new MenuActionToolTipBehavior(recentFileActions[i], fileMenu, this);
369     }
370     fileMenu->addSeparator();
371     fileMenu->addAction( exitAction );
372 
373     editMenu = menuBar()->addMenu( tr("&Edit") );
374     editMenu->addAction( copyAction );
375     editMenu->addAction( selectAllAction );
376     editMenu->addSeparator();
377     editMenu->addAction( findAction );
378 
379     viewMenu = menuBar()->addMenu( tr("&View") );
380     viewMenu->addAction( overviewVisibleAction );
381     viewMenu->addSeparator();
382     viewMenu->addAction( lineNumbersVisibleInMainAction );
383     viewMenu->addAction( lineNumbersVisibleInFilteredAction );
384     viewMenu->addSeparator();
385     viewMenu->addAction( followAction );
386     viewMenu->addSeparator();
387     viewMenu->addAction( reloadAction );
388 
389     toolsMenu = menuBar()->addMenu( tr("&Tools") );
390     toolsMenu->addAction( filtersAction );
391     toolsMenu->addSeparator();
392     toolsMenu->addAction( optionsAction );
393 
394     encodingMenu = menuBar()->addMenu( tr("En&coding") );
395     encodingMenu->addAction( encodingAction[0] );
396     encodingMenu->addSeparator();
397     for ( int i = 1; i < CrawlerWidget::ENCODING_MAX; ++i ) {
398         encodingMenu->addAction( encodingAction[i] );
399     }
400 
401     menuBar()->addSeparator();
402 
403     helpMenu = menuBar()->addMenu( tr("&Help") );
404     helpMenu->addAction( aboutAction );
405 }
406 
407 void MainWindow::createToolBars()
408 {
409     infoLine = new InfoLine();
410     infoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
411     infoLine->setLineWidth( 0 );
412 
413     lineNbField = new QLabel( );
414     lineNbField->setText( "Line 0" );
415     lineNbField->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
416     lineNbField->setMinimumSize(
417             lineNbField->fontMetrics().size( 0, "Line 0000000") );
418 
419     toolBar = addToolBar( tr("&Toolbar") );
420     toolBar->setIconSize( QSize( 14, 14 ) );
421     toolBar->setMovable( false );
422     toolBar->addAction( openAction );
423     toolBar->addAction( reloadAction );
424     toolBar->addWidget( infoLine );
425     toolBar->addAction( stopAction );
426     toolBar->addWidget( lineNbField );
427 }
428 
429 //
430 // Slots
431 //
432 
433 // Opens the file selection dialog to select a new log file
434 void MainWindow::open()
435 {
436     QString defaultDir = ".";
437 
438     // Default to the path of the current file if there is one
439     if ( auto current = currentCrawlerWidget() )
440     {
441         std::string current_file = session_->getFilename( current );
442         QFileInfo fileInfo = QFileInfo( QString( current_file.c_str() ) );
443         defaultDir = fileInfo.path();
444     }
445 
446     QString fileName = QFileDialog::getOpenFileName(this,
447             tr("Open file"), defaultDir, tr("All files (*)"));
448     if (!fileName.isEmpty())
449         loadFile(fileName);
450 }
451 
452 // Opens a log file from the recent files list
453 void MainWindow::openRecentFile()
454 {
455     QAction* action = qobject_cast<QAction*>(sender());
456     if (action)
457         loadFile(action->data().toString());
458 }
459 
460 // Close current tab
461 void MainWindow::closeTab()
462 {
463     int currentIndex = mainTabWidget_.currentIndex();
464 
465     if ( currentIndex >= 0 )
466     {
467         closeTab(currentIndex);
468     }
469 }
470 
471 // Close all tabs
472 void MainWindow::closeAll()
473 {
474     while ( mainTabWidget_.count() )
475     {
476         closeTab(0);
477     }
478 }
479 
480 // Select all the text in the currently selected view
481 void MainWindow::selectAll()
482 {
483     CrawlerWidget* current = currentCrawlerWidget();
484 
485     if ( current )
486         current->selectAll();
487 }
488 
489 // Copy the currently selected line into the clipboard
490 void MainWindow::copy()
491 {
492     static QClipboard* clipboard = QApplication::clipboard();
493     CrawlerWidget* current = currentCrawlerWidget();
494 
495     if ( current ) {
496         clipboard->setText( current->getSelectedText() );
497 
498         // Put it in the global selection as well (X11 only)
499         clipboard->setText( current->getSelectedText(),
500                 QClipboard::Selection );
501     }
502 }
503 
504 // Display the QuickFind bar
505 void MainWindow::find()
506 {
507     displayQuickFindBar( QuickFindMux::Forward );
508 }
509 
510 // Opens the 'Filters' dialog box
511 void MainWindow::filters()
512 {
513     FiltersDialog dialog(this);
514     signalMux_.connect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
515     dialog.exec();
516     signalMux_.disconnect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
517 }
518 
519 // Opens the 'Options' modal dialog box
520 void MainWindow::options()
521 {
522     OptionsDialog dialog(this);
523     signalMux_.connect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
524     dialog.exec();
525     signalMux_.disconnect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
526 }
527 
528 // Opens the 'About' dialog box.
529 void MainWindow::about()
530 {
531     QMessageBox::about(this, tr("About glogg"),
532             tr("<h2>glogg " GLOGG_VERSION "</h2>"
533                 "<p>A fast, advanced log explorer."
534 #ifdef GLOGG_COMMIT
535                 "<p>Built " GLOGG_DATE " from " GLOGG_COMMIT
536 #endif
537                 "<p><a href=\"http://glogg.bonnefon.org/\">http://glogg.bonnefon.org/</a></p>"
538                 "<p>Copyright &copy; 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicolas Bonnefon and other contributors"
539                 "<p>You may modify and redistribute the program under the terms of the GPL (version 3 or later)." ) );
540 }
541 
542 // Opens the 'About Qt' dialog box.
543 void MainWindow::aboutQt()
544 {
545 }
546 
547 void MainWindow::encodingChanged( QAction* action )
548 {
549     int i = 0;
550     for ( i = 0; i < CrawlerWidget::ENCODING_MAX; ++i )
551         if ( action == encodingAction[i] )
552             break;
553 
554     LOG(logDEBUG) << "encodingChanged, encoding " << i;
555     currentCrawlerWidget()->setEncoding( static_cast<CrawlerWidget::Encoding>( i ) );
556     updateInfoLine();
557 }
558 
559 void MainWindow::toggleOverviewVisibility( bool isVisible )
560 {
561     std::shared_ptr<Configuration> config =
562         Persistent<Configuration>( "settings" );
563     config->setOverviewVisible( isVisible );
564     emit optionsChanged();
565 }
566 
567 void MainWindow::toggleMainLineNumbersVisibility( bool isVisible )
568 {
569     std::shared_ptr<Configuration> config =
570         Persistent<Configuration>( "settings" );
571     config->setMainLineNumbersVisible( isVisible );
572     emit optionsChanged();
573 }
574 
575 void MainWindow::toggleFilteredLineNumbersVisibility( bool isVisible )
576 {
577     std::shared_ptr<Configuration> config =
578         Persistent<Configuration>( "settings" );
579     config->setFilteredLineNumbersVisible( isVisible );
580     emit optionsChanged();
581 }
582 
583 void MainWindow::changeFollowMode( bool follow )
584 {
585     followAction->setChecked( follow );
586 }
587 
588 void MainWindow::lineNumberHandler( int line )
589 {
590     // The line number received is the internal (starts at 0)
591     lineNbField->setText( tr( "Line %1" ).arg( line + 1 ) );
592 }
593 
594 void MainWindow::updateLoadingProgress( int progress )
595 {
596     LOG(logDEBUG) << "Loading progress: " << progress;
597 
598     QString current_file =
599         session_->getFilename( currentCrawlerWidget() ).c_str();
600 
601     // We ignore 0% and 100% to avoid a flash when the file (or update)
602     // is very short.
603     if ( progress > 0 && progress < 100 ) {
604         infoLine->setText( current_file +
605                 tr( " - Indexing lines... (%1 %)" ).arg( progress ) );
606         infoLine->displayGauge( progress );
607 
608         stopAction->setEnabled( true );
609         reloadAction->setEnabled( false );
610     }
611 }
612 
613 void MainWindow::handleLoadingFinished( LoadingStatus status )
614 {
615     LOG(logDEBUG) << "handleLoadingFinished success=" <<
616         ( status == LoadingStatus::Successful );
617 
618     // No file is loading
619     loadingFileName.clear();
620 
621     if ( status == LoadingStatus::Successful )
622     {
623         updateInfoLine();
624 
625         infoLine->hideGauge();
626         stopAction->setEnabled( false );
627         reloadAction->setEnabled( true );
628 
629         // Now everything is ready, we can finally show the file!
630         currentCrawlerWidget()->show();
631     }
632     else
633     {
634         if ( status == LoadingStatus::NoMemory )
635         {
636             QMessageBox alertBox;
637             alertBox.setText( "Not enough memory." );
638             alertBox.setInformativeText( "The system does not have enough \
639 memory to hold the index for this file. The file will now be closed." );
640             alertBox.setIcon( QMessageBox::Critical );
641             alertBox.exec();
642         }
643 
644         closeTab( mainTabWidget_.currentIndex()  );
645     }
646 
647     // mainTabWidget_.setEnabled( true );
648 }
649 
650 void MainWindow::handleSearchRefreshChanged( int state )
651 {
652     auto config = Persistent<Configuration>( "settings" );
653     config->setSearchAutoRefreshDefault( state == Qt::Checked );
654 }
655 
656 void MainWindow::handleIgnoreCaseChanged( int state )
657 {
658     auto config = Persistent<Configuration>( "settings" );
659     config->setSearchIgnoreCaseDefault( state == Qt::Checked );
660 }
661 
662 void MainWindow::closeTab( int index )
663 {
664     auto widget = dynamic_cast<CrawlerWidget*>(
665             mainTabWidget_.widget( index ) );
666 
667     assert( widget );
668 
669     widget->stopLoading();
670     mainTabWidget_.removeTab( index );
671     session_->close( widget );
672     delete widget;
673 }
674 
675 void MainWindow::currentTabChanged( int index )
676 {
677     LOG(logDEBUG) << "currentTabChanged";
678 
679     if ( index >= 0 )
680     {
681         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
682                 mainTabWidget_.widget( index ) );
683         signalMux_.setCurrentDocument( crawler_widget );
684         quickFindMux_.registerSelector( crawler_widget );
685 
686         // New tab is set up with fonts etc...
687         emit optionsChanged();
688 
689         // Update the menu bar
690         updateMenuBarFromDocument( crawler_widget );
691 
692         // Update the title bar
693         updateTitleBar( QString(
694                     session_->getFilename( crawler_widget ).c_str() ) );
695     }
696     else
697     {
698         // No tab left
699         signalMux_.setCurrentDocument( nullptr );
700         quickFindMux_.registerSelector( nullptr );
701 
702         infoLine->hideGauge();
703         infoLine->clear();
704 
705         updateTitleBar( QString() );
706     }
707 }
708 
709 void MainWindow::changeQFPattern( const QString& newPattern )
710 {
711     quickFindWidget_.changeDisplayedPattern( newPattern );
712 }
713 
714 void MainWindow::loadFileNonInteractive( const QString& file_name )
715 {
716     LOG(logDEBUG) << "loadFileNonInteractive( "
717         << file_name.toStdString() << " )";
718 
719     loadFile( file_name );
720 
721     // Try to get the window to the front
722     // This is a bit of a hack but has been tested on:
723     // Qt 5.3 / Gnome / Linux
724     // Qt 4.8 / Win7
725 #ifdef _WIN32
726     // Hack copied from http://qt-project.org/forums/viewthread/6164
727     ::SetWindowPos((HWND) effectiveWinId(), HWND_TOPMOST,
728             0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
729     ::SetWindowPos((HWND) effectiveWinId(), HWND_NOTOPMOST,
730             0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
731 #else
732     Qt::WindowFlags window_flags = windowFlags();
733     window_flags |= Qt::WindowStaysOnTopHint;
734     setWindowFlags( window_flags );
735 #endif
736 
737     activateWindow();
738     raise();
739 
740 #ifndef _WIN32
741     window_flags = windowFlags();
742     window_flags &= ~Qt::WindowStaysOnTopHint;
743     setWindowFlags( window_flags );
744 #endif
745 
746     showNormal();
747 }
748 
749 void MainWindow::newVersionNotification( const QString& new_version )
750 {
751     LOG(logDEBUG) << "newVersionNotification( " <<
752         new_version.toStdString() << " )";
753 
754     QMessageBox msgBox;
755     msgBox.setText( QString( "A new version of glogg (%1) is available for download <p>"
756                 "<a href=\"http://glogg.bonnefon.org/download.html\">http://glogg.bonnefon.org/download.html</a>"
757                 ).arg( new_version ) );
758     msgBox.exec();
759 }
760 
761 //
762 // Events
763 //
764 
765 // Closes the application
766 void MainWindow::closeEvent( QCloseEvent *event )
767 {
768     writeSettings();
769     event->accept();
770 }
771 
772 // Accepts the drag event if it looks like a filename
773 void MainWindow::dragEnterEvent( QDragEnterEvent* event )
774 {
775     if ( event->mimeData()->hasFormat( "text/uri-list" ) )
776         event->acceptProposedAction();
777 }
778 
779 // Tries and loads the file if the URL dropped is local
780 void MainWindow::dropEvent( QDropEvent* event )
781 {
782     QList<QUrl> urls = event->mimeData()->urls();
783     if ( urls.isEmpty() )
784         return;
785 
786     QString fileName = urls.first().toLocalFile();
787     if ( fileName.isEmpty() )
788         return;
789 
790     loadFile( fileName );
791 }
792 
793 void MainWindow::keyPressEvent( QKeyEvent* keyEvent )
794 {
795     LOG(logDEBUG4) << "keyPressEvent received";
796 
797     switch ( (keyEvent->text())[0].toLatin1() ) {
798         case '/':
799             displayQuickFindBar( QuickFindMux::Forward );
800             break;
801         case '?':
802             displayQuickFindBar( QuickFindMux::Backward );
803             break;
804         default:
805             keyEvent->ignore();
806     }
807 
808     if ( !keyEvent->isAccepted() )
809         QMainWindow::keyPressEvent( keyEvent );
810 }
811 
812 //
813 // Private functions
814 //
815 
816 // Create a CrawlerWidget for the passed file, start its loading
817 // and update the title bar.
818 // The loading is done asynchronously.
819 bool MainWindow::loadFile( const QString& fileName )
820 {
821     LOG(logDEBUG) << "loadFile ( " << fileName.toStdString() << " )";
822 
823     // First check if the file is already open...
824     CrawlerWidget* existing_crawler = dynamic_cast<CrawlerWidget*>(
825             session_->getViewIfOpen( fileName.toStdString() ) );
826     if ( existing_crawler ) {
827         // ... and switch to it.
828         mainTabWidget_.setCurrentWidget( existing_crawler );
829 
830         return true;
831     }
832 
833     // Load the file
834     loadingFileName = fileName;
835 
836     try {
837         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
838                 session_->open( fileName.toStdString(),
839                     []() { return new CrawlerWidget(); } ) );
840         assert( crawler_widget );
841 
842         // We won't show the widget until the file is fully loaded
843         crawler_widget->hide();
844 
845         // We disable the tab widget to avoid having someone switch
846         // tab during loading. (maybe FIXME)
847         //mainTabWidget_.setEnabled( false );
848 
849         int index = mainTabWidget_.addTab(
850                 crawler_widget, strippedName( fileName ) );
851 
852         // Setting the new tab, the user will see a blank page for the duration
853         // of the loading, with no way to switch to another tab
854         mainTabWidget_.setCurrentIndex( index );
855 
856         // Update the recent files list
857         // (reload the list first in case another glogg changed it)
858         GetPersistentInfo().retrieve( "recentFiles" );
859         recentFiles_->addRecent( fileName );
860         GetPersistentInfo().save( "recentFiles" );
861         updateRecentFileActions();
862     }
863     catch ( FileUnreadableErr ) {
864         LOG(logDEBUG) << "Can't open file " << fileName.toStdString();
865         return false;
866     }
867 
868     LOG(logDEBUG) << "Success loading file " << fileName.toStdString();
869     return true;
870 
871 }
872 
873 // Strips the passed filename from its directory part.
874 QString MainWindow::strippedName( const QString& fullFileName ) const
875 {
876     return QFileInfo( fullFileName ).fileName();
877 }
878 
879 // Return the currently active CrawlerWidget, or NULL if none
880 CrawlerWidget* MainWindow::currentCrawlerWidget() const
881 {
882     auto current = dynamic_cast<CrawlerWidget*>(
883             mainTabWidget_.currentWidget() );
884 
885     return current;
886 }
887 
888 // Update the title bar.
889 void MainWindow::updateTitleBar( const QString& file_name )
890 {
891     QString shownName = tr( "Untitled" );
892     if ( !file_name.isEmpty() )
893         shownName = strippedName( file_name );
894 
895     setWindowTitle(
896             tr("%1 - %2").arg(shownName).arg(tr("glogg"))
897 #ifdef GLOGG_COMMIT
898             + " (dev build " GLOGG_VERSION ")"
899 #endif
900             );
901 }
902 
903 // Updates the actions for the recent files.
904 // Must be called after having added a new name to the list.
905 void MainWindow::updateRecentFileActions()
906 {
907     QStringList recent_files = recentFiles_->recentFiles();
908 
909     for ( int j = 0; j < MaxRecentFiles; ++j ) {
910         if ( j < recent_files.count() ) {
911             QString text = tr("&%1 %2").arg(j + 1).arg(strippedName(recent_files[j]));
912             recentFileActions[j]->setText( text );
913             recentFileActions[j]->setToolTip( recent_files[j] );
914             recentFileActions[j]->setData( recent_files[j] );
915             recentFileActions[j]->setVisible( true );
916         }
917         else {
918             recentFileActions[j]->setVisible( false );
919         }
920     }
921 
922     // separatorAction->setVisible(!recentFiles.isEmpty());
923 }
924 
925 // Update our menu bar to match the settings of the crawler
926 // (used when the tab is changed)
927 void MainWindow::updateMenuBarFromDocument( const CrawlerWidget* crawler )
928 {
929     auto encoding = crawler->encodingSetting();
930     encodingAction[static_cast<int>( encoding )]->setChecked( true );
931     bool follow = crawler->isFollowEnabled();
932     followAction->setChecked( follow );
933 }
934 
935 // Update the top info line from the session
936 void MainWindow::updateInfoLine()
937 {
938     QLocale defaultLocale;
939 
940     // Following should always work as we will only receive enter
941     // this slot if there is a crawler connected.
942     QString current_file =
943         session_->getFilename( currentCrawlerWidget() ).c_str();
944 
945     uint64_t fileSize;
946     uint32_t fileNbLine;
947     QDateTime lastModified;
948 
949     session_->getFileInfo( currentCrawlerWidget(),
950             &fileSize, &fileNbLine, &lastModified );
951     if ( lastModified.isValid() ) {
952         const QString date =
953             defaultLocale.toString( lastModified, QLocale::NarrowFormat );
954         infoLine->setText( tr( "%1 (%2 - %3 lines - modified on %4 - %5)" )
955                 .arg(current_file).arg(readableSize(fileSize))
956                 .arg(fileNbLine).arg( date )
957                 .arg(currentCrawlerWidget()->encodingText()) );
958     }
959     else {
960         infoLine->setText( tr( "%1 (%2 - %3 lines - %4)" )
961                 .arg(current_file).arg(readableSize(fileSize))
962                 .arg(fileNbLine)
963                 .arg(currentCrawlerWidget()->encodingText()) );
964     }
965 }
966 
967 // Write settings to permanent storage
968 void MainWindow::writeSettings()
969 {
970     // Save the session
971     // Generate the ordered list of widgets and their topLine
972     std::vector<
973             std::tuple<const ViewInterface*, uint64_t, std::shared_ptr<const ViewContextInterface>>
974         > widget_list;
975     for ( int i = 0; i < mainTabWidget_.count(); ++i )
976     {
977         auto view = dynamic_cast<const ViewInterface*>( mainTabWidget_.widget( i ) );
978         widget_list.push_back( std::make_tuple(
979                 view,
980                 0UL,
981                 view->context() ) );
982     }
983     session_->save( widget_list, saveGeometry() );
984 
985     // User settings
986     GetPersistentInfo().save( QString( "settings" ) );
987 }
988 
989 // Read settings from permanent storage
990 void MainWindow::readSettings()
991 {
992     // Get and restore the session
993     // GetPersistentInfo().retrieve( QString( "session" ) );
994     // SessionInfo session = Persistent<SessionInfo>( "session" );
995     /*
996      * FIXME: should be in the session
997     crawlerWidget->restoreState( session.crawlerState() );
998     */
999 
1000     // History of recent files
1001     GetPersistentInfo().retrieve( QString( "recentFiles" ) );
1002     updateRecentFileActions();
1003 
1004     // GetPersistentInfo().retrieve( QString( "settings" ) );
1005     GetPersistentInfo().retrieve( QString( "filterSet" ) );
1006 }
1007 
1008 void MainWindow::displayQuickFindBar( QuickFindMux::QFDirection direction )
1009 {
1010     LOG(logDEBUG) << "MainWindow::displayQuickFindBar";
1011 
1012     // Warn crawlers so they can save the position of the focus in order
1013     // to do incremental search in the right view.
1014     emit enteringQuickFind();
1015 
1016     quickFindMux_.setDirection( direction );
1017     quickFindWidget_.userActivate();
1018 }
1019 
1020 // Returns the size in human readable format
1021 static QString readableSize( qint64 size )
1022 {
1023     static const QString sizeStrs[] = {
1024         QObject::tr("B"), QObject::tr("KiB"), QObject::tr("MiB"),
1025         QObject::tr("GiB"), QObject::tr("TiB") };
1026 
1027     QLocale defaultLocale;
1028     unsigned int i;
1029     double humanSize = size;
1030 
1031     for ( i=0; i+1 < (sizeof(sizeStrs)/sizeof(QString)) && (humanSize/1024.0) >= 1024.0; i++ )
1032         humanSize /= 1024.0;
1033 
1034     if ( humanSize >= 1024.0 ) {
1035         humanSize /= 1024.0;
1036         i++;
1037     }
1038 
1039     QString output;
1040     if ( i == 0 )
1041         // No decimal part if we display straight bytes.
1042         output = defaultLocale.toString( (int) humanSize );
1043     else
1044         output = defaultLocale.toString( humanSize, 'f', 1 );
1045 
1046     output += QString(" ") + sizeStrs[i];
1047 
1048     return output;
1049 }
1050