xref: /glogg/src/mainwindow.cpp (revision 32e44cfdc623782d0ed539a56e61636702f974ba)
1 /*
2  * Copyright (C) 2009, 2010, 2011, 2013 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 
26 #include <QAction>
27 #include <QDesktopWidget>
28 #include <QMenuBar>
29 #include <QToolBar>
30 #include <QFileInfo>
31 #include <QFileDialog>
32 #include <QClipboard>
33 #include <QMessageBox>
34 #include <QCloseEvent>
35 #include <QDragEnterEvent>
36 #include <QMimeData>
37 #include <QUrl>
38 
39 #include "log.h"
40 
41 #include "mainwindow.h"
42 
43 #include "sessioninfo.h"
44 #include "recentfiles.h"
45 #include "crawlerwidget.h"
46 #include "filtersdialog.h"
47 #include "optionsdialog.h"
48 #include "persistentinfo.h"
49 #include "savedsearches.h"
50 #include "menuactiontooltipbehavior.h"
51 
52 // Returns the size in human readable format
53 static QString readableSize( qint64 size );
54 
55 MainWindow::MainWindow( std::unique_ptr<Session> session ) :
56     session_( std::move( session )  ),
57     recentFiles( Persistent<RecentFiles>( "recentFiles" ) ),
58     mainIcon_(),
59     signalMux_()
60 {
61     createActions();
62     createMenus();
63     // createContextMenu();
64     createToolBars();
65     // createStatusBar();
66 
67     setAcceptDrops( true );
68 
69     // Default geometry
70     const QRect geometry = QApplication::desktop()->availableGeometry( this );
71     setGeometry( geometry.x() + 20, geometry.y() + 40,
72             geometry.width() - 140, geometry.height() - 140 );
73 
74     mainIcon_.addFile( ":/images/hicolor/16x16/glogg.png" );
75     mainIcon_.addFile( ":/images/hicolor/24x24/glogg.png" );
76     mainIcon_.addFile( ":/images/hicolor/32x32/glogg.png" );
77     mainIcon_.addFile( ":/images/hicolor/48x48/glogg.png" );
78 
79     setWindowIcon( mainIcon_ );
80 
81     readSettings();
82 
83     crawlerWidget = nullptr;
84 }
85 
86 void MainWindow::loadInitialFile( QString fileName )
87 {
88     LOG(logDEBUG) << "loadInitialFile";
89 
90     // Is there a file passed as argument?
91     if ( !fileName.isEmpty() )
92         loadFile( fileName );
93     else if ( !previousFile.isEmpty() )
94         loadFile( previousFile );
95 }
96 
97 //
98 // Private functions
99 //
100 
101 // Menu actions
102 void MainWindow::createActions()
103 {
104     Configuration& config = Persistent<Configuration>( "settings" );
105 
106     openAction = new QAction(tr("&Open..."), this);
107     openAction->setShortcut(QKeySequence::Open);
108     openAction->setIcon( QIcon(":/images/open16.png") );
109     openAction->setStatusTip(tr("Open a file"));
110     connect(openAction, SIGNAL(triggered()), this, SLOT(open()));
111 
112     // Recent files
113     for (int i = 0; i < MaxRecentFiles; ++i) {
114         recentFileActions[i] = new QAction(this);
115         recentFileActions[i]->setVisible(false);
116         connect(recentFileActions[i], SIGNAL(triggered()),
117                 this, SLOT(openRecentFile()));
118     }
119 
120     exitAction = new QAction(tr("E&xit"), this);
121     exitAction->setShortcut(tr("Ctrl+Q"));
122     exitAction->setStatusTip(tr("Exit the application"));
123     connect( exitAction, SIGNAL(triggered()), this, SLOT(close()) );
124 
125     copyAction = new QAction(tr("&Copy"), this);
126     copyAction->setShortcut(QKeySequence::Copy);
127     copyAction->setStatusTip(tr("Copy the selection"));
128     connect( copyAction, SIGNAL(triggered()), this, SLOT(copy()) );
129 
130     selectAllAction = new QAction(tr("Select &All"), this);
131     selectAllAction->setShortcut(tr("Ctrl+A"));
132     selectAllAction->setStatusTip(tr("Select all the text"));
133     connect( selectAllAction, SIGNAL(triggered()),
134              this, SLOT( selectAll() ) );
135 
136     findAction = new QAction(tr("&Find..."), this);
137     findAction->setShortcut(QKeySequence::Find);
138     findAction->setStatusTip(tr("Find the text"));
139     connect( findAction, SIGNAL(triggered()),
140             this, SLOT( find() ) );
141 
142     overviewVisibleAction = new QAction( tr("Matches &overview"), this );
143     overviewVisibleAction->setCheckable( true );
144     overviewVisibleAction->setChecked( config.isOverviewVisible() );
145     connect( overviewVisibleAction, SIGNAL( toggled( bool ) ),
146             this, SLOT( toggleOverviewVisibility( bool )) );
147 
148     lineNumbersVisibleInMainAction =
149         new QAction( tr("Line &numbers in main view"), this );
150     lineNumbersVisibleInMainAction->setCheckable( true );
151     lineNumbersVisibleInMainAction->setChecked( config.mainLineNumbersVisible() );
152     connect( lineNumbersVisibleInMainAction, SIGNAL( toggled( bool ) ),
153             this, SLOT( toggleMainLineNumbersVisibility( bool )) );
154 
155     lineNumbersVisibleInFilteredAction =
156         new QAction( tr("Line &numbers in filtered view"), this );
157     lineNumbersVisibleInFilteredAction->setCheckable( true );
158     lineNumbersVisibleInFilteredAction->setChecked( config.filteredLineNumbersVisible() );
159     connect( lineNumbersVisibleInFilteredAction, SIGNAL( toggled( bool ) ),
160             this, SLOT( toggleFilteredLineNumbersVisibility( bool )) );
161 
162     followAction = new QAction( tr("&Follow File"), this );
163     followAction->setShortcut(Qt::Key_F);
164     followAction->setCheckable(true);
165     connect( followAction, SIGNAL(toggled( bool )),
166             this, SIGNAL(followSet( bool )) );
167 
168     reloadAction = new QAction( tr("&Reload"), this );
169     reloadAction->setShortcut(QKeySequence::Refresh);
170     reloadAction->setIcon( QIcon(":/images/reload16.png") );
171     signalMux_.connect( reloadAction, SIGNAL(triggered()), SLOT(reload()) );
172 
173     stopAction = new QAction( tr("&Stop"), this );
174     stopAction->setIcon( QIcon(":/images/stop16.png") );
175     stopAction->setEnabled( false );
176     connect( stopAction, SIGNAL(triggered()), this, SLOT(stop()) );
177 
178     filtersAction = new QAction(tr("&Filters..."), this);
179     filtersAction->setStatusTip(tr("Show the Filters box"));
180     connect( filtersAction, SIGNAL(triggered()), this, SLOT(filters()) );
181 
182     optionsAction = new QAction(tr("&Options..."), this);
183     optionsAction->setStatusTip(tr("Show the Options box"));
184     connect( optionsAction, SIGNAL(triggered()), this, SLOT(options()) );
185 
186     aboutAction = new QAction(tr("&About"), this);
187     aboutAction->setStatusTip(tr("Show the About box"));
188     connect( aboutAction, SIGNAL(triggered()), this, SLOT(about()) );
189 
190     aboutQtAction = new QAction(tr("About &Qt"), this);
191     aboutAction->setStatusTip(tr("Show the Qt library's About box"));
192     connect( aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()) );
193 }
194 
195 void MainWindow::createMenus()
196 {
197     fileMenu = menuBar()->addMenu( tr("&File") );
198     fileMenu->addAction( openAction );
199     fileMenu->addSeparator();
200     for (int i = 0; i < MaxRecentFiles; ++i) {
201         fileMenu->addAction( recentFileActions[i] );
202         recentFileActionBehaviors[i] =
203             new MenuActionToolTipBehavior(recentFileActions[i], fileMenu, this);
204     }
205     fileMenu->addSeparator();
206     fileMenu->addAction( exitAction );
207 
208     editMenu = menuBar()->addMenu( tr("&Edit") );
209     editMenu->addAction( copyAction );
210     editMenu->addAction( selectAllAction );
211     editMenu->addSeparator();
212     editMenu->addAction( findAction );
213 
214     viewMenu = menuBar()->addMenu( tr("&View") );
215     viewMenu->addAction( overviewVisibleAction );
216     viewMenu->addSeparator();
217     viewMenu->addAction( lineNumbersVisibleInMainAction );
218     viewMenu->addAction( lineNumbersVisibleInFilteredAction );
219     viewMenu->addSeparator();
220     viewMenu->addAction( followAction );
221     viewMenu->addSeparator();
222     viewMenu->addAction( reloadAction );
223 
224     toolsMenu = menuBar()->addMenu( tr("&Tools") );
225     toolsMenu->addAction( filtersAction );
226     toolsMenu->addSeparator();
227     toolsMenu->addAction( optionsAction );
228 
229     menuBar()->addSeparator();
230 
231     helpMenu = menuBar()->addMenu( tr("&Help") );
232     helpMenu->addAction( aboutAction );
233 }
234 
235 void MainWindow::createToolBars()
236 {
237     infoLine = new InfoLine();
238     infoLine->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
239     infoLine->setLineWidth( 0 );
240 
241     lineNbField = new QLabel( );
242     lineNbField->setText( "Line 0" );
243     lineNbField->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
244     lineNbField->setMinimumSize(
245             lineNbField->fontMetrics().size( 0, "Line 0000000") );
246 
247     toolBar = addToolBar( tr("&Toolbar") );
248     toolBar->setIconSize( QSize( 16, 16 ) );
249     toolBar->setMovable( false );
250     toolBar->addAction( openAction );
251     toolBar->addAction( reloadAction );
252     toolBar->addWidget( infoLine );
253     toolBar->addAction( stopAction );
254     toolBar->addWidget( lineNbField );
255 }
256 
257 //
258 // Slots
259 //
260 
261 // Opens the file selection dialog to select a new log file
262 void MainWindow::open()
263 {
264     QString defaultDir = ".";
265 
266     // Default to the path of the current file if there is one
267     if ( !currentFile.isEmpty() ) {
268         QFileInfo fileInfo = QFileInfo( currentFile );
269         defaultDir = fileInfo.path();
270     }
271 
272     QString fileName = QFileDialog::getOpenFileName(this,
273             tr("Open file"), defaultDir, tr("All files (*)"));
274     if (!fileName.isEmpty())
275         loadFile(fileName);
276 }
277 
278 // Opens a log file from the recent files list
279 void MainWindow::openRecentFile()
280 {
281     QAction* action = qobject_cast<QAction*>(sender());
282     if (action)
283         loadFile(action->data().toString());
284 }
285 
286 // Select all the text in the currently selected view
287 void MainWindow::selectAll()
288 {
289     crawlerWidget->selectAll();
290 }
291 
292 // Copy the currently selected line into the clipboard
293 void MainWindow::copy()
294 {
295     static QClipboard* clipboard = QApplication::clipboard();
296 
297     clipboard->setText( crawlerWidget->getSelectedText() );
298 
299     // Put it in the global selection as well (X11 only)
300     clipboard->setText( crawlerWidget->getSelectedText(),
301             QClipboard::Selection );
302 }
303 
304 // Display the QuickFind bar
305 void MainWindow::find()
306 {
307     crawlerWidget->displayQuickFindBar( QuickFindMux::Forward );
308 }
309 
310 // Stop the loading operation
311 void MainWindow::stop()
312 {
313     session_->stopLoading( crawlerWidget );
314 }
315 
316 // Opens the 'Filters' dialog box
317 void MainWindow::filters()
318 {
319     FiltersDialog dialog(this);
320     connect(&dialog, SIGNAL( optionsChanged() ), crawlerWidget, SLOT( applyConfiguration() ));
321     dialog.exec();
322 }
323 
324 // Opens the 'Options' modal dialog box
325 void MainWindow::options()
326 {
327     OptionsDialog dialog(this);
328     connect(&dialog, SIGNAL( optionsChanged() ), crawlerWidget, SLOT( applyConfiguration() ));
329     dialog.exec();
330 }
331 
332 // Opens the 'About' dialog box.
333 void MainWindow::about()
334 {
335     QMessageBox::about(this, tr("About glogg"),
336             tr("<h2>glogg " GLOGG_VERSION "</h2>"
337                 "<p>A fast, advanced log explorer."
338 #ifdef GLOGG_COMMIT
339                 "<p>Built " GLOGG_DATE " from " GLOGG_COMMIT
340 #endif
341                 "<p>Copyright &copy; 2009, 2010, 2011, 2012, 2013 Nicolas Bonnefon and other contributors"
342                 "<p>You may modify and redistribute the program under the terms of the GPL (version 3 or later)." ) );
343 }
344 
345 // Opens the 'About Qt' dialog box.
346 void MainWindow::aboutQt()
347 {
348 }
349 
350 void MainWindow::toggleOverviewVisibility( bool isVisible )
351 {
352     Configuration& config = Persistent<Configuration>( "settings" );
353     config.setOverviewVisible( isVisible );
354     emit optionsChanged();
355 }
356 
357 void MainWindow::toggleMainLineNumbersVisibility( bool isVisible )
358 {
359     Configuration& config = Persistent<Configuration>( "settings" );
360     config.setMainLineNumbersVisible( isVisible );
361     emit optionsChanged();
362 }
363 
364 void MainWindow::toggleFilteredLineNumbersVisibility( bool isVisible )
365 {
366     Configuration& config = Persistent<Configuration>( "settings" );
367     config.setFilteredLineNumbersVisible( isVisible );
368     emit optionsChanged();
369 }
370 
371 void MainWindow::disableFollow()
372 {
373     followAction->setChecked( false );
374 }
375 
376 void MainWindow::lineNumberHandler( int line )
377 {
378     // The line number received is the internal (starts at 0)
379     lineNbField->setText( tr( "Line %1" ).arg( line + 1 ) );
380 }
381 
382 void MainWindow::updateLoadingProgress( int progress )
383 {
384     LOG(logDEBUG) << "Loading progress: " << progress;
385 
386     // We ignore 0% and 100% to avoid a flash when the file (or update)
387     // is very short.
388     if ( progress > 0 && progress < 100 ) {
389         infoLine->setText( loadingFileName + tr( " - Indexing lines... (%1 %)" ).arg( progress ) );
390         infoLine->displayGauge( progress );
391 
392         stopAction->setEnabled( true );
393     }
394 }
395 
396 void MainWindow::displayNormalStatus( bool success )
397 {
398     QLocale defaultLocale;
399 
400     LOG(logDEBUG) << "displayNormalStatus";
401 
402     if ( success )
403         setCurrentFile( loadingFileName );
404 
405     uint64_t fileSize;
406     uint32_t fileNbLine;
407     QDateTime lastModified;
408 
409     session_->getFileInfo( crawlerWidget,
410             &fileSize, &fileNbLine, &lastModified );
411     if ( lastModified.isValid() ) {
412         const QString date =
413             defaultLocale.toString( lastModified, QLocale::NarrowFormat );
414         infoLine->setText( tr( "%1 (%2 - %3 lines - modified on %4)" )
415                 .arg(currentFile).arg(readableSize(fileSize))
416                 .arg(fileNbLine).arg( date ) );
417     }
418     else {
419         infoLine->setText( tr( "%1 (%2 - %3 lines)" )
420                 .arg(currentFile).arg(readableSize(fileSize))
421                 .arg(fileNbLine) );
422     }
423 
424     infoLine->hideGauge();
425     stopAction->setEnabled( false );
426 
427     // Now everything is ready, we can finally show the file!
428     crawlerWidget->show();
429 }
430 
431 //
432 // Events
433 //
434 
435 // Closes the application
436 void MainWindow::closeEvent( QCloseEvent *event )
437 {
438     writeSettings();
439     event->accept();
440 }
441 
442 // Accepts the drag event if it looks like a filename
443 void MainWindow::dragEnterEvent( QDragEnterEvent* event )
444 {
445     if ( event->mimeData()->hasFormat( "text/uri-list" ) )
446         event->acceptProposedAction();
447 }
448 
449 // Tries and loads the file if the URL dropped is local
450 void MainWindow::dropEvent( QDropEvent* event )
451 {
452     QList<QUrl> urls = event->mimeData()->urls();
453     if ( urls.isEmpty() )
454         return;
455 
456     QString fileName = urls.first().toLocalFile();
457     if ( fileName.isEmpty() )
458         return;
459 
460     loadFile( fileName );
461 }
462 
463 //
464 // Private functions
465 //
466 
467 // Create a CrawlerWidget for the passed file, start its loading
468 // and update the title bar.
469 // The loading is done asynchronously.
470 bool MainWindow::loadFile( const QString& fileName )
471 {
472     LOG(logDEBUG) << "loadFile ( " << fileName.toStdString() << " )";
473 
474     // First get the global search history
475     savedSearches = &(Persistent<SavedSearches>( "savedSearches" ));
476 
477     // Load the file
478     loadingFileName = fileName;
479 
480     crawlerWidget = dynamic_cast<CrawlerWidget*>( session_->open( fileName.toStdString(),
481             [this]() { return new CrawlerWidget( savedSearches, this ); } ) );
482 
483     // We won't show the widget until the file is fully loaded
484     crawlerWidget->hide();
485 
486     signalMux_.setCurrentDocument( crawlerWidget );
487 
488     // Send actions to the crawlerwidget
489     signalMux_.connect( this, SIGNAL( followSet( bool ) ),
490             SIGNAL( followSet( bool ) ) );
491     signalMux_.connect( this, SIGNAL( optionsChanged() ),
492             SLOT( applyConfiguration() ) );
493 
494     // Actions from the CrawlerWidget
495     signalMux_.connect( SIGNAL( followDisabled() ),
496             this, SLOT( disableFollow() ) );
497     signalMux_.connect( SIGNAL( updateLineNumber( int ) ),
498             this, SLOT( lineNumberHandler( int ) ) );
499 
500     // FIXME: is it necessary?
501     emit optionsChanged();
502 
503     // We start with the empty file
504     setCurrentFile( "" );
505 
506     // Register for progress status bar
507     signalMux_.connect( SIGNAL( loadingProgressed( int ) ),
508             this, SLOT( updateLoadingProgress( int ) ) );
509     signalMux_.connect( SIGNAL( loadingFinished( bool ) ),
510             this, SLOT( displayNormalStatus( bool ) ) );
511 
512     setCentralWidget(crawlerWidget);
513 
514     LOG(logDEBUG) << "Success loading file " << fileName.toStdString();
515     return true;
516 }
517 
518 // Strips the passed filename from its directory part.
519 QString MainWindow::strippedName( const QString& fullFileName ) const
520 {
521     return QFileInfo( fullFileName ).fileName();
522 }
523 
524 // Add the filename to the recent files list and update the title bar.
525 void MainWindow::setCurrentFile( const QString& fileName )
526 {
527     if ( fileName != currentFile )
528     {
529         // Change the current file
530         currentFile = fileName;
531         QString shownName = tr( "Untitled" );
532         if ( !currentFile.isEmpty() ) {
533             // (reload the list first in case another glogg changed it)
534             GetPersistentInfo().retrieve( "recentFiles" );
535             recentFiles.addRecent( currentFile );
536             GetPersistentInfo().save( "recentFiles" );
537             updateRecentFileActions();
538             shownName = strippedName( currentFile );
539         }
540 
541         setWindowTitle(
542                 tr("%1 - %2").arg(shownName).arg(tr("glogg"))
543 #ifdef GLOGG_COMMIT
544                 + " (dev build " GLOGG_VERSION ")"
545 #endif
546                 );
547     }
548     else
549     {
550         // Nothing, happens when e.g., the file is reloaded
551     }
552 }
553 
554 // Updates the actions for the recent files.
555 // Must be called after having added a new name to the list.
556 void MainWindow::updateRecentFileActions()
557 {
558     QStringList recent_files = recentFiles.recentFiles();
559 
560     for ( int j = 0; j < MaxRecentFiles; ++j ) {
561         if ( j < recent_files.count() ) {
562             QString text = tr("&%1 %2").arg(j + 1).arg(strippedName(recent_files[j]));
563             recentFileActions[j]->setText( text );
564             recentFileActions[j]->setToolTip( recent_files[j] );
565             recentFileActions[j]->setData( recent_files[j] );
566             recentFileActions[j]->setVisible( true );
567         }
568         else {
569             recentFileActions[j]->setVisible( false );
570         }
571     }
572 
573     // separatorAction->setVisible(!recentFiles.isEmpty());
574 }
575 
576 // Write settings to permanent storage
577 void MainWindow::writeSettings()
578 {
579     // Save the session
580     SessionInfo& session = Persistent<SessionInfo>( "session" );
581     session.setGeometry( saveGeometry() );
582     session.setCrawlerState( crawlerWidget->saveState() );
583     session.setCurrentFile( currentFile );
584     GetPersistentInfo().save( QString( "session" ) );
585 
586     // User settings
587     GetPersistentInfo().save( QString( "settings" ) );
588 }
589 
590 // Read settings from permanent storage
591 void MainWindow::readSettings()
592 {
593     // Get and restore the session
594     GetPersistentInfo().retrieve( QString( "session" ) );
595     SessionInfo session = Persistent<SessionInfo>( "session" );
596     restoreGeometry( session.geometry() );
597     previousFile = session.currentFile();
598     /*
599      * FIXME: should be in the session
600     crawlerWidget->restoreState( session.crawlerState() );
601     */
602 
603     // History of recent files
604     GetPersistentInfo().retrieve( QString( "recentFiles" ) );
605     updateRecentFileActions();
606 
607     GetPersistentInfo().retrieve( QString( "savedSearches" ) );
608     GetPersistentInfo().retrieve( QString( "settings" ) );
609     GetPersistentInfo().retrieve( QString( "filterSet" ) );
610 }
611 
612 // Returns the size in human readable format
613 static QString readableSize( qint64 size )
614 {
615     static const QString sizeStrs[] = {
616         QObject::tr("B"), QObject::tr("KiB"), QObject::tr("MiB"),
617         QObject::tr("GiB"), QObject::tr("TiB") };
618 
619     QLocale defaultLocale;
620     unsigned int i;
621     double humanSize = size;
622 
623     for ( i=0; i+1 < (sizeof(sizeStrs)/sizeof(QString)) && (humanSize/1024.0) >= 1024.0; i++ )
624         humanSize /= 1024.0;
625 
626     if ( humanSize >= 1024.0 ) {
627         humanSize /= 1024.0;
628         i++;
629     }
630 
631     QString output;
632     if ( i == 0 )
633         // No decimal part if we display straight bytes.
634         output = defaultLocale.toString( (int) humanSize );
635     else
636         output = defaultLocale.toString( humanSize, 'f', 1 );
637 
638     output += QString(" ") + sizeStrs[i];
639 
640     return output;
641 }
642