xref: /glogg/src/mainwindow.cpp (revision f109b95bd02d7449e397ad07a5c7d861a672f4ee)
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( followDisabled() ),
106             this, SLOT( disableFollow() ) );
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     // Configure the main tabbed widget
117     mainTabWidget_.setDocumentMode( true );
118     mainTabWidget_.setMovable( true );
119     //mainTabWidget_.setTabShape( QTabWidget::Triangular );
120     mainTabWidget_.setTabsClosable( true );
121 
122     connect( &mainTabWidget_, SIGNAL( tabCloseRequested( int ) ),
123             this, SLOT( closeTab( int ) ) );
124     connect( &mainTabWidget_, SIGNAL( currentChanged( int ) ),
125             this, SLOT( currentTabChanged( int ) ) );
126 
127     // Establish the QuickFindWidget and mux ( to send requests from the
128     // QFWidget to the right window )
129     connect( &quickFindWidget_, SIGNAL( patternConfirmed( const QString&, bool ) ),
130              &quickFindMux_, SLOT( confirmPattern( const QString&, bool ) ) );
131     connect( &quickFindWidget_, SIGNAL( patternUpdated( const QString&, bool ) ),
132              &quickFindMux_, SLOT( setNewPattern( const QString&, bool ) ) );
133     connect( &quickFindWidget_, SIGNAL( cancelSearch() ),
134              &quickFindMux_, SLOT( cancelSearch() ) );
135     connect( &quickFindWidget_, SIGNAL( searchForward() ),
136              &quickFindMux_, SLOT( searchForward() ) );
137     connect( &quickFindWidget_, SIGNAL( searchBackward() ),
138              &quickFindMux_, SLOT( searchBackward() ) );
139     connect( &quickFindWidget_, SIGNAL( searchNext() ),
140              &quickFindMux_, SLOT( searchNext() ) );
141 
142     // QuickFind changes coming from the views
143     connect( &quickFindMux_, SIGNAL( patternChanged( const QString& ) ),
144              this, SLOT( changeQFPattern( const QString& ) ) );
145     connect( &quickFindMux_, SIGNAL( notify( const QFNotification& ) ),
146              &quickFindWidget_, SLOT( notify( const QFNotification& ) ) );
147     connect( &quickFindMux_, SIGNAL( clearNotification() ),
148              &quickFindWidget_, SLOT( clearNotification() ) );
149 
150     // Actions from external instances
151     connect( externalCommunicator_.get(), SIGNAL( loadFile( const QString& ) ),
152              this, SLOT( loadFileNonInteractive( const QString& ) ) );
153 
154 #ifdef GLOGG_SUPPORTS_VERSION_CHECKING
155     // Version checker notification
156     connect( &versionChecker_, SIGNAL( newVersionFound( const QString& ) ),
157             this, SLOT( newVersionNotification( const QString& ) ) );
158 #endif
159 
160     // Construct the QuickFind bar
161     quickFindWidget_.hide();
162 
163     QWidget* central_widget = new QWidget();
164     QVBoxLayout* main_layout = new QVBoxLayout();
165     main_layout->setContentsMargins( 0, 0, 0, 0 );
166     main_layout->addWidget( &mainTabWidget_ );
167     main_layout->addWidget( &quickFindWidget_ );
168     central_widget->setLayout( main_layout );
169 
170     setCentralWidget( central_widget );
171 }
172 
173 void MainWindow::reloadSession()
174 {
175     int current_file_index = -1;
176 
177     for ( auto open_file: session_->restore(
178                []() { return new CrawlerWidget(); },
179                &current_file_index ) )
180     {
181         QString file_name = { open_file.first.c_str() };
182         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
183                 open_file.second );
184 
185         assert( crawler_widget );
186 
187         mainTabWidget_.addTab( crawler_widget, strippedName( file_name ) );
188     }
189 
190     if ( current_file_index >= 0 )
191         mainTabWidget_.setCurrentIndex( current_file_index );
192 }
193 
194 void MainWindow::loadInitialFile( QString fileName )
195 {
196     LOG(logDEBUG) << "loadInitialFile";
197 
198     // Is there a file passed as argument?
199     if ( !fileName.isEmpty() )
200         loadFile( fileName );
201 }
202 
203 void MainWindow::startBackgroundTasks()
204 {
205     LOG(logDEBUG) << "startBackgroundTasks";
206 
207 #ifdef GLOGG_SUPPORTS_VERSION_CHECKING
208     versionChecker_.startCheck();
209 #endif
210 }
211 
212 //
213 // Private functions
214 //
215 
216 // Menu actions
217 void MainWindow::createActions()
218 {
219     std::shared_ptr<Configuration> config =
220         Persistent<Configuration>( "settings" );
221 
222     openAction = new QAction(tr("&Open..."), this);
223     openAction->setShortcut(QKeySequence::Open);
224     openAction->setIcon( QIcon(":/images/open16.png") );
225     openAction->setStatusTip(tr("Open a file"));
226     connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
227 
228     // Recent files
229     for (int i = 0; i < MaxRecentFiles; ++i) {
230         recentFileActions[i] = new QAction(this);
231         recentFileActions[i]->setVisible(false);
232         connect(recentFileActions[i], SIGNAL(triggered()),
233                 this, SLOT(openRecentFile()));
234     }
235 
236     exitAction = new QAction(tr("E&xit"), this);
237     exitAction->setShortcut(tr("Ctrl+Q"));
238     exitAction->setStatusTip(tr("Exit the application"));
239     connect( exitAction, SIGNAL(triggered()), this, SLOT(close()) );
240 
241     copyAction = new QAction(tr("&Copy"), this);
242     copyAction->setShortcut(QKeySequence::Copy);
243     copyAction->setStatusTip(tr("Copy the selection"));
244     connect( copyAction, SIGNAL(triggered()), this, SLOT(copy()) );
245 
246     selectAllAction = new QAction(tr("Select &All"), this);
247     selectAllAction->setShortcut(tr("Ctrl+A"));
248     selectAllAction->setStatusTip(tr("Select all the text"));
249     connect( selectAllAction, SIGNAL(triggered()),
250              this, SLOT( selectAll() ) );
251 
252     findAction = new QAction(tr("&Find..."), this);
253     findAction->setShortcut(QKeySequence::Find);
254     findAction->setStatusTip(tr("Find the text"));
255     connect( findAction, SIGNAL(triggered()),
256             this, SLOT( find() ) );
257 
258     overviewVisibleAction = new QAction( tr("Matches &overview"), this );
259     overviewVisibleAction->setCheckable( true );
260     overviewVisibleAction->setChecked( config->isOverviewVisible() );
261     connect( overviewVisibleAction, SIGNAL( toggled( bool ) ),
262             this, SLOT( toggleOverviewVisibility( bool )) );
263 
264     lineNumbersVisibleInMainAction =
265         new QAction( tr("Line &numbers in main view"), this );
266     lineNumbersVisibleInMainAction->setCheckable( true );
267     lineNumbersVisibleInMainAction->setChecked( config->mainLineNumbersVisible() );
268     connect( lineNumbersVisibleInMainAction, SIGNAL( toggled( bool ) ),
269             this, SLOT( toggleMainLineNumbersVisibility( bool )) );
270 
271     lineNumbersVisibleInFilteredAction =
272         new QAction( tr("Line &numbers in filtered view"), this );
273     lineNumbersVisibleInFilteredAction->setCheckable( true );
274     lineNumbersVisibleInFilteredAction->setChecked( config->filteredLineNumbersVisible() );
275     connect( lineNumbersVisibleInFilteredAction, SIGNAL( toggled( bool ) ),
276             this, SLOT( toggleFilteredLineNumbersVisibility( bool )) );
277 
278     followAction = new QAction( tr("&Follow File"), this );
279     followAction->setShortcut(Qt::Key_F);
280     followAction->setCheckable(true);
281     connect( followAction, SIGNAL(toggled( bool )),
282             this, SIGNAL(followSet( bool )) );
283 
284     reloadAction = new QAction( tr("&Reload"), this );
285     reloadAction->setShortcut(QKeySequence::Refresh);
286     reloadAction->setIcon( QIcon(":/images/reload16.png") );
287     signalMux_.connect( reloadAction, SIGNAL(triggered()), SLOT(reload()) );
288 
289     stopAction = new QAction( tr("&Stop"), this );
290     stopAction->setIcon( QIcon(":/images/stop16.png") );
291     stopAction->setEnabled( true );
292     signalMux_.connect( stopAction, SIGNAL(triggered()), SLOT(stopLoading()) );
293 
294     filtersAction = new QAction(tr("&Filters..."), this);
295     filtersAction->setStatusTip(tr("Show the Filters box"));
296     connect( filtersAction, SIGNAL(triggered()), this, SLOT(filters()) );
297 
298     optionsAction = new QAction(tr("&Options..."), this);
299     optionsAction->setStatusTip(tr("Show the Options box"));
300     connect( optionsAction, SIGNAL(triggered()), this, SLOT(options()) );
301 
302     aboutAction = new QAction(tr("&About"), this);
303     aboutAction->setStatusTip(tr("Show the About box"));
304     connect( aboutAction, SIGNAL(triggered()), this, SLOT(about()) );
305 
306     aboutQtAction = new QAction(tr("About &Qt"), this);
307     aboutAction->setStatusTip(tr("Show the Qt library's About box"));
308     connect( aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()) );
309 }
310 
311 void MainWindow::createMenus()
312 {
313     fileMenu = menuBar()->addMenu( tr("&File") );
314     fileMenu->addAction( openAction );
315     fileMenu->addSeparator();
316     for (int i = 0; i < MaxRecentFiles; ++i) {
317         fileMenu->addAction( recentFileActions[i] );
318         recentFileActionBehaviors[i] =
319             new MenuActionToolTipBehavior(recentFileActions[i], fileMenu, this);
320     }
321     fileMenu->addSeparator();
322     fileMenu->addAction( exitAction );
323 
324     editMenu = menuBar()->addMenu( tr("&Edit") );
325     editMenu->addAction( copyAction );
326     editMenu->addAction( selectAllAction );
327     editMenu->addSeparator();
328     editMenu->addAction( findAction );
329 
330     viewMenu = menuBar()->addMenu( tr("&View") );
331     viewMenu->addAction( overviewVisibleAction );
332     viewMenu->addSeparator();
333     viewMenu->addAction( lineNumbersVisibleInMainAction );
334     viewMenu->addAction( lineNumbersVisibleInFilteredAction );
335     viewMenu->addSeparator();
336     viewMenu->addAction( followAction );
337     viewMenu->addSeparator();
338     viewMenu->addAction( reloadAction );
339 
340     toolsMenu = menuBar()->addMenu( tr("&Tools") );
341     toolsMenu->addAction( filtersAction );
342     toolsMenu->addSeparator();
343     toolsMenu->addAction( optionsAction );
344 
345     menuBar()->addSeparator();
346 
347     helpMenu = menuBar()->addMenu( tr("&Help") );
348     helpMenu->addAction( aboutAction );
349 }
350 
351 void MainWindow::createToolBars()
352 {
353     infoLine = new InfoLine();
354     infoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
355     infoLine->setLineWidth( 0 );
356 
357     lineNbField = new QLabel( );
358     lineNbField->setText( "Line 0" );
359     lineNbField->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
360     lineNbField->setMinimumSize(
361             lineNbField->fontMetrics().size( 0, "Line 0000000") );
362 
363     toolBar = addToolBar( tr("&Toolbar") );
364     toolBar->setIconSize( QSize( 16, 16 ) );
365     toolBar->setMovable( false );
366     toolBar->addAction( openAction );
367     toolBar->addAction( reloadAction );
368     toolBar->addWidget( infoLine );
369     toolBar->addAction( stopAction );
370     toolBar->addWidget( lineNbField );
371 }
372 
373 //
374 // Slots
375 //
376 
377 // Opens the file selection dialog to select a new log file
378 void MainWindow::open()
379 {
380     QString defaultDir = ".";
381 
382     // Default to the path of the current file if there is one
383     if ( auto current = currentCrawlerWidget() )
384     {
385         std::string current_file = session_->getFilename( current );
386         QFileInfo fileInfo = QFileInfo( QString( current_file.c_str() ) );
387         defaultDir = fileInfo.path();
388     }
389 
390     QString fileName = QFileDialog::getOpenFileName(this,
391             tr("Open file"), defaultDir, tr("All files (*)"));
392     if (!fileName.isEmpty())
393         loadFile(fileName);
394 }
395 
396 // Opens a log file from the recent files list
397 void MainWindow::openRecentFile()
398 {
399     QAction* action = qobject_cast<QAction*>(sender());
400     if (action)
401         loadFile(action->data().toString());
402 }
403 
404 // Select all the text in the currently selected view
405 void MainWindow::selectAll()
406 {
407     CrawlerWidget* current = currentCrawlerWidget();
408 
409     if ( current )
410         current->selectAll();
411 }
412 
413 // Copy the currently selected line into the clipboard
414 void MainWindow::copy()
415 {
416     static QClipboard* clipboard = QApplication::clipboard();
417     CrawlerWidget* current = currentCrawlerWidget();
418 
419     if ( current ) {
420         clipboard->setText( current->getSelectedText() );
421 
422         // Put it in the global selection as well (X11 only)
423         clipboard->setText( current->getSelectedText(),
424                 QClipboard::Selection );
425     }
426 }
427 
428 // Display the QuickFind bar
429 void MainWindow::find()
430 {
431     displayQuickFindBar( QuickFindMux::Forward );
432 }
433 
434 // Opens the 'Filters' dialog box
435 void MainWindow::filters()
436 {
437     FiltersDialog dialog(this);
438     signalMux_.connect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
439     dialog.exec();
440     signalMux_.disconnect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
441 }
442 
443 // Opens the 'Options' modal dialog box
444 void MainWindow::options()
445 {
446     OptionsDialog dialog(this);
447     signalMux_.connect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
448     dialog.exec();
449     signalMux_.disconnect(&dialog, SIGNAL( optionsChanged() ), SLOT( applyConfiguration() ));
450 }
451 
452 // Opens the 'About' dialog box.
453 void MainWindow::about()
454 {
455     QMessageBox::about(this, tr("About glogg"),
456             tr("<h2>glogg " GLOGG_VERSION "</h2>"
457                 "<p>A fast, advanced log explorer."
458 #ifdef GLOGG_COMMIT
459                 "<p>Built " GLOGG_DATE " from " GLOGG_COMMIT
460 #endif
461                 "<p><a href=\"http://glogg.bonnefon.org/\">http://glogg.bonnefon.org/</a></p>"
462                 "<p>Copyright &copy; 2009, 2010, 2011, 2012, 2013, 2014 Nicolas Bonnefon and other contributors"
463                 "<p>You may modify and redistribute the program under the terms of the GPL (version 3 or later)." ) );
464 }
465 
466 // Opens the 'About Qt' dialog box.
467 void MainWindow::aboutQt()
468 {
469 }
470 
471 void MainWindow::toggleOverviewVisibility( bool isVisible )
472 {
473     std::shared_ptr<Configuration> config =
474         Persistent<Configuration>( "settings" );
475     config->setOverviewVisible( isVisible );
476     emit optionsChanged();
477 }
478 
479 void MainWindow::toggleMainLineNumbersVisibility( bool isVisible )
480 {
481     std::shared_ptr<Configuration> config =
482         Persistent<Configuration>( "settings" );
483     config->setMainLineNumbersVisible( isVisible );
484     emit optionsChanged();
485 }
486 
487 void MainWindow::toggleFilteredLineNumbersVisibility( bool isVisible )
488 {
489     std::shared_ptr<Configuration> config =
490         Persistent<Configuration>( "settings" );
491     config->setFilteredLineNumbersVisible( isVisible );
492     emit optionsChanged();
493 }
494 
495 void MainWindow::disableFollow()
496 {
497     followAction->setChecked( false );
498 }
499 
500 void MainWindow::lineNumberHandler( int line )
501 {
502     // The line number received is the internal (starts at 0)
503     lineNbField->setText( tr( "Line %1" ).arg( line + 1 ) );
504 }
505 
506 void MainWindow::updateLoadingProgress( int progress )
507 {
508     LOG(logDEBUG) << "Loading progress: " << progress;
509 
510     QString current_file =
511         session_->getFilename( currentCrawlerWidget() ).c_str();
512 
513     // We ignore 0% and 100% to avoid a flash when the file (or update)
514     // is very short.
515     if ( progress > 0 && progress < 100 ) {
516         infoLine->setText( current_file +
517                 tr( " - Indexing lines... (%1 %)" ).arg( progress ) );
518         infoLine->displayGauge( progress );
519 
520         stopAction->setEnabled( true );
521         reloadAction->setEnabled( false );
522     }
523 }
524 
525 void MainWindow::handleLoadingFinished( LoadingStatus status )
526 {
527     QLocale defaultLocale;
528 
529     LOG(logDEBUG) << "handleLoadingFinished success=" <<
530         ( status == LoadingStatus::Successful );
531 
532     // No file is loading
533     loadingFileName.clear();
534 
535     if ( status == LoadingStatus::Successful )
536     {
537         // Following should always work as we will only receive enter
538         // this slot if there is a crawler connected.
539         QString current_file =
540             session_->getFilename( currentCrawlerWidget() ).c_str();
541 
542         uint64_t fileSize;
543         uint32_t fileNbLine;
544         QDateTime lastModified;
545 
546         session_->getFileInfo( currentCrawlerWidget(),
547                 &fileSize, &fileNbLine, &lastModified );
548         if ( lastModified.isValid() ) {
549             const QString date =
550                 defaultLocale.toString( lastModified, QLocale::NarrowFormat );
551             infoLine->setText( tr( "%1 (%2 - %3 lines - modified on %4)" )
552                     .arg(current_file).arg(readableSize(fileSize))
553                     .arg(fileNbLine).arg( date ) );
554         }
555         else {
556             infoLine->setText( tr( "%1 (%2 - %3 lines)" )
557                     .arg(current_file).arg(readableSize(fileSize))
558                     .arg(fileNbLine) );
559         }
560 
561         infoLine->hideGauge();
562         stopAction->setEnabled( false );
563         reloadAction->setEnabled( true );
564 
565         // Now everything is ready, we can finally show the file!
566         currentCrawlerWidget()->show();
567     }
568     else
569     {
570         if ( status == LoadingStatus::NoMemory )
571         {
572             QMessageBox alertBox;
573             alertBox.setText( "Not enough memory." );
574             alertBox.setInformativeText( "The system does not have enough \
575 memory to hold the index for this file. The file will now be closed." );
576             alertBox.setIcon( QMessageBox::Critical );
577             alertBox.exec();
578         }
579 
580         closeTab( mainTabWidget_.currentIndex()  );
581     }
582 
583     // mainTabWidget_.setEnabled( true );
584 }
585 
586 void MainWindow::closeTab( int index )
587 {
588     auto widget = dynamic_cast<CrawlerWidget*>(
589             mainTabWidget_.widget( index ) );
590 
591     assert( widget );
592 
593     widget->stopLoading();
594     mainTabWidget_.removeTab( index );
595     session_->close( widget );
596     delete widget;
597 }
598 
599 void MainWindow::currentTabChanged( int index )
600 {
601     LOG(logDEBUG) << "currentTabChanged";
602 
603     if ( index >= 0 )
604     {
605         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
606                 mainTabWidget_.widget( index ) );
607         signalMux_.setCurrentDocument( crawler_widget );
608         quickFindMux_.registerSelector( crawler_widget );
609 
610         // New tab is set up with fonts etc...
611         emit optionsChanged();
612 
613         // Update the title bar
614         updateTitleBar( QString(
615                     session_->getFilename( crawler_widget ).c_str() ) );
616     }
617     else
618     {
619         // No tab left
620         signalMux_.setCurrentDocument( nullptr );
621         quickFindMux_.registerSelector( nullptr );
622 
623         infoLine->hideGauge();
624         infoLine->clear();
625 
626         updateTitleBar( QString() );
627     }
628 }
629 
630 void MainWindow::changeQFPattern( const QString& newPattern )
631 {
632     quickFindWidget_.changeDisplayedPattern( newPattern );
633 }
634 
635 void MainWindow::loadFileNonInteractive( const QString& file_name )
636 {
637     LOG(logDEBUG) << "loadFileNonInteractive( "
638         << file_name.toStdString() << " )";
639 
640     loadFile( file_name );
641 }
642 
643 void MainWindow::newVersionNotification( const QString& new_version )
644 {
645     LOG(logDEBUG) << "newVersionNotification( " <<
646         new_version.toStdString() << " )";
647 
648     QMessageBox msgBox;
649     msgBox.setText( QString( "A new version of glogg (%1) is available for download <p>"
650                 "<a href=\"http://glogg.bonnefon.org/download.html\">http://glogg.bonnefon.org/download.html</a>"
651                 ).arg( new_version ) );
652     msgBox.exec();
653 }
654 
655 //
656 // Events
657 //
658 
659 // Closes the application
660 void MainWindow::closeEvent( QCloseEvent *event )
661 {
662     writeSettings();
663     event->accept();
664 }
665 
666 // Accepts the drag event if it looks like a filename
667 void MainWindow::dragEnterEvent( QDragEnterEvent* event )
668 {
669     if ( event->mimeData()->hasFormat( "text/uri-list" ) )
670         event->acceptProposedAction();
671 }
672 
673 // Tries and loads the file if the URL dropped is local
674 void MainWindow::dropEvent( QDropEvent* event )
675 {
676     QList<QUrl> urls = event->mimeData()->urls();
677     if ( urls.isEmpty() )
678         return;
679 
680     QString fileName = urls.first().toLocalFile();
681     if ( fileName.isEmpty() )
682         return;
683 
684     loadFile( fileName );
685 }
686 
687 void MainWindow::keyPressEvent( QKeyEvent* keyEvent )
688 {
689     LOG(logDEBUG4) << "keyPressEvent received";
690 
691     switch ( (keyEvent->text())[0].toLatin1() ) {
692         case '/':
693             displayQuickFindBar( QuickFindMux::Forward );
694             break;
695         case '?':
696             displayQuickFindBar( QuickFindMux::Backward );
697             break;
698         default:
699             keyEvent->ignore();
700     }
701 
702     if ( !keyEvent->isAccepted() )
703         QMainWindow::keyPressEvent( keyEvent );
704 }
705 
706 //
707 // Private functions
708 //
709 
710 // Create a CrawlerWidget for the passed file, start its loading
711 // and update the title bar.
712 // The loading is done asynchronously.
713 bool MainWindow::loadFile( const QString& fileName )
714 {
715     LOG(logDEBUG) << "loadFile ( " << fileName.toStdString() << " )";
716 
717     // First check if the file is already open...
718     CrawlerWidget* existing_crawler = dynamic_cast<CrawlerWidget*>(
719             session_->getViewIfOpen( fileName.toStdString() ) );
720     if ( existing_crawler ) {
721         // ... and switch to it.
722         mainTabWidget_.setCurrentWidget( existing_crawler );
723 
724         return true;
725     }
726 
727     // Load the file
728     loadingFileName = fileName;
729 
730     try {
731         CrawlerWidget* crawler_widget = dynamic_cast<CrawlerWidget*>(
732                 session_->open( fileName.toStdString(),
733                     []() { return new CrawlerWidget(); } ) );
734         assert( crawler_widget );
735 
736         // We won't show the widget until the file is fully loaded
737         crawler_widget->hide();
738 
739         // We disable the tab widget to avoid having someone switch
740         // tab during loading. (maybe FIXME)
741         //mainTabWidget_.setEnabled( false );
742 
743         int index = mainTabWidget_.addTab(
744                 crawler_widget, strippedName( fileName ) );
745 
746         // Setting the new tab, the user will see a blank page for the duration
747         // of the loading, with no way to switch to another tab
748         mainTabWidget_.setCurrentIndex( index );
749 
750         // Update the recent files list
751         // (reload the list first in case another glogg changed it)
752         GetPersistentInfo().retrieve( "recentFiles" );
753         recentFiles_->addRecent( fileName );
754         GetPersistentInfo().save( "recentFiles" );
755         updateRecentFileActions();
756     }
757     catch ( FileUnreadableErr ) {
758         LOG(logDEBUG) << "Can't open file " << fileName.toStdString();
759         return false;
760     }
761 
762     LOG(logDEBUG) << "Success loading file " << fileName.toStdString();
763     return true;
764 
765 }
766 
767 // Strips the passed filename from its directory part.
768 QString MainWindow::strippedName( const QString& fullFileName ) const
769 {
770     return QFileInfo( fullFileName ).fileName();
771 }
772 
773 // Return the currently active CrawlerWidget, or NULL if none
774 CrawlerWidget* MainWindow::currentCrawlerWidget() const
775 {
776     auto current = dynamic_cast<CrawlerWidget*>(
777             mainTabWidget_.currentWidget() );
778 
779     return current;
780 }
781 
782 // Update the title bar.
783 void MainWindow::updateTitleBar( const QString& file_name )
784 {
785     QString shownName = tr( "Untitled" );
786     if ( !file_name.isEmpty() )
787         shownName = strippedName( file_name );
788 
789     setWindowTitle(
790             tr("%1 - %2").arg(shownName).arg(tr("glogg"))
791 #ifdef GLOGG_COMMIT
792             + " (dev build " GLOGG_VERSION ")"
793 #endif
794             );
795 }
796 
797 // Updates the actions for the recent files.
798 // Must be called after having added a new name to the list.
799 void MainWindow::updateRecentFileActions()
800 {
801     QStringList recent_files = recentFiles_->recentFiles();
802 
803     for ( int j = 0; j < MaxRecentFiles; ++j ) {
804         if ( j < recent_files.count() ) {
805             QString text = tr("&%1 %2").arg(j + 1).arg(strippedName(recent_files[j]));
806             recentFileActions[j]->setText( text );
807             recentFileActions[j]->setToolTip( recent_files[j] );
808             recentFileActions[j]->setData( recent_files[j] );
809             recentFileActions[j]->setVisible( true );
810         }
811         else {
812             recentFileActions[j]->setVisible( false );
813         }
814     }
815 
816     // separatorAction->setVisible(!recentFiles.isEmpty());
817 }
818 
819 // Write settings to permanent storage
820 void MainWindow::writeSettings()
821 {
822     // Save the session
823     // Generate the ordered list of widgets and their topLine
824     std::vector<
825             std::tuple<const ViewInterface*, uint64_t, std::shared_ptr<const ViewContextInterface>>
826         > widget_list;
827     for ( int i = 0; i < mainTabWidget_.count(); ++i )
828     {
829         auto view = dynamic_cast<const ViewInterface*>( mainTabWidget_.widget( i ) );
830         widget_list.push_back( std::make_tuple(
831                 view,
832                 0UL,
833                 view->context() ) );
834     }
835     session_->save( widget_list );
836     //SessionInfo& session = Persistent<SessionInfo>( "session" );
837     //session.setGeometry( saveGeometry() );
838     //session.setCrawlerState( crawlerWidget->saveState() );
839     //GetPersistentInfo().save( QString( "session" ) );
840 
841     // User settings
842     GetPersistentInfo().save( QString( "settings" ) );
843 }
844 
845 // Read settings from permanent storage
846 void MainWindow::readSettings()
847 {
848     // Get and restore the session
849     // GetPersistentInfo().retrieve( QString( "session" ) );
850     // SessionInfo session = Persistent<SessionInfo>( "session" );
851     //restoreGeometry( session.geometry() );
852     /*
853      * FIXME: should be in the session
854     crawlerWidget->restoreState( session.crawlerState() );
855     */
856 
857     // History of recent files
858     GetPersistentInfo().retrieve( QString( "recentFiles" ) );
859     updateRecentFileActions();
860 
861     // GetPersistentInfo().retrieve( QString( "settings" ) );
862     GetPersistentInfo().retrieve( QString( "filterSet" ) );
863 }
864 
865 void MainWindow::displayQuickFindBar( QuickFindMux::QFDirection direction )
866 {
867     LOG(logDEBUG) << "MainWindow::displayQuickFindBar";
868 
869     // Warn crawlers so they can save the position of the focus in order
870     // to do incremental search in the right view.
871     emit enteringQuickFind();
872 
873     quickFindMux_.setDirection( direction );
874     quickFindWidget_.userActivate();
875 }
876 
877 // Returns the size in human readable format
878 static QString readableSize( qint64 size )
879 {
880     static const QString sizeStrs[] = {
881         QObject::tr("B"), QObject::tr("KiB"), QObject::tr("MiB"),
882         QObject::tr("GiB"), QObject::tr("TiB") };
883 
884     QLocale defaultLocale;
885     unsigned int i;
886     double humanSize = size;
887 
888     for ( i=0; i+1 < (sizeof(sizeStrs)/sizeof(QString)) && (humanSize/1024.0) >= 1024.0; i++ )
889         humanSize /= 1024.0;
890 
891     if ( humanSize >= 1024.0 ) {
892         humanSize /= 1024.0;
893         i++;
894     }
895 
896     QString output;
897     if ( i == 0 )
898         // No decimal part if we display straight bytes.
899         output = defaultLocale.toString( (int) humanSize );
900     else
901         output = defaultLocale.toString( humanSize, 'f', 1 );
902 
903     output += QString(" ") + sizeStrs[i];
904 
905     return output;
906 }
907