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