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