pageview.cpp 38.4 KB
Newer Older
1
/***************************************************************************
2
 *   Copyright (C) 2004 by Enrico Ros <eros.kde@email.it>                  *
3
 *   Copyright (C) 2004 by Albert Astals Cid <tsdgeos@terra.es>            *
4 5 6 7 8 9 10 11
 *                                                                         *
 *   With portions of code from kpdf_pagewidget.cc by:                     *
 *     Copyright (C) 2002 by Wilco Greven <greven@kde.org>                 *
 *     Copyright (C) 2003 by Christophe Devriese                           *
 *                           <Christophe.Devriese@student.kuleuven.ac.be>  *
 *     Copyright (C) 2003 by Laurent Montel <montel@kde.org>               *
 *     Copyright (C) 2003 by Dirk Mueller <mueller@kde.org>                *
 *     Copyright (C) 2004 by James Ots <kde@jamesots.com>                  *
12 13 14 15 16 17 18 19 20 21
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <qpainter.h>
#include <qtimer.h>
#include <qpushbutton.h>
Enrico Ros's avatar
Enrico Ros committed
22 23
#include <qapplication.h>
#include <qclipboard.h>
24 25 26 27 28

#include <kiconloader.h>
#include <kurldrag.h>
#include <kaction.h>
#include <kactioncollection.h>
29
#include <kpopupmenu.h>
30 31 32 33
#include <klocale.h>
#include <kconfigbase.h>

#include <math.h>
34
#include <stdlib.h>
35 36

#include "pageview.h"
37
#include "pageviewutils.h"
38 39 40 41 42 43 44 45 46 47
#include "pixmapwidget.h"
#include "page.h"


// structure used internally by PageView for data storage
class PageViewPrivate
{
public:
    // the document, current page and pages indices vector
    KPDFDocument * document;
48
    PageWidget * page; //equal to pages[vectorIndex]
49 50 51 52
    QValueVector< PageWidget * > pages;
    int vectorIndex;

    // view layout, zoom and mouse
53 54
    int viewColumns;
    bool viewContinous;
55 56 57 58
    PageView::ZoomMode zoomMode;
    float zoomFactor;
    PageView::MouseMode mouseMode;
    QPoint mouseGrabPos;
59
    QPoint mouseStartPos;
60
    bool mouseOnLink;
61
    bool mouseOnActiveRect;
62
    PageWidget * mouseSelectionWidget;
63 64

    // other stuff
65
    QTimer *delayTimer;
66 67
    QTimer *scrollTimer;
    int scrollIncrement;
68
    bool dirtyLayout;
69 70
    PageViewOverlay * overlayWindow;    //in pageviewutils.h
    PageViewMessage * messageWindow;    //in pageviewutils.h
71 72 73 74 75 76

    // actions
    KSelectAction *aZoom;
    KToggleAction *aZoomFitWidth;
    KToggleAction *aZoomFitPage;
    KToggleAction *aZoomFitText;
77
    KToggleAction *aZoomFitRect;
78 79
    KToggleAction *aViewTwoPages;
    KToggleAction *aViewContinous;
80 81 82
};


83

84 85 86 87 88 89 90 91 92
/* PageView. What's in this file? -> quick overview.
 * Code weight (in rows) and meaning:
 *  160 - constructor and creating actions plus their connected slots (empty stuff)
 *  70  - DocumentObserver inherited methodes (important)
 *  200 - events: mouse, keyboard, drag/drop
 *  170 - slotRelayoutPages: set contents of the scrollview on continous/single modes
 *  100 - zoom: zooming pages in different ways, keeping update the toolbar actions, etc..
 *  other misc functions: only slotRequestVisiblePixmaps and pickPageOnPoint noticeable,
 * and many insignificant stuff like this comment :-)
93 94
 */
PageView::PageView( QWidget *parent, KPDFDocument *document )
95
    : QScrollView( parent, "KPDF::pageView", WNoAutoErase | WStaticContents )
96 97 98 99 100
{
    // create and initialize private storage structure
    d = new PageViewPrivate();
    d->document = document;
    d->page = 0;
101
    d->vectorIndex = -1;
102 103
    d->viewColumns = 1;
    d->viewContinous = false;
104
    d->zoomMode = ZoomFixed;
105
    d->zoomFactor = 1.0;
106 107
    d->mouseMode = MouseNormal;
    d->mouseOnLink = false;
108
    d->mouseOnActiveRect = false;
109
    d->mouseSelectionWidget = 0;
110
    d->delayTimer = 0;
111 112
    d->scrollTimer = 0;
    d->scrollIncrement = 0;
113
    d->dirtyLayout = false;
114 115
    d->overlayWindow = 0;
    d->messageWindow = new PageViewMessage(this);
116 117 118

    // dealing with (very) large areas so enable clipper
    enableClipper( true );
119

120 121 122 123 124
    // widget setup: setup focus, accept drops and track mouse
    viewport()->setFocusProxy( this );
    viewport()->setFocusPolicy( StrongFocus );
    viewport()->setPaletteBackgroundColor( Qt::gray );
    setResizePolicy( Manual );
125
    setAcceptDrops( true );
126
    setDragAutoScroll( false );
127
    viewport()->setMouseTracking( true );
128 129 130

    // conntect the padding of the viewport to pixmaps requests
    connect( this, SIGNAL(contentsMoving(int, int)), this, SLOT(slotRequestVisiblePixmaps(int, int)) );
131 132 133

    // set a corner button to resize the view to the page size
    QPushButton * resizeButton = new QPushButton( viewport() );
134
    resizeButton->setPixmap( SmallIcon("crop") );
135 136 137 138 139 140 141 142 143 144 145 146
    setCornerWidget( resizeButton );
    resizeButton->setEnabled( false );
    // connect(...);
}

PageView::~PageView()
{
    delete d;
}

void PageView::setupActions( KActionCollection * ac, KConfigGroup * config )
{
147
    // Zoom actions ( higher scales takes lots of memory! )
148
    d->aZoom = new KSelectAction( i18n( "Zoom" ), "viewmag", 0, this, SLOT( slotZoom() ), ac, "zoom_to" );
149 150
    d->aZoom->setEditable( true );
    updateZoomText();
151 152 153 154 155 156 157 158 159 160 161

    KStdAction::zoomIn( this, SLOT( slotZoomIn() ), ac, "zoom_in" );

    KStdAction::zoomOut( this, SLOT( slotZoomOut() ), ac, "zoom_out" );

    d->aZoomFitWidth = new KToggleAction( i18n("Fit to Page &Width"), "viewmagfit", 0, ac, "zoom_fit_width" );
    connect( d->aZoomFitWidth, SIGNAL( toggled( bool ) ), SLOT( slotFitToWidthToggled( bool ) ) );

    d->aZoomFitPage = new KToggleAction( i18n("Fit to &Page"), "viewmagfit", 0, ac, "zoom_fit_page" );
    connect( d->aZoomFitPage, SIGNAL( toggled( bool ) ), SLOT( slotFitToPageToggled( bool ) ) );

162
    d->aZoomFitText = new KToggleAction( i18n("Fit to &Text"), "viewmagfit", 0, ac, "zoom_fit_text" );
163 164
    connect( d->aZoomFitText, SIGNAL( toggled( bool ) ), SLOT( slotFitToTextToggled( bool ) ) );

165 166 167
    d->aZoomFitRect = new KToggleAction( i18n("Zoom to rect"), "viewmag", 0, ac, "zoom_fit_rect" );
    connect( d->aZoomFitRect, SIGNAL( toggled( bool ) ), SLOT( slotFitToRectToggled( bool ) ) );

168
    // View-Layout actions
169 170 171 172
    d->aViewTwoPages = new KToggleAction( i18n("Two Pages"), "view_left_right", 0, ac, "view_twopages" );
    connect( d->aViewTwoPages, SIGNAL( toggled( bool ) ), SLOT( slotTwoPagesToggled( bool ) ) );
    d->aViewTwoPages->setChecked( config->readBoolEntry( "ViewTwoPages", false ) );
    slotTwoPagesToggled( d->aViewTwoPages->isChecked() );
173

174 175 176 177
    d->aViewContinous = new KToggleAction( i18n("Continous"), "view_text", 0, ac, "view_continous" );
    connect( d->aViewContinous, SIGNAL( toggled( bool ) ), SLOT( slotContinousToggled( bool ) ) );
    d->aViewContinous->setChecked( config->readBoolEntry( "ViewContinous", true ) );
    slotContinousToggled( d->aViewContinous->isChecked() );
178 179

    // Mouse-Mode actions
180
    KToggleAction * mn = new KRadioAction( i18n("Normal"), "mouse", 0, this, SLOT( slotSetMouseNormal() ), ac, "mouse_drag" );
181 182 183
    mn->setExclusiveGroup("MouseType");
    mn->setChecked( true );

184
    KToggleAction * ms = new KRadioAction( i18n("Select"), "frame_edit", 0, this, SLOT( slotSetMouseSelect() ), ac, "mouse_select" );
185
    ms->setExclusiveGroup("MouseType");
186
    //ms->setEnabled( false ); // implement feature before removing this line
187

188
    KToggleAction * md = new KRadioAction( i18n("Draw"), "edit", 0, this, SLOT( slotSetMouseDraw() ), ac, "mouse_draw" );
189
    md->setExclusiveGroup("MouseType");
190
    //md->setEnabled( false ); // implement feature before removing this line
191 192

    // Other actions
193 194 195 196 197 198
    KAction * su = new KAction( i18n("Scroll Up"), 0, this, SLOT( slotScrollUp() ), ac, "view_scroll_up" );
    su->setShortcut( "Shift+Up" );

    KAction * sd = new KAction( i18n("Scroll Down"), 0, this, SLOT( slotScrollDown() ), ac, "view_scroll_down" );
    sd->setShortcut( "Shift+Down" );

199 200 201 202 203 204 205 206 207 208 209
    KToggleAction * ss = new KToggleAction( i18n( "Show &Scrollbars" ), 0, ac, "show_scrollbars" );
    ss->setCheckedState(i18n("Hide &Scrollbars"));
    connect( ss, SIGNAL( toggled( bool ) ), SLOT( slotToggleScrollBars( bool ) ) );

    ss->setChecked( config->readBoolEntry( "ShowScrollBars", true ) );
    slotToggleScrollBars( ss->isChecked() );
}

void PageView::saveSettings( KConfigGroup * config )
{
    config->writeEntry( "ShowScrollBars", hScrollBarMode() == AlwaysOn );
210 211
    config->writeEntry( "ViewTwoPages", d->aViewTwoPages->isChecked() );
    config->writeEntry( "ViewContinous", d->aViewContinous->isChecked() );
212 213 214
}


215
//BEGIN KPDFDocumentObserver inherited methods
Enrico Ros's avatar
Enrico Ros committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229
void PageView::pageSetup( const QValueVector<KPDFPage*> & pageSet, bool documentChanged )
{
    // reuse current pages if nothing new
    if ( ( pageSet.count() == d->pages.count() ) && !documentChanged )
    {
        int count = pageSet.count();
        for ( int i = 0; (i < count) && !documentChanged; i++ )
            if ( (int)pageSet[i]->number() != d->pages[i]->pageNumber() )
                documentChanged = true;
        if ( !documentChanged )
            return;
    }

    // delete all widgets (one for each page in pageSet)
230 231 232 233 234 235 236 237 238 239
    QValueVector< PageWidget * >::iterator dIt = d->pages.begin(), dEnd = d->pages.end();
    for ( ; dIt != dEnd; ++dIt )
        delete *dIt;
    d->pages.clear();
    d->page = 0;

    // create children widgets
    QValueVector< KPDFPage * >::const_iterator setIt = pageSet.begin(), setEnd = pageSet.end();
    for ( ; setIt != setEnd; ++setIt )
    {
240 241
        PageWidget * p = new PageWidget( viewport(), *setIt );
        p->setFocusProxy( this );
242
        p->setMouseTracking( true );
243 244 245
        d->pages.push_back( p );
    }

246
    // invalidate layout
247
    d->dirtyLayout = true;
248 249
}

Enrico Ros's avatar
Enrico Ros committed
250
void PageView::pageSetCurrent( int pageNumber, const QRect & /*viewport*/ )
251
{
252 253 254
    // select next page
    d->vectorIndex = 0;
    d->page = 0;
255 256 257
    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
    {
258
        if ( (*pIt)->pageNumber() == pageNumber )
259
        {
260
            d->page = *pIt;
261 262
            break;
        }
263
        d->vectorIndex ++;
264
    }
265 266
    if ( !d->page )
        return;
267

Enrico Ros's avatar
Enrico Ros committed
268 269
    // relayout in "Single Pages" mode or if a relayout is pending
    if ( !d->viewContinous || d->dirtyLayout )
270 271 272
        slotRelayoutPages();

    // center the view to see the selected page
Enrico Ros's avatar
Enrico Ros committed
273
    // FIXME take care of viewport
274
    int xPos = childX( d->page ) + d->page->widthHint() / 2,
Enrico Ros's avatar
Enrico Ros committed
275
        yPos = childY( d->page );
276 277 278 279 280 281
    center( xPos, yPos + visibleHeight() / 2 - 10 );
    slotRequestVisiblePixmaps();

    // update zoom text if in a ZoomFit/* zoom mode
    if ( d->zoomMode != ZoomFixed )
        updateZoomText();
282 283
}

284
void PageView::notifyPixmapChanged( int pageNumber )
285
{
286 287 288
    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
        if ( (*pIt)->pageNumber() == pageNumber )
289
        {
290
            (*pIt)->update();
291 292 293 294 295
            break;
        }
}
//END KPDFDocumentObserver inherited methods

296
//BEGIN widget events
297 298
void PageView::contentsMousePressEvent( QMouseEvent * e )
{
299 300 301 302 303 304 305 306 307 308 309
    bool leftButton = e->button() & LeftButton;

    // handle 'Zoom To Area', in every mouse mode
    if ( leftButton && d->zoomMode == ZoomRect )
    {
        d->mouseStartPos = e->pos();
        d->mouseGrabPos = QPoint();
        return;
    }

    // handle mode dependant mouse press actions
310 311
    switch ( d->mouseMode )
    {
312 313
        case MouseNormal:    // drag start / click / link following
            if ( leftButton )
314
            {
315 316 317 318
                d->mouseStartPos = e->globalPos();
                d->mouseGrabPos = d->mouseOnLink ? QPoint() : d->mouseStartPos;
                if ( !d->mouseOnLink )
                    setCursor( sizeAllCursor );
319
            }
320 321 322
            else if ( e->button() & RightButton )
                emit rightClick();
            break;
323

324 325
        case MouseSelection: // set first corner of the selection rect
            if ( leftButton )
326
            {
327 328 329 330 331 332 333 334 335
                if ( d->mouseSelectionWidget )
                    d->mouseSelectionWidget->clearSelection();
                d->mouseSelectionWidget = 0;
                PageWidget * page = pickPageOnPoint( e->x(), e->y() );
                if ( page )
                {
                    page->setBeginCorner( e->x() - childX( page ), e->y() - childY( page ) );
                    d->mouseSelectionWidget = page;
                }
336
            }
337
            break;
338

339 340
        case MouseEdit:      // ? place the beginning of [tool] ?
            break;
341 342 343
    }
}

344
void PageView::contentsMouseReleaseEvent( QMouseEvent * e )
345
{
346 347
    bool leftButton = e->button() & LeftButton,
         rightButton = e->button() & RightButton;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

    // handle 'Zoom To Area', in every mouse mode
    if ( leftButton && d->overlayWindow )
    {
        // find out new zoom ratio
        QRect selRect = d->overlayWindow->selectedRect();
        float zoom = QMIN( (float)clipper()->width() / (float)selRect.width(),
                           (float)clipper()->height() / (float)selRect.height() );

        // get normalized view center (relative to the contentsRect)
        // coeffs (2.0 and 1.5) are for correcting the asymmetic page border
        // that makes the page not perfectly centered on the viewport
        double nX = ( contentsX() - 1.0 + selRect.left() + (double)selRect.width() / 2.0 ) / (double)contentsWidth();
        double nY = ( contentsY() - 1.5 + selRect.top() + (double)selRect.height() / 2.0 ) / (double)contentsHeight();

        // zoom up to 400%
        if ( d->zoomFactor <= 4.0 || zoom <= 1.0 )
        {
            d->zoomFactor *= zoom;
            if ( d->zoomFactor > 4.0 )
                d->zoomFactor = 4.0;
            updateZoom( ZoomRefreshCurrent );
        }

        // recenter view
        center( (int)(nX * contentsWidth()), (int)(nY * contentsHeight()) );

        // hide message box and delete overlay window
        d->messageWindow->hide();
        delete d->overlayWindow;
        d->overlayWindow = 0;

        // reset start position
        d->mouseStartPos = QPoint();
        return;
    }
    // if in ZoomRect mode, right click zooms out
    if ( rightButton && d->zoomMode == ZoomRect )
    {
        updateZoom( ZoomOut );
        updateZoom( ZoomRect );
        return;
    }

392
    PageWidget * pageWidget = pickPageOnPoint( e->x(), e->y() );
393 394
    switch ( d->mouseMode )
    {
395
        case MouseNormal:
396
            setCursor( arrowCursor );
397
            if ( leftButton && pageWidget )
398
            {
399 400 401 402 403 404 405 406 407 408 409 410 411
                if ( d->mouseOnLink )
                {
                    // activate link
                    int linkX = e->x() - childX( pageWidget ),
                        linkY = e->y() - childY( pageWidget );
                    d->document->slotProcessLink( pageWidget->page()->getLink( linkX, linkY ) );
                }
                else
                {
                    // mouse not moved since press, so we have a click. select the page.
                    if ( e->globalPos() == d->mouseStartPos )
                        d->document->slotSetCurrentPage( pageWidget->pageNumber() );
                }
412
            }
413
            else if ( rightButton && pageWidget )
414
            {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                // if over a page display a popup menu
                const KPDFPage * kpdfPage = pageWidget->page();
                KPopupMenu * m_popup = new KPopupMenu( this, "rmb popup" );
                m_popup->insertTitle( i18n( "Page %1" ).arg( kpdfPage->number() + 1 ) );
                if ( kpdfPage->isBookmarked() )
                    m_popup->insertItem( SmallIcon("bookmark"), i18n("Remove Bookmark"), 1 );
                else
                    m_popup->insertItem( SmallIcon("bookmark_add"), i18n("Add Bookmark"), 1 );
                m_popup->insertItem( SmallIcon("viewmagfit"), i18n("Fit Page"), 2 );
                m_popup->insertItem( SmallIcon("pencil"), i18n("Edit"), 3 );
                switch ( m_popup->exec(e->globalPos()) )
                {
                    case 1:
                        d->document->slotBookmarkPage( kpdfPage->number(), !kpdfPage->isBookmarked() );
                        break;
                    case 2: // FiXME less hackish, please!
                        d->aZoomFitWidth->setChecked( true );
                        updateZoom( ZoomFitWidth );
                        d->aViewTwoPages->setChecked( false );
                        slotTwoPagesToggled( false );
                        d->document->slotSetCurrentPage( kpdfPage->number() );
                        break;
                    case 3: // ToDO switch to edit mode
                        slotSetMouseDraw();
                        break;
                }
441
                delete m_popup;
442
            }
443 444 445
            // reset start position
            d->mouseStartPos = QPoint();
            break;
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        case MouseSelection:
            if ( leftButton && d->mouseSelectionWidget )
            {
                // request the textpage if there isn't one
                const KPDFPage * kpdfPage = d->mouseSelectionWidget->page();
                if ( !kpdfPage->hasSearchPage() )
                    d->document->requestTextPage( kpdfPage->number() );

                // copy text into the clipboard
                QClipboard *cb = QApplication::clipboard();
                const QString & selection = d->mouseSelectionWidget->selectedText();
                cb->setText( selection, QClipboard::Clipboard );
                if ( cb->supportsSelection() )
                    cb->setText( selection, QClipboard::Selection );

                // clear widget selection
                d->mouseSelectionWidget->clearSelection();
                d->mouseSelectionWidget = 0;
            }
            break;
467

468 469
        case MouseEdit:      // ? apply [tool] ?
            break;
470 471 472 473 474
    }
}

void PageView::contentsMouseMoveEvent( QMouseEvent * e )
{
475
    bool leftButton = e->state() & LeftButton;
476 477 478

    // handle 'Zoom To Area', in every mouse mode
    if ( leftButton && d->zoomMode == ZoomRect && !d->mouseStartPos.isNull() )
479
    {
480 481
        // create zooming a window (overlay mode)
        if ( !d->overlayWindow )
482
        {
483 484
            d->overlayWindow = new PageViewOverlay( clipper(), PageViewOverlay::Zoom );
            d->overlayWindow->setBeginCorner( d->mouseStartPos.x() - contentsX(), d->mouseStartPos.y() - contentsY() );
485
        }
486 487 488 489 490 491 492 493 494 495

        // set rect's 2nd corner
        d->overlayWindow->setEndCorner( e->x() - contentsX(), e->y() - contentsY() );
        return;
    }

    switch ( d->mouseMode )
    {
        case MouseNormal:
            if ( leftButton )
496
            {
497 498 499 500 501 502 503 504 505 506 507 508 509 510
                // drag page
                if ( !d->mouseGrabPos.isNull() )
                {
                    // scroll page by position increment
                    QPoint delta = d->mouseGrabPos - e->globalPos();
                    scrollBy( delta.x(), delta.y() );
                    d->mouseGrabPos = e->globalPos();
                    // if the page was scrolling, stop it
                    if ( d->scrollTimer )
                    {
                        d->scrollIncrement = 0;
                        d->scrollTimer->stop();
                    }
                }
511
            }
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
            else
            {
                // detect the underlaying page (if present)
                PageWidget * pageWidget = pickPageOnPoint( e->x(), e->y() );
                if ( pageWidget )
                {
                    int pageX = e->x() - childX( pageWidget ),
                        pageY = e->y() - childY( pageWidget );

                    // check if over a KPDFActiveRect
                    bool onActiveRect = pageWidget->page()->hasActiveRect( pageX, pageY );
                    if ( onActiveRect != d->mouseOnActiveRect )
                    {
                        d->mouseOnActiveRect = onActiveRect;
                        setCursor( onActiveRect ? pointingHandCursor : arrowCursor );
                    }

                    // check if over a KPDFLink
                    bool onLink = pageWidget->page()->hasLink( pageX, pageY );
                    if ( onLink != d->mouseOnLink )
                    {
                        d->mouseOnLink = onLink;
                        setCursor( onLink ? pointingHandCursor : arrowCursor );
                    }
                }
            }
            break;

        case MouseSelection:
            // set second corner of selection in selection pagewidget
            if ( leftButton && d->mouseSelectionWidget )
                d->mouseSelectionWidget->setEndCorner( e->x() - childX( d->mouseSelectionWidget ),
                                                       e->y() - childY( d->mouseSelectionWidget ) );
            break;

        case MouseEdit:      // ? update graphics ?
            break;
549 550 551 552 553
    }
}

void PageView::keyPressEvent( QKeyEvent * e )
{
554 555
    e->accept();
    // move/scroll page by using keys
556 557
    switch ( e->key() )
    {
558 559 560 561 562 563 564 565 566
        case Key_Up:
            if ( atTop() && !d->viewContinous )
                scrollUp();
            else
                verticalScrollBar()->subtractLine();
            break;
        case Key_Down:
            if ( atBottom() && !d->viewContinous )
                scrollDown();
567
            else
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
                verticalScrollBar()->addLine();
            break;
        case Key_Left:
            horizontalScrollBar()->subtractLine();
            break;
        case Key_Right:
            horizontalScrollBar()->addLine();
            break;
        case Key_PageUp:
            verticalScrollBar()->subtractPage();
            break;
        case Key_PageDown:
            verticalScrollBar()->addPage();
            break;
        case Key_Shift:
        case Key_Control:
            if ( d->scrollTimer )
            {
                if ( d->scrollTimer->isActive() )
                    d->scrollTimer->stop();
                else
                    slotAutoScoll();
                return;
            }
        default:
            e->ignore();
594
            return;
595
    }
596
    // if a known key has been pressed, stop scrolling the page
597 598 599 600 601
    if ( d->scrollTimer )
    {
        d->scrollIncrement = 0;
        d->scrollTimer->stop();
    }
602 603 604 605 606 607 608
}

void PageView::wheelEvent( QWheelEvent *e )
{
    int delta = e->delta();
    e->accept();
    if ( (e->state() & ControlButton) == ControlButton ) {
609
        if ( e->delta() < 0 )
610 611 612 613
            slotZoomOut();
        else
            slotZoomIn();
    }
614
    else if ( delta <= -120 && atBottom() && !d->viewContinous )
615
        scrollDown();
616
    else if ( delta >= 120 && atTop() && !d->viewContinous )
617 618 619 620 621
        scrollUp();
    else
        QScrollView::wheelEvent( e );
}

622 623 624 625 626 627 628 629 630 631 632
void PageView::viewportResizeEvent( QResizeEvent * )
{
    // start a timer that will refresh the pixmap after 0.5s
    if ( !d->delayTimer )
    {
        d->delayTimer = new QTimer( this );
        connect( d->delayTimer, SIGNAL( timeout() ), this, SLOT( slotRelayoutPages() ) );
    }
    d->delayTimer->start( 400, true );
}

633 634 635 636 637 638 639 640 641 642 643 644 645 646
void PageView::dragEnterEvent( QDragEnterEvent * ev )
{
    ev->accept();
}

void PageView::dropEvent( QDropEvent * ev )
{
    KURL::List lst;
    if (  KURLDrag::decode(  ev, lst ) )
        emit urlDropped( lst.first() );
}
//END widget events

//BEGIN internal SLOTS
647
void PageView::slotZoom()
648
{
649
    updateZoom( ZoomFixed );
650 651 652 653
}

void PageView::slotZoomIn()
{
654
    updateZoom( ZoomIn );
655 656 657 658
}

void PageView::slotZoomOut()
{
659
    updateZoom( ZoomOut );
660 661 662 663
}

void PageView::slotFitToWidthToggled( bool on )
{
664
    if ( on ) updateZoom( ZoomFitWidth );
665 666 667 668
}

void PageView::slotFitToPageToggled( bool on )
{
669
    if ( on ) updateZoom( ZoomFitPage );
670 671 672 673
}

void PageView::slotFitToTextToggled( bool on )
{
674
    if ( on ) updateZoom( ZoomFitText );
675 676
}

677 678 679 680 681 682
void PageView::slotFitToRectToggled( bool on )
{
    if ( on ) updateZoom( ZoomRect );
    else updateZoom( ZoomFixed );
}

683 684
void PageView::slotTwoPagesToggled( bool on )
{
685 686 687 688
    int newColumns = on ? 2 : 1;
    if ( d->viewColumns != newColumns )
    {
        d->viewColumns = newColumns;
689
        slotRelayoutPages();
690
    }
691 692
}

693 694
void PageView::slotContinousToggled( bool on )
{
695 696 697
    if ( d->viewContinous != on )
    {
        d->viewContinous = on;
698
        slotRelayoutPages();
699
    }
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
}

void PageView::slotSetMouseNormal()
{
    d->mouseMode = MouseNormal;
}

void PageView::slotSetMouseSelect()
{
    d->mouseMode = MouseSelection;
}

void PageView::slotSetMouseDraw()
{
    d->mouseMode = MouseEdit;
}

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
void PageView::slotScrollUp()
{
    if ( d->scrollIncrement < -9 )
        return;
    d->scrollIncrement--;
    slotAutoScoll();
}

void PageView::slotScrollDown()
{
    if ( d->scrollIncrement > 9 )
        return;
    d->scrollIncrement++;
    slotAutoScoll();
}

733 734 735 736 737 738
void PageView::slotToggleScrollBars( bool on )
{
    setHScrollBarMode( on ? AlwaysOn : AlwaysOff );
    setVScrollBarMode( on ? AlwaysOn : AlwaysOff );
}

739 740
void PageView::slotRelayoutPages()
// called by: pageSetup, viewportResizeEvent, slotTwoPagesToggled, slotContinousToggled, updateZoom
741 742 743 744 745 746 747 748 749 750
{
    // set an empty container if we have no pages
    int pageCount = d->pages.count();
    if ( pageCount < 1 )
    {
        resizeContents( 0,0 );
        return;
    }

    int viewportWidth = clipper()->width(),
751 752 753
        viewportHeight = clipper()->height(),
        fullWidth = 0,
        fullHeight = 0;
754 755

    if ( d->viewContinous == TRUE )
756
    {
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
        // Here we find out column's width and row's height to compute a table
        // so we can place widgets 'centered in virtual cells'.
        int nCols = d->viewColumns,
            nRows = (int)ceilf( (float)pageCount / (float)nCols ),
            * colWidth = new int[ nCols ],
            * rowHeight = new int[ nRows ],
            cIdx = 0,
            rIdx = 0;
        for ( int i = 0; i < nCols; i++ )
            colWidth[ i ] = viewportWidth / nCols;
        for ( int i = 0; i < nRows; i++ )
            rowHeight[ i ] = 0;

        // 1) find the maximum columns width and rows height for a grid in
        // which each page must well-fit inside a cell
        QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
        for ( ; pIt != pEnd; ++pIt )
774
        {
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
            PageWidget * p = *pIt;
            // update internal page geometry
            if ( d->zoomMode == ZoomFixed )
                p->setZoomFixed( d->zoomFactor );
            else if ( d->zoomMode == ZoomFitWidth )
                p->setZoomFitWidth( colWidth[ cIdx ] - 10 );
            else
                p->setZoomFitRect( colWidth[ cIdx ] - 10, viewportHeight - 10 );
            // find row's maximum height and column's max width
            int pWidth = p->widthHint(),
                pHeight = p->heightHint();
            if ( pWidth > colWidth[ cIdx ] )
                colWidth[ cIdx ] = pWidth;
            if ( pHeight > rowHeight[ rIdx ] )
                rowHeight[ rIdx ] = pHeight;
            // update col/row indices
            if ( ++cIdx == nCols )
792
            {
793 794
                cIdx = 0;
                rIdx++;
795 796
            }
        }
797 798 799

        // 2) arrange widgets inside cells
        int insertX = 0,
800
            insertY = (int)(2.0 + 4.0 * d->zoomFactor);
801 802 803 804 805 806 807 808 809 810 811 812
        cIdx = 0;
        rIdx = 0;
        for ( pIt = d->pages.begin(); pIt != pEnd; ++pIt )
        {
            PageWidget * p = *pIt;
            int pWidth = p->widthHint(),
                pHeight = p->heightHint(),
                cWidth = colWidth[ cIdx ],
                rHeight = rowHeight[ rIdx ];
            // show, resize and center widget inside 'cells'
            p->resize( pWidth, pHeight );
            moveChild( p, insertX + (cWidth - pWidth) / 2,
813
                       insertY + (rHeight - pHeight) / 2 );
814 815 816 817 818 819 820 821 822 823 824 825
            p->show();
            // advance col/row index
            insertX += cWidth;
            if ( ++cIdx == nCols )
            {
                cIdx = 0;
                rIdx++;
                insertX = 0;
                insertY += rHeight + (int)(5.0 + 15.0 * d->zoomFactor);
            }
        }

826
        fullHeight = cIdx ? (insertY + rowHeight[ rIdx ] + 10) : insertY;
827 828 829 830 831 832 833 834
        for ( int i = 0; i < nCols; i++ )
            fullWidth += colWidth[ i ];

        delete [] colWidth;
        delete [] rowHeight;
    }
    else // viewContinous is FALSE
    {
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        PageWidget * currentPage = d->page ? d->page : d->pages[0];

        // setup varialbles for a 1(row) x N(columns) grid
        int nCols = d->viewColumns,
            * colWidth = new int[ nCols ],
            cIdx = 0;
        fullHeight = viewportHeight;
        for ( int i = 0; i < nCols; i++ )
            colWidth[ i ] = viewportWidth / nCols;

        // 1) find out maximum area extension for the pages
        QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
        for ( ; pIt != pEnd; ++pIt )
        {
            PageWidget * p = *pIt;
            if ( p == currentPage || (cIdx > 0 && cIdx < nCols) )
            {
                if ( d->zoomMode == ZoomFixed )
                    p->setZoomFixed( d->zoomFactor );
                else if ( d->zoomMode == ZoomFitWidth )
                    p->setZoomFitWidth( colWidth[ cIdx ] - 10 );
                else
                    p->setZoomFitRect( colWidth[ cIdx ] - 10, viewportHeight - 10 );
                if ( p->widthHint() > colWidth[ cIdx ] )
                    colWidth[ cIdx ] = p->widthHint();
                fullHeight = QMAX( fullHeight, p->heightHint() );
                cIdx++;
            }
        }

        // 2) hide all widgets except the displayable ones and dispose those
        int insertX = 0,
            insertY = (int)(2.0 + 4.0 * d->zoomFactor);
        cIdx = 0;
        for ( pIt = d->pages.begin(); pIt != pEnd; ++pIt )
        {
            PageWidget * p = *pIt;
            if ( p == currentPage || (cIdx > 0 && cIdx < nCols) )
            {
                int pWidth = p->widthHint(),
                    pHeight = p->heightHint();
                // show, resize and center widget inside 'cells'
                p->resize( pWidth, pHeight );
                moveChild( p, insertX + (colWidth[ cIdx ] - pWidth) / 2,
                           insertY + (fullHeight - pHeight) / 2 );
                p->show();
                // advance col/row index
                insertX += colWidth[ cIdx ];
                cIdx++;
            }
            else
                p->hide();
        }

        for ( int i = 0; i < nCols; i++ )
            fullWidth += colWidth[ i ];

        delete [] colWidth;
    }

    // 3) update scrollview's contents size and recenter view
    int oldWidth = contentsWidth(),
        oldHeight = contentsHeight();
    if ( oldWidth != fullWidth || oldHeight != fullHeight )
    {
        resizeContents( fullWidth, fullHeight );
        if ( oldWidth > 0 && oldHeight > 0 )
            center( fullWidth * (contentsX() + visibleWidth() / 2) / oldWidth,
                    fullHeight * (contentsY() + visibleHeight() / 2) / oldHeight );
        else
            center( fullWidth / 2, 0 );
906
    }
907 908

    // reset dirty state
909 910 911
    d->dirtyLayout = false;
}

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
void PageView::slotRequestVisiblePixmaps( int newLeft, int newTop )
{
    // precalc view limits for intersecting with page coords inside the lOOp
    int vLeft = (newLeft == -1) ? contentsX() : newLeft,
        vRight = vLeft + visibleWidth(),
        vTop = (newTop == -1) ? contentsY() : newTop,
        vBottom = vTop + visibleHeight();

    // scroll from the top to the last visible thumbnail
    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
    {
        PageWidget * p = *pIt;
        int pLeft = childX( p ),
            pRight = pLeft + p->widthHint(),
            pTop = childY( p ),
            pBottom = pTop + p->heightHint();
        if ( p->isShown() && pRight > vLeft && pLeft < vRight && pBottom > vTop && pTop < vBottom )
            d->document->requestPixmap( PAGEVIEW_ID, p->pageNumber(), p->pixmapWidth(), p->pixmapHeight(), true );
    }
}
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956

void PageView::slotAutoScoll()
{
    // the first time create the timer
    if ( !d->scrollTimer )
    {
        d->scrollTimer = new QTimer( this );
        connect( d->scrollTimer, SIGNAL( timeout() ), this, SLOT( slotAutoScoll() ) );
    }

    // if scrollIncrement is zero, stop the timer
    if ( !d->scrollIncrement )
    {
        d->scrollTimer->stop();
        return;
    }

    // compute delay between timer ticks and scroll amount per tick
    int index = abs( d->scrollIncrement ) - 1;  // 0..9
    const int scrollDelay[10] =  { 200, 100, 50, 30, 20, 30, 25, 20, 30, 20 };
    const int scrollOffset[10] = {   1,   1,  1,  1,  1,  2,  2,  2,  4,  4 };
    d->scrollTimer->changeInterval( scrollDelay[ index ] );
    scrollBy( 0, d->scrollIncrement > 0 ? scrollOffset[ index ] : -scrollOffset[ index ] );
}
957 958
//END internal SLOTS

959 960
void PageView::updateZoom( ZoomMode newZoomMode )
{
961 962 963 964 965 966 967 968 969 970 971 972 973 974
    // handle zoomRect case, showing message window too
    if ( newZoomMode == ZoomRect )
    {
        d->zoomMode = ZoomRect;
        d->aZoomFitWidth->setChecked( false );
        d->aZoomFitPage->setChecked( false );
        d->aZoomFitText->setChecked( false );
        d->messageWindow->display( i18n( "Select Zooming Area. Right-Click to zoom out." ), PageViewMessage::Info );
        return;
    }
    // if zoomMode is changing from ZoomRect, hide info popup
    if ( d->zoomMode == ZoomRect )
        d->messageWindow->hide();

975 976
    if ( newZoomMode == ZoomFixed )
    {
977
        if ( d->aZoom->currentItem() == 0 )
978
            newZoomMode = ZoomFitWidth;
979
        else if ( d->aZoom->currentItem() == 1 )
980 981 982 983 984 985 986
            newZoomMode = ZoomFitPage;
    }

    float newFactor = d->zoomFactor;
    KAction * checkedZoomAction = 0;
    switch ( newZoomMode )
    {
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        default:{ //ZoomFixed case
            QString z = d->aZoom->currentText();
            newFactor = KGlobal::locale()->readNumber( z.remove( z.find( '%' ), 1 ) ) / 100.0;
            if ( newFactor < 0.1 || newFactor > 8.0 )
                return;
            }break;
        case ZoomIn:
            newFactor += 0.1;
            if ( newFactor >= 4.0 )
                newFactor = 4.0;
            newZoomMode = ZoomFixed;
            break;
        case ZoomOut:
            newFactor -= 0.1;
            if ( newFactor <= 0.125 )
                newFactor = 0.125;
            newZoomMode = ZoomFixed;
            break;
        case ZoomFitWidth:
            checkedZoomAction = d->aZoomFitWidth;
            break;
        case ZoomFitPage:
            checkedZoomAction = d->aZoomFitPage;
            break;
        case ZoomFitText:
            checkedZoomAction = d->aZoomFitText;
            break;
        case ZoomRefreshCurrent:
            newZoomMode = ZoomFixed;
            d->zoomFactor = -1;
            break;
1018 1019 1020 1021 1022 1023 1024 1025 1026
    }

    if ( newZoomMode != d->zoomMode || (newZoomMode == ZoomFixed && newFactor != d->zoomFactor ) )
    {
        // rebuild layout and change the zoom selectAction contents
        d->zoomMode = newZoomMode;
        d->zoomFactor = newFactor;
        slotRelayoutPages();
        updateZoomText();
1027
        // update actions checked state
1028 1029 1030
        d->aZoomFitWidth->setChecked( checkedZoomAction == d->aZoomFitWidth );
        d->aZoomFitPage->setChecked( checkedZoomAction == d->aZoomFitPage );
        d->aZoomFitText->setChecked( checkedZoomAction == d->aZoomFitText );
1031
        d->aZoomFitRect->setChecked( false );
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        // request pixmaps
        slotRequestVisiblePixmaps();
    }
}

void PageView::updateZoomText()
{
    // use current page zoom as zoomFactor if in ZoomFit/* mode
    if ( d->zoomMode != ZoomFixed && d->pages.count() > 0 )
        d->zoomFactor = d->page ? d->page->zoomFactor() : d->pages[0]->zoomFactor();
    float newFactor = d->zoomFactor;
    d->aZoom->clear();

    // add items that describe fit actions
    QStringList translated;
    translated << i18n("Fit Width") << i18n("Fit Page"); // << i18n("Fit Text");

    // add percent items
    QString double_oh( "00" );
    const float zoomValue[10] = { 0.125, 0.25, 0.333, 0.5, 0.667, 0.75, 1, 1.25, 1.50, 2 };
    int idx = 0,
        selIdx = 2; // use 3 if "fit text" present
    bool inserted = false; //use: "d->zoomMode != ZoomFixed" to hide Fit/* zoom ratio
    while ( idx < 10 || !inserted )
    {
        float value = idx < 10 ? zoomValue[ idx ] : newFactor;
1058
        if ( !inserted && newFactor < (value - 0.0001) )
1059 1060 1061
            value = newFactor;
        else
            idx ++;
1062
        if ( value > (newFactor - 0.0001) && value < (newFactor + 0.0001) )
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
            inserted = true;
        if ( !inserted )
            selIdx++;
        QString localValue( KGlobal::locale()->formatNumber( value * 100.0, 2 ) );
        localValue.remove( KGlobal::locale()->decimalSymbol() + double_oh );
        translated << QString( "%1%" ).arg( localValue );
    }
    d->aZoom->setItems( translated );

    // select current item in list
    if ( d->zoomMode == ZoomFitWidth )
        selIdx = 0;
    else if ( d->zoomMode == ZoomFitPage )
        selIdx = 1;
    else if ( d->zoomMode == ZoomFitText )
        selIdx = 2;
    d->aZoom->setCurrentItem( selIdx );
1080 1081
}

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
PageWidget * PageView::pickPageOnPoint( int x, int y )
{
    PageWidget * page = 0;
    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
    {
        PageWidget * p = *pIt;
        int pLeft = childX( p ),
            pRight = pLeft + p->widthHint(),
            pTop = childY( p ),
            pBottom = pTop + p->heightHint();
        // little optimized, stops if found or probably quits on the next row
1094
        if ( x > pLeft && x < pRight && y < pBottom && p->isShown() )
1095 1096 1097 1098 1099 1100 1101 1102 1103
        {
            if ( y > pTop )
                page = p;
            break;
        }
    }
    return page;
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
bool PageView::atTop() const
{
    return verticalScrollBar()->value() == verticalScrollBar()->minValue();
}

bool PageView::atBottom() const
{
    return verticalScrollBar()->value() == verticalScrollBar()->maxValue();
}

void PageView::scrollUp()
{
    if( atTop() && d->vectorIndex > 0 )
        // go to the bottom of previous page
Enrico Ros's avatar
Enrico Ros committed
1118
        d->document->slotSetCurrentPage( d->pages[ d->vectorIndex - 1 ]->pageNumber() ); //TODO add position
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    else
    {   // go towards the top of current page
        int newValue = QMAX( verticalScrollBar()->value() - height() + 50,
                             verticalScrollBar()->minValue() );
        verticalScrollBar()->setValue( newValue );
    }
}

void PageView::scrollDown()
{
    if( atBottom() && d->vectorIndex < (int)d->pages.count() - 1 )
        // go to the top of previous page
Enrico Ros's avatar
Enrico Ros committed
1131
        d->document->slotSetCurrentPage( d->pages[ d->vectorIndex + 1 ]->pageNumber() ); // TODO add position
1132 1133 1134 1135 1136 1137 1138 1139 1140
    else
    {    // go towards the bottom of current page
        int newValue = QMIN( verticalScrollBar()->value() + height() - 50,
                             verticalScrollBar()->maxValue() );
        verticalScrollBar()->setValue( newValue );
    }
}

#include "pageview.moc"