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