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