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