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