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