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