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