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