1 /* 2 * Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Nicolas Bonnefon 3 * and other contributors 4 * 5 * This file is part of glogg. 6 * 7 * glogg is free software: you can redistribute it and/or modify 8 * it under the terms of the GNU General Public License as published by 9 * the Free Software Foundation, either version 3 of the License, or 10 * (at your option) any later version. 11 * 12 * glogg is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with glogg. If not, see <http://www.gnu.org/licenses/>. 19 */ 20 21 // This file implements the AbstractLogView base class. 22 // Most of the actual drawing and event management common to the two views 23 // is implemented in this class. The class only calls protected virtual 24 // functions when view specific behaviour is desired, using the template 25 // pattern. 26 27 #include <iostream> 28 #include <cassert> 29 30 #include <QApplication> 31 #include <QClipboard> 32 #include <QFile> 33 #include <QRect> 34 #include <QPaintEvent> 35 #include <QPainter> 36 #include <QFontMetrics> 37 #include <QScrollBar> 38 #include <QMenu> 39 #include <QAction> 40 #include <QtCore> 41 #include <QGestureEvent> 42 43 #include "log.h" 44 45 #include "persistentinfo.h" 46 #include "filterset.h" 47 #include "logmainview.h" 48 #include "quickfind.h" 49 #include "quickfindpattern.h" 50 #include "overview.h" 51 #include "configuration.h" 52 53 namespace { 54 int mapPullToFollowLength( int length ); 55 }; 56 57 namespace { 58 59 int countDigits( quint64 n ) 60 { 61 if (n == 0) 62 return 1; 63 64 // We must force the compiler to not store intermediate results 65 // in registers because this causes incorrect result on some 66 // systems under optimizations level >0. For the skeptical: 67 // 68 // #include <math.h> 69 // #include <stdlib.h> 70 // int main(int argc, char **argv) { 71 // (void)argc; 72 // long long int n = atoll(argv[1]); 73 // return floor( log( n ) / log( 10 ) + 1 ); 74 // } 75 // 76 // This is on Thinkpad T60 (Genuine Intel(R) CPU T2300). 77 // $ g++ --version 78 // g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 79 // $ g++ -O0 -Wall -W -o math math.cpp -lm; ./math 10; echo $? 80 // 2 81 // $ g++ -O1 -Wall -W -o math math.cpp -lm; ./math 10; echo $? 82 // 1 83 // 84 // A fix is to (1) explicitly place intermediate results in 85 // variables *and* (2) [A] mark them as 'volatile', or [B] pass 86 // -ffloat-store to g++ (note that approach [A] is more portable). 87 88 volatile qreal ln_n = qLn( n ); 89 volatile qreal ln_10 = qLn( 10 ); 90 volatile qreal lg_n = ln_n / ln_10; 91 volatile qreal lg_n_1 = lg_n + 1; 92 volatile qreal fl_lg_n_1 = qFloor( lg_n_1 ); 93 94 return fl_lg_n_1; 95 } 96 97 } // anon namespace 98 99 100 LineChunk::LineChunk( int first_col, int last_col, ChunkType type ) 101 { 102 // LOG(logDEBUG) << "new LineChunk: " << first_col << " " << last_col; 103 104 start_ = first_col; 105 end_ = last_col; 106 type_ = type; 107 } 108 109 QList<LineChunk> LineChunk::select( int sel_start, int sel_end ) const 110 { 111 QList<LineChunk> list; 112 113 if ( ( sel_start < start_ ) && ( sel_end < start_ ) ) { 114 // Selection BEFORE this chunk: no change 115 list << LineChunk( *this ); 116 } 117 else if ( sel_start > end_ ) { 118 // Selection AFTER this chunk: no change 119 list << LineChunk( *this ); 120 } 121 else /* if ( ( sel_start >= start_ ) && ( sel_end <= end_ ) ) */ 122 { 123 // We only want to consider what's inside THIS chunk 124 sel_start = qMax( sel_start, start_ ); 125 sel_end = qMin( sel_end, end_ ); 126 127 if ( sel_start > start_ ) 128 list << LineChunk( start_, sel_start - 1, type_ ); 129 list << LineChunk( sel_start, sel_end, Selected ); 130 if ( sel_end < end_ ) 131 list << LineChunk( sel_end + 1, end_, type_ ); 132 } 133 134 return list; 135 } 136 137 inline void LineDrawer::addChunk( int first_col, int last_col, 138 QColor fore, QColor back ) 139 { 140 if ( first_col < 0 ) 141 first_col = 0; 142 int length = last_col - first_col + 1; 143 if ( length > 0 ) { 144 list << Chunk ( first_col, length, fore, back ); 145 } 146 } 147 148 inline void LineDrawer::addChunk( const LineChunk& chunk, 149 QColor fore, QColor back ) 150 { 151 int first_col = chunk.start(); 152 int last_col = chunk.end(); 153 154 addChunk( first_col, last_col, fore, back ); 155 } 156 157 inline void LineDrawer::draw( QPainter& painter, 158 int initialXPos, int initialYPos, 159 int line_width, const QString& line, 160 int leftExtraBackgroundPx ) 161 { 162 QFontMetrics fm = painter.fontMetrics(); 163 const int fontHeight = fm.height(); 164 const int fontAscent = fm.ascent(); 165 // For some reason on Qt 4.8.2 for Win, maxWidth() is wrong but the 166 // following give the right result, not sure why: 167 const int fontWidth = fm.width( QChar('a') ); 168 169 int xPos = initialXPos; 170 int yPos = initialYPos; 171 172 foreach ( Chunk chunk, list ) { 173 // Draw each chunk 174 // LOG(logDEBUG) << "Chunk: " << chunk.start() << " " << chunk.length(); 175 QString cutline = line.mid( chunk.start(), chunk.length() ); 176 const int chunk_width = cutline.length() * fontWidth; 177 if ( xPos == initialXPos ) { 178 // First chunk, we extend the left background a bit, 179 // it looks prettier. 180 painter.fillRect( xPos - leftExtraBackgroundPx, yPos, 181 chunk_width + leftExtraBackgroundPx, 182 fontHeight, chunk.backColor() ); 183 } 184 else { 185 // other chunks... 186 painter.fillRect( xPos, yPos, chunk_width, 187 fontHeight, chunk.backColor() ); 188 } 189 painter.setPen( chunk.foreColor() ); 190 painter.drawText( xPos, yPos + fontAscent, cutline ); 191 xPos += chunk_width; 192 } 193 194 // Draw the empty block at the end of the line 195 int blank_width = line_width - xPos; 196 197 if ( blank_width > 0 ) 198 painter.fillRect( xPos, yPos, blank_width, fontHeight, backColor_ ); 199 } 200 201 const int DigitsBuffer::timeout_ = 2000; 202 203 DigitsBuffer::DigitsBuffer() : QObject() 204 { 205 } 206 207 void DigitsBuffer::reset() 208 { 209 LOG(logDEBUG) << "DigitsBuffer::reset()"; 210 211 timer_.stop(); 212 digits_.clear(); 213 } 214 215 void DigitsBuffer::add( char character ) 216 { 217 LOG(logDEBUG) << "DigitsBuffer::add()"; 218 219 digits_.append( QChar( character ) ); 220 timer_.start( timeout_ , this ); 221 } 222 223 int DigitsBuffer::content() 224 { 225 int result = digits_.toInt(); 226 reset(); 227 228 return result; 229 } 230 231 void DigitsBuffer::timerEvent( QTimerEvent* event ) 232 { 233 if ( event->timerId() == timer_.timerId() ) { 234 reset(); 235 } 236 else { 237 QObject::timerEvent( event ); 238 } 239 } 240 241 AbstractLogView::AbstractLogView(const AbstractLogData* newLogData, 242 const QuickFindPattern* const quickFindPattern, QWidget* parent) : 243 QAbstractScrollArea( parent ), 244 followElasticHook_( HOOK_THRESHOLD ), 245 lineNumbersVisible_( false ), 246 selectionStartPos_(), 247 selectionCurrentEndPos_(), 248 autoScrollTimer_(), 249 selection_(), 250 quickFindPattern_( quickFindPattern ), 251 quickFind_( newLogData, &selection_, quickFindPattern ) 252 { 253 logData = newLogData; 254 255 followMode_ = false; 256 257 selectionStarted_ = false; 258 markingClickInitiated_ = false; 259 260 firstLine = 0; 261 lastLineAligned = false; 262 firstCol = 0; 263 264 overview_ = NULL; 265 overviewWidget_ = NULL; 266 267 // Display 268 leftMarginPx_ = 0; 269 270 // Fonts (sensible default for overview widget) 271 charWidth_ = 1; 272 charHeight_ = 10; 273 274 // Create the viewport QWidget 275 setViewport( 0 ); 276 277 // Hovering 278 setMouseTracking( true ); 279 lastHoveredLine_ = -1; 280 281 // Init the popup menu 282 createMenu(); 283 284 // Signals 285 connect( quickFindPattern_, SIGNAL( patternUpdated() ), 286 this, SLOT ( handlePatternUpdated() ) ); 287 connect( &quickFind_, SIGNAL( notify( const QFNotification& ) ), 288 this, SIGNAL( notifyQuickFind( const QFNotification& ) ) ); 289 connect( &quickFind_, SIGNAL( clearNotification() ), 290 this, SIGNAL( clearQuickFindNotification() ) ); 291 connect( &followElasticHook_, SIGNAL( lengthChanged() ), 292 this, SLOT( repaint() ) ); 293 connect( &followElasticHook_, SIGNAL( hooked( bool ) ), 294 this, SIGNAL( followModeChanged( bool ) ) ); 295 } 296 297 AbstractLogView::~AbstractLogView() 298 { 299 } 300 301 302 // 303 // Received events 304 // 305 306 void AbstractLogView::changeEvent( QEvent* changeEvent ) 307 { 308 QAbstractScrollArea::changeEvent( changeEvent ); 309 310 // Stop the timer if the widget becomes inactive 311 if ( changeEvent->type() == QEvent::ActivationChange ) { 312 if ( ! isActiveWindow() ) 313 autoScrollTimer_.stop(); 314 } 315 viewport()->update(); 316 } 317 318 void AbstractLogView::mousePressEvent( QMouseEvent* mouseEvent ) 319 { 320 static std::shared_ptr<Configuration> config = 321 Persistent<Configuration>( "settings" ); 322 323 if ( mouseEvent->button() == Qt::LeftButton ) 324 { 325 int line = convertCoordToLine( mouseEvent->y() ); 326 327 if ( mouseEvent->modifiers() & Qt::ShiftModifier ) 328 { 329 selection_.selectRangeFromPrevious( line ); 330 emit updateLineNumber( line ); 331 update(); 332 } 333 else 334 { 335 if ( mouseEvent->x() < bulletZoneWidthPx_ ) { 336 // Mark a line if it is clicked in the left margin 337 // (only if click and release in the same area) 338 markingClickInitiated_ = true; 339 markingClickLine_ = line; 340 } 341 else { 342 // Select the line, and start a selection 343 if ( line < logData->getNbLine() ) { 344 selection_.selectLine( line ); 345 emit updateLineNumber( line ); 346 emit newSelection( line ); 347 } 348 349 // Remember the click in case we're starting a selection 350 selectionStarted_ = true; 351 selectionStartPos_ = convertCoordToFilePos( mouseEvent->pos() ); 352 selectionCurrentEndPos_ = selectionStartPos_; 353 } 354 } 355 356 // Invalidate our cache 357 textAreaCache_.invalid_ = true; 358 } 359 else if ( mouseEvent->button() == Qt::RightButton ) 360 { 361 // Prepare the popup depending on selection type 362 if ( selection_.isSingleLine() ) { 363 copyAction_->setText( "&Copy this line" ); 364 } 365 else { 366 copyAction_->setText( "&Copy" ); 367 copyAction_->setStatusTip( tr("Copy the selection") ); 368 } 369 370 if ( selection_.isPortion() ) { 371 findNextAction_->setEnabled( true ); 372 findPreviousAction_->setEnabled( true ); 373 addToSearchAction_->setEnabled( true ); 374 } 375 else { 376 findNextAction_->setEnabled( false ); 377 findPreviousAction_->setEnabled( false ); 378 addToSearchAction_->setEnabled( false ); 379 } 380 381 // "Add to search" only makes sense in regexp mode 382 if ( config->mainRegexpType() != ExtendedRegexp ) 383 addToSearchAction_->setEnabled( false ); 384 385 // Display the popup (blocking) 386 popupMenu_->exec( QCursor::pos() ); 387 } 388 389 emit activity(); 390 } 391 392 void AbstractLogView::mouseMoveEvent( QMouseEvent* mouseEvent ) 393 { 394 // Selection implementation 395 if ( selectionStarted_ ) 396 { 397 // Invalidate our cache 398 textAreaCache_.invalid_ = true; 399 400 QPoint thisEndPos = convertCoordToFilePos( mouseEvent->pos() ); 401 if ( thisEndPos != selectionCurrentEndPos_ ) 402 { 403 // Are we on a different line? 404 if ( selectionStartPos_.y() != thisEndPos.y() ) 405 { 406 if ( thisEndPos.y() != selectionCurrentEndPos_.y() ) 407 { 408 // This is a 'range' selection 409 selection_.selectRange( selectionStartPos_.y(), 410 thisEndPos.y() ); 411 emit updateLineNumber( thisEndPos.y() ); 412 update(); 413 } 414 } 415 // So we are on the same line. Are we moving horizontaly? 416 else if ( thisEndPos.x() != selectionCurrentEndPos_.x() ) 417 { 418 // This is a 'portion' selection 419 selection_.selectPortion( thisEndPos.y(), 420 selectionStartPos_.x(), thisEndPos.x() ); 421 update(); 422 } 423 // On the same line, and moving vertically then 424 else 425 { 426 // This is a 'line' selection 427 selection_.selectLine( thisEndPos.y() ); 428 emit updateLineNumber( thisEndPos.y() ); 429 update(); 430 } 431 selectionCurrentEndPos_ = thisEndPos; 432 433 // Do we need to scroll while extending the selection? 434 QRect visible = viewport()->rect(); 435 if ( visible.contains( mouseEvent->pos() ) ) 436 autoScrollTimer_.stop(); 437 else if ( ! autoScrollTimer_.isActive() ) 438 autoScrollTimer_.start( 100, this ); 439 } 440 } 441 else { 442 considerMouseHovering( mouseEvent->x(), mouseEvent->y() ); 443 } 444 } 445 446 void AbstractLogView::mouseReleaseEvent( QMouseEvent* mouseEvent ) 447 { 448 if ( markingClickInitiated_ ) { 449 markingClickInitiated_ = false; 450 int line = convertCoordToLine( mouseEvent->y() ); 451 if ( line == markingClickLine_ ) { 452 // Invalidate our cache 453 textAreaCache_.invalid_ = true; 454 455 emit markLine( line ); 456 } 457 } 458 else { 459 selectionStarted_ = false; 460 if ( autoScrollTimer_.isActive() ) 461 autoScrollTimer_.stop(); 462 updateGlobalSelection(); 463 } 464 } 465 466 void AbstractLogView::mouseDoubleClickEvent( QMouseEvent* mouseEvent ) 467 { 468 if ( mouseEvent->button() == Qt::LeftButton ) 469 { 470 // Invalidate our cache 471 textAreaCache_.invalid_ = true; 472 473 const QPoint pos = convertCoordToFilePos( mouseEvent->pos() ); 474 selectWordAtPosition( pos ); 475 } 476 477 emit activity(); 478 } 479 480 void AbstractLogView::timerEvent( QTimerEvent* timerEvent ) 481 { 482 if ( timerEvent->timerId() == autoScrollTimer_.timerId() ) { 483 QRect visible = viewport()->rect(); 484 const QPoint globalPos = QCursor::pos(); 485 const QPoint pos = viewport()->mapFromGlobal( globalPos ); 486 QMouseEvent ev( QEvent::MouseMove, pos, globalPos, Qt::LeftButton, 487 Qt::LeftButton, Qt::NoModifier ); 488 mouseMoveEvent( &ev ); 489 int deltaX = qMax( pos.x() - visible.left(), 490 visible.right() - pos.x() ) - visible.width(); 491 int deltaY = qMax( pos.y() - visible.top(), 492 visible.bottom() - pos.y() ) - visible.height(); 493 int delta = qMax( deltaX, deltaY ); 494 495 if ( delta >= 0 ) { 496 if ( delta < 7 ) 497 delta = 7; 498 int timeout = 4900 / ( delta * delta ); 499 autoScrollTimer_.start( timeout, this ); 500 501 if ( deltaX > 0 ) 502 horizontalScrollBar()->triggerAction( 503 pos.x() <visible.center().x() ? 504 QAbstractSlider::SliderSingleStepSub : 505 QAbstractSlider::SliderSingleStepAdd ); 506 507 if ( deltaY > 0 ) 508 verticalScrollBar()->triggerAction( 509 pos.y() <visible.center().y() ? 510 QAbstractSlider::SliderSingleStepSub : 511 QAbstractSlider::SliderSingleStepAdd ); 512 } 513 } 514 QAbstractScrollArea::timerEvent( timerEvent ); 515 } 516 517 void AbstractLogView::keyPressEvent( QKeyEvent* keyEvent ) 518 { 519 LOG(logDEBUG4) << "keyPressEvent received"; 520 521 bool controlModifier = (keyEvent->modifiers() & Qt::ControlModifier) == Qt::ControlModifier; 522 bool shiftModifier = (keyEvent->modifiers() & Qt::ShiftModifier) == Qt::ShiftModifier; 523 bool noModifier = keyEvent->modifiers() == Qt::NoModifier; 524 525 if ( keyEvent->key() == Qt::Key_Left && noModifier ) 526 horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub); 527 else if ( keyEvent->key() == Qt::Key_Right && noModifier ) 528 horizontalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd); 529 else if ( keyEvent->key() == Qt::Key_Home && !controlModifier) 530 jumpToStartOfLine(); 531 else if ( keyEvent->key() == Qt::Key_End && !controlModifier) 532 jumpToRightOfScreen(); 533 else if ( (keyEvent->key() == Qt::Key_PageDown && controlModifier) 534 || (keyEvent->key() == Qt::Key_End && controlModifier) ) 535 { 536 disableFollow(); // duplicate of 'G' action. 537 selection_.selectLine( logData->getNbLine() - 1 ); 538 emit updateLineNumber( logData->getNbLine() - 1 ); 539 jumpToBottom(); 540 } 541 else if ( (keyEvent->key() == Qt::Key_PageUp && controlModifier) 542 || (keyEvent->key() == Qt::Key_Home && controlModifier) ) 543 selectAndDisplayLine( 0 ); 544 else if ( keyEvent->key() == Qt::Key_F3 && !shiftModifier ) 545 searchNext(); // duplicate of 'n' action. 546 else if ( keyEvent->key() == Qt::Key_F3 && shiftModifier ) 547 searchPrevious(); // duplicate of 'N' action. 548 else { 549 const char character = (keyEvent->text())[0].toLatin1(); 550 551 if ( keyEvent->modifiers() == Qt::NoModifier && 552 ( character >= '0' ) && ( character <= '9' ) ) { 553 // Adds the digit to the timed buffer 554 digitsBuffer_.add( character ); 555 } 556 else { 557 switch ( (keyEvent->text())[0].toLatin1() ) { 558 case 'j': 559 { 560 int delta = qMax( 1, digitsBuffer_.content() ); 561 disableFollow(); 562 //verticalScrollBar()->triggerAction( 563 //QScrollBar::SliderSingleStepAdd); 564 moveSelection( delta ); 565 break; 566 } 567 case 'k': 568 { 569 int delta = qMin( -1, - digitsBuffer_.content() ); 570 disableFollow(); 571 //verticalScrollBar()->triggerAction( 572 //QScrollBar::SliderSingleStepSub); 573 moveSelection( delta ); 574 break; 575 } 576 case 'h': 577 horizontalScrollBar()->triggerAction( 578 QScrollBar::SliderSingleStepSub); 579 break; 580 case 'l': 581 horizontalScrollBar()->triggerAction( 582 QScrollBar::SliderSingleStepAdd); 583 break; 584 case '0': 585 jumpToStartOfLine(); 586 break; 587 case '$': 588 jumpToEndOfLine(); 589 break; 590 case 'g': 591 { 592 int newLine = qMax( 0, digitsBuffer_.content() - 1 ); 593 if ( newLine >= logData->getNbLine() ) 594 newLine = logData->getNbLine() - 1; 595 selectAndDisplayLine( newLine ); 596 break; 597 } 598 case 'G': 599 disableFollow(); 600 selection_.selectLine( logData->getNbLine() - 1 ); 601 emit updateLineNumber( logData->getNbLine() - 1 ); 602 emit newSelection( logData->getNbLine() - 1 ); 603 jumpToBottom(); 604 break; 605 case 'n': 606 emit searchNext(); 607 break; 608 case 'N': 609 emit searchPrevious(); 610 break; 611 case '*': 612 // Use the selected 'word' and search forward 613 findNextSelected(); 614 break; 615 case '#': 616 // Use the selected 'word' and search backward 617 findPreviousSelected(); 618 break; 619 default: 620 keyEvent->ignore(); 621 } 622 } 623 } 624 625 if ( keyEvent->isAccepted() ) { 626 emit activity(); 627 } 628 else { 629 // Only pass bare keys to the superclass this is so that 630 // shortcuts such as Ctrl+Alt+Arrow are handled by the parent. 631 LOG(logDEBUG) << std::hex << keyEvent->modifiers(); 632 if ( keyEvent->modifiers() == Qt::NoModifier || 633 keyEvent->modifiers() == Qt::KeypadModifier ) { 634 QAbstractScrollArea::keyPressEvent( keyEvent ); 635 } 636 } 637 } 638 639 void AbstractLogView::wheelEvent( QWheelEvent* wheelEvent ) 640 { 641 emit activity(); 642 643 // LOG(logDEBUG) << "wheelEvent"; 644 645 // This is to handle the case where follow mode is on, but the user 646 // has moved using the scroll bar. We take them back to the bottom. 647 if ( followMode_ ) 648 jumpToBottom(); 649 650 int y_delta = 0; 651 if ( verticalScrollBar()->value() == verticalScrollBar()->maximum() ) { 652 // First see if we need to block the elastic (on Mac) 653 if ( wheelEvent->phase() == Qt::ScrollBegin ) 654 followElasticHook_.hold(); 655 else if ( wheelEvent->phase() == Qt::ScrollEnd ) 656 followElasticHook_.release(); 657 658 auto pixel_delta = wheelEvent->pixelDelta(); 659 660 if ( pixel_delta.isNull() ) { 661 y_delta = wheelEvent->angleDelta().y() / 0.7; 662 } 663 else { 664 y_delta = pixel_delta.y(); 665 } 666 667 // LOG(logDEBUG) << "Elastic " << y_delta; 668 followElasticHook_.move( - y_delta ); 669 } 670 671 // LOG(logDEBUG) << "Length = " << followElasticHook_.length(); 672 if ( followElasticHook_.length() == 0 && !followElasticHook_.isHooked() ) { 673 QAbstractScrollArea::wheelEvent( wheelEvent ); 674 } 675 } 676 677 void AbstractLogView::resizeEvent( QResizeEvent* ) 678 { 679 if ( logData == NULL ) 680 return; 681 682 LOG(logDEBUG) << "resizeEvent received"; 683 684 updateDisplaySize(); 685 } 686 687 bool AbstractLogView::event( QEvent* e ) 688 { 689 LOG(logDEBUG4) << "Event! Type: " << e->type(); 690 691 // Make sure we ignore the gesture events as 692 // they seem to be accepted by default. 693 if ( e->type() == QEvent::Gesture ) { 694 auto gesture_event = dynamic_cast<QGestureEvent*>( e ); 695 if ( gesture_event ) { 696 foreach( QGesture* gesture, gesture_event->gestures() ) { 697 LOG(logDEBUG4) << "Gesture: " << gesture->gestureType(); 698 gesture_event->ignore( gesture ); 699 } 700 701 // Ensure the event is sent up to parents who might care 702 return false; 703 } 704 } 705 706 return QAbstractScrollArea::event( e ); 707 } 708 709 void AbstractLogView::scrollContentsBy( int dx, int dy ) 710 { 711 LOG(logDEBUG) << "scrollContentsBy received " << dy 712 << "position " << verticalScrollBar()->value(); 713 714 int32_t last_top_line = ( logData->getNbLine() - getNbVisibleLines() ); 715 if ( ( last_top_line > 0 ) && verticalScrollBar()->value() > last_top_line ) { 716 // The user is going further than the last line, we need to lock the last line at the bottom 717 LOG(logDEBUG) << "scrollContentsBy beyond!"; 718 firstLine = last_top_line; 719 lastLineAligned = true; 720 } 721 else { 722 firstLine = verticalScrollBar()->value(); 723 lastLineAligned = false; 724 } 725 726 firstCol = (firstCol - dx) > 0 ? firstCol - dx : 0; 727 LineNumber last_line = firstLine + getNbVisibleLines(); 728 729 // Update the overview if we have one 730 if ( overview_ != NULL ) 731 overview_->updateCurrentPosition( firstLine, last_line ); 732 733 // Are we hovering over a new line? 734 const QPoint mouse_pos = mapFromGlobal( QCursor::pos() ); 735 considerMouseHovering( mouse_pos.x(), mouse_pos.y() ); 736 737 // Redraw 738 update(); 739 } 740 741 void AbstractLogView::paintEvent( QPaintEvent* paintEvent ) 742 { 743 const QRect invalidRect = paintEvent->rect(); 744 if ( (invalidRect.isEmpty()) || (logData == NULL) ) 745 return; 746 747 LOG(logDEBUG4) << "paintEvent received, firstLine=" << firstLine 748 << " lastLineAligned=" << lastLineAligned 749 << " rect: " << invalidRect.topLeft().x() << 750 ", " << invalidRect.topLeft().y() << 751 ", " << invalidRect.bottomRight().x() << 752 ", " << invalidRect.bottomRight().y(); 753 754 #ifdef GLOGG_PERF_MEASURE_FPS 755 static uint32_t maxline = logData->getNbLine(); 756 if ( ! perfCounter_.addEvent() && logData->getNbLine() > maxline ) { 757 LOG(logWARNING) << "Redraw per second: " << perfCounter_.readAndReset() 758 << " lines: " << logData->getNbLine(); 759 perfCounter_.addEvent(); 760 maxline = logData->getNbLine(); 761 } 762 #endif 763 764 auto start = std::chrono::system_clock::now(); 765 766 // Can we use our cache? 767 int32_t delta_y = textAreaCache_.first_line_ - firstLine; 768 769 if ( textAreaCache_.invalid_ || ( textAreaCache_.first_column_ != firstCol ) ) { 770 // Force a full redraw 771 delta_y = INT32_MAX; 772 } 773 774 if ( delta_y != 0 ) { 775 // Full or partial redraw 776 drawTextArea( &textAreaCache_.pixmap_, delta_y ); 777 778 textAreaCache_.invalid_ = false; 779 textAreaCache_.first_line_ = firstLine; 780 textAreaCache_.first_column_ = firstCol; 781 782 LOG(logDEBUG) << "End of writing " << 783 std::chrono::duration_cast<std::chrono::microseconds> 784 ( std::chrono::system_clock::now() - start ).count(); 785 } 786 else { 787 // Use the cache as is: nothing to do! 788 } 789 790 // Height including the potentially invisible last line 791 const int whole_height = getNbVisibleLines() * charHeight_; 792 // Height in pixels of the "pull to follow" bottom bar. 793 int pullToFollowHeight = mapPullToFollowLength( followElasticHook_.length() ) 794 + ( followElasticHook_.isHooked() ? 795 ( whole_height - viewport()->height() ) + PULL_TO_FOLLOW_HOOKED_HEIGHT : 0 ); 796 797 if ( pullToFollowHeight 798 && ( pullToFollowCache_.nb_columns_ != getNbVisibleCols() ) ) { 799 LOG(logDEBUG) << "Drawing pull to follow bar"; 800 pullToFollowCache_.pixmap_ = drawPullToFollowBar( 801 viewport()->width(), viewport()->devicePixelRatio() ); 802 pullToFollowCache_.nb_columns_ = getNbVisibleCols(); 803 } 804 805 QPainter devicePainter( viewport() ); 806 int drawingTopPosition = - pullToFollowHeight; 807 int drawingPullToFollowTopPosition = drawingTopPosition + whole_height; 808 809 // This is to cover the special case where there is less than a screenful 810 // worth of data, we want to see the document from the top, rather than 811 // pushing the first couple of lines above the viewport. 812 if ( followElasticHook_.isHooked() && ( logData->getNbLine() < getNbVisibleLines() ) ) { 813 drawingTopOffset_ = 0; 814 drawingTopPosition += ( whole_height - viewport()->height() ) + PULL_TO_FOLLOW_HOOKED_HEIGHT; 815 drawingPullToFollowTopPosition = drawingTopPosition + viewport()->height() - PULL_TO_FOLLOW_HOOKED_HEIGHT; 816 } 817 // This is the case where the user is on the 'extra' slot at the end 818 // and is aligned on the last line (but no elastic shown) 819 else if ( lastLineAligned && !followElasticHook_.isHooked() ) { 820 drawingTopOffset_ = - ( whole_height - viewport()->height() ); 821 drawingTopPosition += drawingTopOffset_; 822 drawingPullToFollowTopPosition = drawingTopPosition + whole_height; 823 } 824 else { 825 drawingTopOffset_ = - pullToFollowHeight; 826 } 827 828 devicePainter.drawPixmap( 0, drawingTopPosition, textAreaCache_.pixmap_ ); 829 830 // Draw the "pull to follow" zone if needed 831 if ( pullToFollowHeight ) { 832 devicePainter.drawPixmap( 0, 833 drawingPullToFollowTopPosition, 834 pullToFollowCache_.pixmap_ ); 835 } 836 837 LOG(logDEBUG) << "End of repaint " << 838 std::chrono::duration_cast<std::chrono::microseconds> 839 ( std::chrono::system_clock::now() - start ).count(); 840 } 841 842 // These two functions are virtual and this implementation is clearly 843 // only valid for a non-filtered display. 844 // We count on the 'filtered' derived classes to override them. 845 qint64 AbstractLogView::displayLineNumber( int lineNumber ) const 846 { 847 return lineNumber + 1; // show a 1-based index 848 } 849 850 qint64 AbstractLogView::maxDisplayLineNumber() const 851 { 852 return logData->getNbLine(); 853 } 854 855 void AbstractLogView::setOverview( Overview* overview, 856 OverviewWidget* overview_widget ) 857 { 858 overview_ = overview; 859 overviewWidget_ = overview_widget; 860 861 if ( overviewWidget_ ) { 862 connect( overviewWidget_, SIGNAL( lineClicked ( int ) ), 863 this, SIGNAL( followDisabled() ) ); 864 connect( overviewWidget_, SIGNAL( lineClicked ( int ) ), 865 this, SLOT( jumpToLine( int ) ) ); 866 } 867 refreshOverview(); 868 } 869 870 LineNumber AbstractLogView::getViewPosition() const 871 { 872 LineNumber line; 873 874 qint64 m_line = selection_.selectedLine(); 875 if ( m_line >= 0 ) { 876 line = m_line; 877 } 878 else { 879 // Middle of the view 880 line = firstLine + getNbVisibleLines() / 2; 881 } 882 883 return line; 884 } 885 886 void AbstractLogView::searchUsingFunction( 887 qint64 (QuickFind::*search_function)() ) 888 { 889 disableFollow(); 890 891 int line = (quickFind_.*search_function)(); 892 if ( line >= 0 ) { 893 LOG(logDEBUG) << "search " << line; 894 displayLine( line ); 895 emit updateLineNumber( line ); 896 } 897 } 898 899 void AbstractLogView::searchForward() 900 { 901 searchUsingFunction( &QuickFind::searchForward ); 902 } 903 904 void AbstractLogView::searchBackward() 905 { 906 searchUsingFunction( &QuickFind::searchBackward ); 907 } 908 909 void AbstractLogView::incrementallySearchForward() 910 { 911 searchUsingFunction( &QuickFind::incrementallySearchForward ); 912 } 913 914 void AbstractLogView::incrementallySearchBackward() 915 { 916 searchUsingFunction( &QuickFind::incrementallySearchBackward ); 917 } 918 919 void AbstractLogView::incrementalSearchAbort() 920 { 921 quickFind_.incrementalSearchAbort(); 922 emit changeQuickFind( 923 "", 924 QuickFindMux::Forward ); 925 } 926 927 void AbstractLogView::incrementalSearchStop() 928 { 929 quickFind_.incrementalSearchStop(); 930 } 931 932 void AbstractLogView::followSet( bool checked ) 933 { 934 followMode_ = checked; 935 followElasticHook_.hook( checked ); 936 update(); 937 if ( checked ) 938 jumpToBottom(); 939 } 940 941 void AbstractLogView::refreshOverview() 942 { 943 assert( overviewWidget_ ); 944 945 // Create space for the Overview if needed 946 if ( ( getOverview() != NULL ) && getOverview()->isVisible() ) { 947 setViewportMargins( 0, 0, OVERVIEW_WIDTH, 0 ); 948 overviewWidget_->show(); 949 } 950 else { 951 setViewportMargins( 0, 0, 0, 0 ); 952 overviewWidget_->hide(); 953 } 954 } 955 956 // Reset the QuickFind when the pattern is changed. 957 void AbstractLogView::handlePatternUpdated() 958 { 959 LOG(logDEBUG) << "AbstractLogView::handlePatternUpdated()"; 960 961 quickFind_.resetLimits(); 962 update(); 963 } 964 965 // OR the current with the current search expression 966 void AbstractLogView::addToSearch() 967 { 968 if ( selection_.isPortion() ) { 969 LOG(logDEBUG) << "AbstractLogView::addToSearch()"; 970 emit addToSearch( selection_.getSelectedText( logData ) ); 971 } 972 else { 973 LOG(logERROR) << "AbstractLogView::addToSearch called for a wrong type of selection"; 974 } 975 } 976 977 // Find next occurence of the selected text (*) 978 void AbstractLogView::findNextSelected() 979 { 980 // Use the selected 'word' and search forward 981 if ( selection_.isPortion() ) { 982 emit changeQuickFind( 983 selection_.getSelectedText( logData ), 984 QuickFindMux::Forward ); 985 emit searchNext(); 986 } 987 } 988 989 // Find next previous of the selected text (#) 990 void AbstractLogView::findPreviousSelected() 991 { 992 if ( selection_.isPortion() ) { 993 emit changeQuickFind( 994 selection_.getSelectedText( logData ), 995 QuickFindMux::Backward ); 996 emit searchNext(); 997 } 998 } 999 1000 // Copy the selection to the clipboard 1001 void AbstractLogView::copy() 1002 { 1003 static QClipboard* clipboard = QApplication::clipboard(); 1004 1005 clipboard->setText( selection_.getSelectedText( logData ) ); 1006 } 1007 1008 // 1009 // Public functions 1010 // 1011 1012 void AbstractLogView::updateData() 1013 { 1014 LOG(logDEBUG) << "AbstractLogView::updateData"; 1015 1016 // Check the top Line is within range 1017 if ( firstLine >= logData->getNbLine() ) { 1018 firstLine = 0; 1019 firstCol = 0; 1020 verticalScrollBar()->setValue( 0 ); 1021 horizontalScrollBar()->setValue( 0 ); 1022 } 1023 1024 // Crop selection if it become out of range 1025 selection_.crop( logData->getNbLine() - 1 ); 1026 1027 // Adapt the scroll bars to the new content 1028 updateScrollBars(); 1029 1030 // Calculate the index of the last line shown 1031 LineNumber last_line = std::min( static_cast<int64_t>( logData->getNbLine() ), 1032 static_cast<int64_t>( firstLine + getNbVisibleLines() ) ); 1033 1034 // Reset the QuickFind in case we have new stuff to search into 1035 quickFind_.resetLimits(); 1036 1037 if ( followMode_ ) 1038 jumpToBottom(); 1039 1040 // Update the overview if we have one 1041 if ( overview_ != NULL ) 1042 overview_->updateCurrentPosition( firstLine, last_line ); 1043 1044 // Invalidate our cache 1045 textAreaCache_.invalid_ = true; 1046 1047 // Repaint! 1048 update(); 1049 } 1050 1051 void AbstractLogView::updateDisplaySize() 1052 { 1053 // Font is assumed to be mono-space (is restricted by options dialog) 1054 QFontMetrics fm = fontMetrics(); 1055 charHeight_ = fm.height(); 1056 // For some reason on Qt 4.8.2 for Win, maxWidth() is wrong but the 1057 // following give the right result, not sure why: 1058 charWidth_ = fm.width( QChar('a') ); 1059 1060 // Update the scroll bars 1061 updateScrollBars(); 1062 verticalScrollBar()->setPageStep( getNbVisibleLines() ); 1063 1064 if ( followMode_ ) 1065 jumpToBottom(); 1066 1067 LOG(logDEBUG) << "viewport.width()=" << viewport()->width(); 1068 LOG(logDEBUG) << "viewport.height()=" << viewport()->height(); 1069 LOG(logDEBUG) << "width()=" << width(); 1070 LOG(logDEBUG) << "height()=" << height(); 1071 1072 if ( overviewWidget_ ) 1073 overviewWidget_->setGeometry( viewport()->width() + 2, 1, 1074 OVERVIEW_WIDTH - 1, viewport()->height() ); 1075 1076 // Our text area cache is now invalid 1077 textAreaCache_.invalid_ = true; 1078 textAreaCache_.pixmap_ = QPixmap { 1079 viewport()->width() * viewport()->devicePixelRatio(), 1080 static_cast<int32_t>( getNbVisibleLines() ) * charHeight_ * viewport()->devicePixelRatio() }; 1081 textAreaCache_.pixmap_.setDevicePixelRatio( viewport()->devicePixelRatio() ); 1082 } 1083 1084 int AbstractLogView::getTopLine() const 1085 { 1086 return firstLine; 1087 } 1088 1089 QString AbstractLogView::getSelection() const 1090 { 1091 return selection_.getSelectedText( logData ); 1092 } 1093 1094 void AbstractLogView::selectAll() 1095 { 1096 selection_.selectRange( 0, logData->getNbLine() - 1 ); 1097 textAreaCache_.invalid_ = true; 1098 update(); 1099 } 1100 1101 void AbstractLogView::selectAndDisplayLine( int line ) 1102 { 1103 disableFollow(); 1104 selection_.selectLine( line ); 1105 displayLine( line ); 1106 emit updateLineNumber( line ); 1107 emit newSelection( line ); 1108 } 1109 1110 // The difference between this function and displayLine() is quite 1111 // subtle: this one always jump, even if the line passed is visible. 1112 void AbstractLogView::jumpToLine( int line ) 1113 { 1114 // Put the selected line in the middle if possible 1115 int newTopLine = line - ( getNbVisibleLines() / 2 ); 1116 if ( newTopLine < 0 ) 1117 newTopLine = 0; 1118 1119 // This will also trigger a scrollContents event 1120 verticalScrollBar()->setValue( newTopLine ); 1121 } 1122 1123 void AbstractLogView::setLineNumbersVisible( bool lineNumbersVisible ) 1124 { 1125 lineNumbersVisible_ = lineNumbersVisible; 1126 } 1127 1128 void AbstractLogView::forceRefresh() 1129 { 1130 // Invalidate our cache 1131 textAreaCache_.invalid_ = true; 1132 } 1133 1134 // 1135 // Private functions 1136 // 1137 1138 // Returns the number of lines visible in the viewport 1139 LineNumber AbstractLogView::getNbVisibleLines() const 1140 { 1141 return static_cast<LineNumber>( viewport()->height() / charHeight_ + 1 ); 1142 } 1143 1144 // Returns the number of columns visible in the viewport 1145 int AbstractLogView::getNbVisibleCols() const 1146 { 1147 return ( viewport()->width() - leftMarginPx_ ) / charWidth_ + 1; 1148 } 1149 1150 // Converts the mouse x, y coordinates to the line number in the file 1151 int AbstractLogView::convertCoordToLine(int yPos) const 1152 { 1153 int line = firstLine + ( yPos - drawingTopOffset_ ) / charHeight_; 1154 1155 return line; 1156 } 1157 1158 // Converts the mouse x, y coordinates to the char coordinates (in the file) 1159 // This function ensure the pos exists in the file. 1160 QPoint AbstractLogView::convertCoordToFilePos( const QPoint& pos ) const 1161 { 1162 int line = convertCoordToLine( pos.y() ); 1163 if ( line >= logData->getNbLine() ) 1164 line = logData->getNbLine() - 1; 1165 if ( line < 0 ) 1166 line = 0; 1167 1168 // Determine column in screen space and convert it to file space 1169 int column = firstCol + ( pos.x() - leftMarginPx_ ) / charWidth_; 1170 1171 QString this_line = logData->getExpandedLineString( line ); 1172 const int length = this_line.length(); 1173 1174 if ( column >= length ) 1175 column = length - 1; 1176 if ( column < 0 ) 1177 column = 0; 1178 1179 LOG(logDEBUG4) << "AbstractLogView::convertCoordToFilePos col=" 1180 << column << " line=" << line; 1181 QPoint point( column, line ); 1182 1183 return point; 1184 } 1185 1186 // Makes the widget adjust itself to display the passed line. 1187 // Doing so, it will throw itself a scrollContents event. 1188 void AbstractLogView::displayLine( LineNumber line ) 1189 { 1190 // If the line is already the screen 1191 if ( ( line >= firstLine ) && 1192 ( line < ( firstLine + getNbVisibleLines() ) ) ) { 1193 // Invalidate our cache 1194 textAreaCache_.invalid_ = true; 1195 1196 // ... don't scroll and just repaint 1197 update(); 1198 } else { 1199 jumpToLine( line ); 1200 } 1201 } 1202 1203 // Move the selection up and down by the passed number of lines 1204 void AbstractLogView::moveSelection( int delta ) 1205 { 1206 LOG(logDEBUG) << "AbstractLogView::moveSelection delta=" << delta; 1207 1208 QList<int> selection = selection_.getLines(); 1209 int new_line; 1210 1211 // If nothing is selected, do as if line -1 was. 1212 if ( selection.isEmpty() ) 1213 selection.append( -1 ); 1214 1215 if ( delta < 0 ) 1216 new_line = selection.first() + delta; 1217 else 1218 new_line = selection.last() + delta; 1219 1220 if ( new_line < 0 ) 1221 new_line = 0; 1222 else if ( new_line >= logData->getNbLine() ) 1223 new_line = logData->getNbLine() - 1; 1224 1225 // Select and display the new line 1226 selection_.selectLine( new_line ); 1227 displayLine( new_line ); 1228 emit updateLineNumber( new_line ); 1229 emit newSelection( new_line ); 1230 } 1231 1232 // Make the start of the lines visible 1233 void AbstractLogView::jumpToStartOfLine() 1234 { 1235 horizontalScrollBar()->setValue( 0 ); 1236 } 1237 1238 // Make the end of the lines in the selection visible 1239 void AbstractLogView::jumpToEndOfLine() 1240 { 1241 QList<int> selection = selection_.getLines(); 1242 1243 // Search the longest line in the selection 1244 int max_length = 0; 1245 foreach ( int line, selection ) { 1246 int length = logData->getLineLength( line ); 1247 if ( length > max_length ) 1248 max_length = length; 1249 } 1250 1251 horizontalScrollBar()->setValue( max_length - getNbVisibleCols() ); 1252 } 1253 1254 // Make the end of the lines on the screen visible 1255 void AbstractLogView::jumpToRightOfScreen() 1256 { 1257 QList<int> selection = selection_.getLines(); 1258 1259 // Search the longest line on screen 1260 int max_length = 0; 1261 for ( auto i = firstLine; i <= ( firstLine + getNbVisibleLines() ); i++ ) { 1262 int length = logData->getLineLength( i ); 1263 if ( length > max_length ) 1264 max_length = length; 1265 } 1266 1267 horizontalScrollBar()->setValue( max_length - getNbVisibleCols() ); 1268 } 1269 1270 // Jump to the first line 1271 void AbstractLogView::jumpToTop() 1272 { 1273 // This will also trigger a scrollContents event 1274 verticalScrollBar()->setValue( 0 ); 1275 update(); // in case the screen hasn't moved 1276 } 1277 1278 // Jump to the last line 1279 void AbstractLogView::jumpToBottom() 1280 { 1281 const int new_top_line = 1282 qMax( logData->getNbLine() - getNbVisibleLines() + 1, 0LL ); 1283 1284 // This will also trigger a scrollContents event 1285 verticalScrollBar()->setValue( new_top_line ); 1286 update(); // in case the screen hasn't moved 1287 } 1288 1289 // Returns whether the character passed is a 'word' character 1290 inline bool AbstractLogView::isCharWord( char c ) 1291 { 1292 if ( ( ( c >= 'A' ) && ( c <= 'Z' ) ) || 1293 ( ( c >= 'a' ) && ( c <= 'z' ) ) || 1294 ( ( c >= '0' ) && ( c <= '9' ) ) || 1295 ( ( c == '_' ) ) ) 1296 return true; 1297 else 1298 return false; 1299 } 1300 1301 // Select the word under the given position 1302 void AbstractLogView::selectWordAtPosition( const QPoint& pos ) 1303 { 1304 const int x = pos.x(); 1305 const QString line = logData->getExpandedLineString( pos.y() ); 1306 1307 if ( isCharWord( line[x].toLatin1() ) ) { 1308 // Search backward for the first character in the word 1309 int currentPos = x; 1310 for ( ; currentPos > 0; currentPos-- ) 1311 if ( ! isCharWord( line[currentPos].toLatin1() ) ) 1312 break; 1313 // Exclude the first char of the line if needed 1314 if ( ! isCharWord( line[currentPos].toLatin1() ) ) 1315 currentPos++; 1316 int start = currentPos; 1317 1318 // Now search for the end 1319 currentPos = x; 1320 for ( ; currentPos < line.length() - 1; currentPos++ ) 1321 if ( ! isCharWord( line[currentPos].toLatin1() ) ) 1322 break; 1323 // Exclude the last char of the line if needed 1324 if ( ! isCharWord( line[currentPos].toLatin1() ) ) 1325 currentPos--; 1326 int end = currentPos; 1327 1328 selection_.selectPortion( pos.y(), start, end ); 1329 updateGlobalSelection(); 1330 update(); 1331 } 1332 } 1333 1334 // Update the system global (middle click) selection (X11 only) 1335 void AbstractLogView::updateGlobalSelection() 1336 { 1337 static QClipboard* const clipboard = QApplication::clipboard(); 1338 1339 // Updating it only for "non-trivial" (range or portion) selections 1340 if ( ! selection_.isSingleLine() ) 1341 clipboard->setText( selection_.getSelectedText( logData ), 1342 QClipboard::Selection ); 1343 } 1344 1345 // Create the pop-up menu 1346 void AbstractLogView::createMenu() 1347 { 1348 copyAction_ = new QAction( tr("&Copy"), this ); 1349 // No text as this action title depends on the type of selection 1350 connect( copyAction_, SIGNAL(triggered()), this, SLOT(copy()) ); 1351 1352 // For '#' and '*', shortcuts doesn't seem to work but 1353 // at least it displays them in the menu, we manually handle those keys 1354 // as keys event anyway (in keyPressEvent). 1355 findNextAction_ = new QAction(tr("Find &next"), this); 1356 findNextAction_->setShortcut( Qt::Key_Asterisk ); 1357 findNextAction_->setStatusTip( tr("Find the next occurence") ); 1358 connect( findNextAction_, SIGNAL(triggered()), 1359 this, SLOT( findNextSelected() ) ); 1360 1361 findPreviousAction_ = new QAction( tr("Find &previous"), this ); 1362 findPreviousAction_->setShortcut( tr("#") ); 1363 findPreviousAction_->setStatusTip( tr("Find the previous occurence") ); 1364 connect( findPreviousAction_, SIGNAL(triggered()), 1365 this, SLOT( findPreviousSelected() ) ); 1366 1367 addToSearchAction_ = new QAction( tr("&Add to search"), this ); 1368 addToSearchAction_->setStatusTip( 1369 tr("Add the selection to the current search") ); 1370 connect( addToSearchAction_, SIGNAL( triggered() ), 1371 this, SLOT( addToSearch() ) ); 1372 1373 popupMenu_ = new QMenu( this ); 1374 popupMenu_->addAction( copyAction_ ); 1375 popupMenu_->addSeparator(); 1376 popupMenu_->addAction( findNextAction_ ); 1377 popupMenu_->addAction( findPreviousAction_ ); 1378 popupMenu_->addAction( addToSearchAction_ ); 1379 } 1380 1381 void AbstractLogView::considerMouseHovering( int x_pos, int y_pos ) 1382 { 1383 int line = convertCoordToLine( y_pos ); 1384 if ( ( x_pos < leftMarginPx_ ) 1385 && ( line >= 0 ) 1386 && ( line < logData->getNbLine() ) ) { 1387 // Mouse moved in the margin, send event up 1388 // (possibly to highlight the overview) 1389 if ( line != lastHoveredLine_ ) { 1390 LOG(logDEBUG) << "Mouse moved in margin line: " << line; 1391 emit mouseHoveredOverLine( line ); 1392 lastHoveredLine_ = line; 1393 } 1394 } 1395 else { 1396 if ( lastHoveredLine_ != -1 ) { 1397 emit mouseLeftHoveringZone(); 1398 lastHoveredLine_ = -1; 1399 } 1400 } 1401 } 1402 1403 void AbstractLogView::updateScrollBars() 1404 { 1405 verticalScrollBar()->setRange( 0, std::max( 0LL, 1406 logData->getNbLine() - getNbVisibleLines() + 1 ) ); 1407 1408 const int hScrollMaxValue = std::max( 0, 1409 logData->getMaxLength() - getNbVisibleCols() + 1 ); 1410 horizontalScrollBar()->setRange( 0, hScrollMaxValue ); 1411 } 1412 1413 void AbstractLogView::drawTextArea( QPaintDevice* paint_device, int32_t delta_y ) 1414 { 1415 // LOG( logDEBUG ) << "devicePixelRatio: " << viewport()->devicePixelRatio(); 1416 // LOG( logDEBUG ) << "viewport size: " << viewport()->size().width(); 1417 // LOG( logDEBUG ) << "pixmap size: " << textPixmap.width(); 1418 // Repaint the viewport 1419 QPainter painter( paint_device ); 1420 // LOG( logDEBUG ) << "font: " << viewport()->font().family().toStdString(); 1421 // LOG( logDEBUG ) << "font painter: " << painter.font().family().toStdString(); 1422 1423 painter.setFont( this->font() ); 1424 1425 const int fontHeight = charHeight_; 1426 const int fontAscent = painter.fontMetrics().ascent(); 1427 const int nbCols = getNbVisibleCols(); 1428 const int paintDeviceHeight = paint_device->height() / viewport()->devicePixelRatio(); 1429 const int paintDeviceWidth = paint_device->width() / viewport()->devicePixelRatio(); 1430 const QPalette& palette = viewport()->palette(); 1431 std::shared_ptr<const FilterSet> filterSet = 1432 Persistent<FilterSet>( "filterSet" ); 1433 QColor foreColor, backColor; 1434 1435 static const QBrush normalBulletBrush = QBrush( Qt::white ); 1436 static const QBrush matchBulletBrush = QBrush( Qt::red ); 1437 static const QBrush markBrush = QBrush( "dodgerblue" ); 1438 1439 static const int SEPARATOR_WIDTH = 1; 1440 static const qreal BULLET_AREA_WIDTH = 11; 1441 static const int CONTENT_MARGIN_WIDTH = 1; 1442 static const int LINE_NUMBER_PADDING = 3; 1443 1444 // First check the lines to be drawn are within range (might not be the case if 1445 // the file has just changed) 1446 const int64_t lines_in_file = logData->getNbLine(); 1447 1448 if ( firstLine > lines_in_file ) 1449 firstLine = lines_in_file ? lines_in_file - 1 : 0; 1450 1451 const int64_t nbLines = std::min( 1452 static_cast<int64_t>( getNbVisibleLines() ), lines_in_file - firstLine ); 1453 1454 const int bottomOfTextPx = nbLines * fontHeight; 1455 1456 LOG(logDEBUG) << "drawing lines from " << firstLine << " (" << nbLines << " lines)"; 1457 LOG(logDEBUG) << "bottomOfTextPx: " << bottomOfTextPx; 1458 LOG(logDEBUG) << "Height: " << paintDeviceHeight; 1459 1460 // Lines to write 1461 const QStringList lines = logData->getExpandedLines( firstLine, nbLines ); 1462 1463 // First draw the bullet left margin 1464 painter.setPen(palette.color(QPalette::Text)); 1465 painter.fillRect( 0, 0, 1466 BULLET_AREA_WIDTH, paintDeviceHeight, 1467 Qt::darkGray ); 1468 1469 // Column at which the content should start (pixels) 1470 qreal contentStartPosX = BULLET_AREA_WIDTH + SEPARATOR_WIDTH; 1471 1472 // This is also the bullet zone width, used for marking clicks 1473 bulletZoneWidthPx_ = contentStartPosX; 1474 1475 // Update the length of line numbers 1476 const int nbDigitsInLineNumber = countDigits( maxDisplayLineNumber() ); 1477 1478 // Draw the line numbers area 1479 int lineNumberAreaStartX = 0; 1480 if ( lineNumbersVisible_ ) { 1481 int lineNumberWidth = charWidth_ * nbDigitsInLineNumber; 1482 int lineNumberAreaWidth = 1483 2 * LINE_NUMBER_PADDING + lineNumberWidth; 1484 lineNumberAreaStartX = contentStartPosX; 1485 1486 painter.setPen(palette.color(QPalette::Text)); 1487 /* Not sure if it looks good... 1488 painter.drawLine( contentStartPosX + lineNumberAreaWidth, 1489 0, 1490 contentStartPosX + lineNumberAreaWidth, 1491 viewport()->height() ); 1492 */ 1493 painter.fillRect( contentStartPosX - SEPARATOR_WIDTH, 0, 1494 lineNumberAreaWidth + SEPARATOR_WIDTH, paintDeviceHeight, 1495 Qt::lightGray ); 1496 1497 // Update for drawing the actual text 1498 contentStartPosX += lineNumberAreaWidth; 1499 } 1500 else { 1501 painter.fillRect( contentStartPosX - SEPARATOR_WIDTH, 0, 1502 SEPARATOR_WIDTH + 1, paintDeviceHeight, 1503 Qt::lightGray ); 1504 // contentStartPosX += SEPARATOR_WIDTH; 1505 } 1506 1507 painter.drawLine( BULLET_AREA_WIDTH, 0, 1508 BULLET_AREA_WIDTH, paintDeviceHeight - 1 ); 1509 1510 // This is the total width of the 'margin' (including line number if any) 1511 // used for mouse calculation etc... 1512 leftMarginPx_ = contentStartPosX + SEPARATOR_WIDTH; 1513 1514 // Then draw each line 1515 for (int i = 0; i < nbLines; i++) { 1516 const LineNumber line_index = i + firstLine; 1517 1518 // Position in pixel of the base line of the line to print 1519 const int yPos = i * fontHeight; 1520 const int xPos = contentStartPosX + CONTENT_MARGIN_WIDTH; 1521 1522 // string to print, cut to fit the length and position of the view 1523 const QString line = lines[i]; 1524 const QString cutLine = line.mid( firstCol, nbCols ); 1525 1526 if ( selection_.isLineSelected( line_index ) ) { 1527 // Reverse the selected line 1528 foreColor = palette.color( QPalette::HighlightedText ); 1529 backColor = palette.color( QPalette::Highlight ); 1530 painter.setPen(palette.color(QPalette::Text)); 1531 } 1532 else if ( filterSet->matchLine( logData->getLineString( line_index ), 1533 &foreColor, &backColor ) ) { 1534 // Apply a filter to the line 1535 } 1536 else { 1537 // Use the default colors 1538 foreColor = palette.color( QPalette::Text ); 1539 backColor = palette.color( QPalette::Base ); 1540 } 1541 1542 // Is there something selected in the line? 1543 int sel_start, sel_end; 1544 bool isSelection = 1545 selection_.getPortionForLine( line_index, &sel_start, &sel_end ); 1546 // Has the line got elements to be highlighted 1547 QList<QuickFindMatch> qfMatchList; 1548 bool isMatch = 1549 quickFindPattern_->matchLine( line, qfMatchList ); 1550 1551 if ( isSelection || isMatch ) { 1552 // We use the LineDrawer and its chunks because the 1553 // line has to be somehow highlighted 1554 LineDrawer lineDrawer( backColor ); 1555 1556 // First we create a list of chunks with the highlights 1557 QList<LineChunk> chunkList; 1558 int column = 0; // Current column in line space 1559 foreach( const QuickFindMatch match, qfMatchList ) { 1560 int start = match.startColumn() - firstCol; 1561 int end = start + match.length(); 1562 // Ignore matches that are *completely* outside view area 1563 if ( ( start < 0 && end < 0 ) || start >= nbCols ) 1564 continue; 1565 if ( start > column ) 1566 chunkList << LineChunk( column, start - 1, LineChunk::Normal ); 1567 column = qMin( start + match.length() - 1, nbCols ); 1568 chunkList << LineChunk( qMax( start, 0 ), column, 1569 LineChunk::Highlighted ); 1570 column++; 1571 } 1572 if ( column <= cutLine.length() - 1 ) 1573 chunkList << LineChunk( column, cutLine.length() - 1, LineChunk::Normal ); 1574 1575 // Then we add the selection if needed 1576 QList<LineChunk> newChunkList; 1577 if ( isSelection ) { 1578 sel_start -= firstCol; // coord in line space 1579 sel_end -= firstCol; 1580 1581 foreach ( const LineChunk chunk, chunkList ) { 1582 newChunkList << chunk.select( sel_start, sel_end ); 1583 } 1584 } 1585 else 1586 newChunkList = chunkList; 1587 1588 foreach ( const LineChunk chunk, newChunkList ) { 1589 // Select the colours 1590 QColor fore; 1591 QColor back; 1592 switch ( chunk.type() ) { 1593 case LineChunk::Normal: 1594 fore = foreColor; 1595 back = backColor; 1596 break; 1597 case LineChunk::Highlighted: 1598 fore = QColor( "black" ); 1599 back = QColor( "yellow" ); 1600 // fore = highlightForeColor; 1601 // back = highlightBackColor; 1602 break; 1603 case LineChunk::Selected: 1604 fore = palette.color( QPalette::HighlightedText ), 1605 back = palette.color( QPalette::Highlight ); 1606 break; 1607 } 1608 lineDrawer.addChunk ( chunk, fore, back ); 1609 } 1610 1611 lineDrawer.draw( painter, xPos, yPos, 1612 viewport()->width(), cutLine, 1613 CONTENT_MARGIN_WIDTH ); 1614 } 1615 else { 1616 // Nothing to be highlighted, we print the whole line! 1617 painter.fillRect( xPos - CONTENT_MARGIN_WIDTH, yPos, 1618 viewport()->width(), fontHeight, backColor ); 1619 // (the rectangle is extended on the left to cover the small 1620 // margin, it looks better (LineDrawer does the same) ) 1621 painter.setPen( foreColor ); 1622 painter.drawText( xPos, yPos + fontAscent, cutLine ); 1623 } 1624 1625 // Then draw the bullet 1626 painter.setPen( palette.color( QPalette::Text ) ); 1627 const qreal circleSize = 3; 1628 const qreal arrowHeight = 4; 1629 const qreal middleXLine = BULLET_AREA_WIDTH / 2; 1630 const qreal middleYLine = yPos + (fontHeight / 2); 1631 1632 const LineType line_type = lineType( line_index ); 1633 if ( line_type == Marked ) { 1634 // A pretty arrow if the line is marked 1635 const QPointF points[7] = { 1636 QPointF(1, middleYLine - 2), 1637 QPointF(middleXLine, middleYLine - 2), 1638 QPointF(middleXLine, middleYLine - arrowHeight), 1639 QPointF(BULLET_AREA_WIDTH - 1, middleYLine), 1640 QPointF(middleXLine, middleYLine + arrowHeight), 1641 QPointF(middleXLine, middleYLine + 2), 1642 QPointF(1, middleYLine + 2 ), 1643 }; 1644 1645 painter.setBrush( markBrush ); 1646 painter.drawPolygon( points, 7 ); 1647 } 1648 else { 1649 // For pretty circles 1650 painter.setRenderHint( QPainter::Antialiasing ); 1651 1652 if ( lineType( line_index ) == Match ) 1653 painter.setBrush( matchBulletBrush ); 1654 else 1655 painter.setBrush( normalBulletBrush ); 1656 painter.drawEllipse( middleXLine - circleSize, 1657 middleYLine - circleSize, 1658 circleSize * 2, circleSize * 2 ); 1659 } 1660 1661 // Draw the line number 1662 if ( lineNumbersVisible_ ) { 1663 static const QString lineNumberFormat( "%1" ); 1664 const QString& lineNumberStr = 1665 lineNumberFormat.arg( displayLineNumber( line_index ), 1666 nbDigitsInLineNumber ); 1667 painter.setPen( palette.color( QPalette::Text ) ); 1668 painter.drawText( lineNumberAreaStartX + LINE_NUMBER_PADDING, 1669 yPos + fontAscent, lineNumberStr ); 1670 } 1671 } // For each line 1672 1673 if ( bottomOfTextPx < paintDeviceHeight ) { 1674 // The lines don't cover the whole device 1675 painter.fillRect( contentStartPosX, bottomOfTextPx, 1676 paintDeviceWidth - contentStartPosX, 1677 paintDeviceHeight, palette.color( QPalette::Window ) ); 1678 } 1679 } 1680 1681 // Draw the "pull to follow" bar and return a pixmap. 1682 // The width is passed in "logic" pixels. 1683 QPixmap AbstractLogView::drawPullToFollowBar( int width, float pixel_ratio ) 1684 { 1685 static constexpr int barWidth = 40; 1686 QPixmap pixmap ( static_cast<float>( width ) * pixel_ratio, barWidth * 6.0 ); 1687 pixmap.setDevicePixelRatio( pixel_ratio ); 1688 pixmap.fill( this->palette().color( this->backgroundRole() ) ); 1689 const int nbBars = width / (barWidth * 2) + 1; 1690 1691 QPainter painter( &pixmap ); 1692 painter.setPen( QPen( QColor( 0, 0, 0, 0 ) ) ); 1693 painter.setBrush( QBrush( QColor( "lightyellow" ) ) ); 1694 1695 for ( int i = 0; i < nbBars; ++i ) { 1696 QPoint points[4] = { 1697 { (i*2+1)*barWidth, 0 }, 1698 { 0, (i*2+1)*barWidth }, 1699 { 0, (i+1)*2*barWidth }, 1700 { (i+1)*2*barWidth, 0 } 1701 }; 1702 painter.drawConvexPolygon( points, 4 ); 1703 } 1704 1705 return pixmap; 1706 } 1707 1708 void AbstractLogView::disableFollow() 1709 { 1710 emit followModeChanged( false ); 1711 followElasticHook_.hook( false ); 1712 } 1713 1714 namespace { 1715 1716 // Convert the length of the pull to follow bar to pixels 1717 int mapPullToFollowLength( int length ) 1718 { 1719 return length / 14; 1720 } 1721 1722 }; 1723