pageview.cpp 27 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 22 23 24 25 26 27
 *                                                                         *
 *   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 <qcursor.h>
#include <qpainter.h>
#include <qtimer.h>
#include <qpushbutton.h>

#include <kiconloader.h>
#include <kurldrag.h>
#include <kaction.h>
#include <kactioncollection.h>
28
#include <kpopupmenu.h>
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <klocale.h>
#include <kconfigbase.h>

#include <math.h>

#include "pageview.h"
#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;
45
    PageWidget * page; //equal to pages[vectorIndex]
46 47 48 49
    QValueVector< PageWidget * > pages;
    int vectorIndex;

    // view layout, zoom and mouse
50 51
    int viewColumns;
    bool viewContinous;
52 53 54 55
    PageView::ZoomMode zoomMode;
    float zoomFactor;
    PageView::MouseMode mouseMode;
    QPoint mouseGrabPos;
56
    QPoint mouseStartPos;
57
    bool mouseOnLink;
58 59

    // other stuff
60
    QTimer *delayTimer;
61
    bool dirtyLayout;
62 63 64 65 66 67

    // actions
    KSelectAction *aZoom;
    KToggleAction *aZoomFitWidth;
    KToggleAction *aZoomFitPage;
    KToggleAction *aZoomFitText;
68 69
    KToggleAction *aViewTwoPages;
    KToggleAction *aViewContinous;
70 71 72 73 74 75 76
};


/*
 * PageView class
 */
PageView::PageView( QWidget *parent, KPDFDocument *document )
77
    : QScrollView( parent, "KPDF::pageView", WNoAutoErase | WStaticContents )
78 79 80 81 82
{
    // create and initialize private storage structure
    d = new PageViewPrivate();
    d->document = document;
    d->page = 0;
83 84 85
    d->viewColumns = 1;
    d->viewContinous = false;
    d->zoomMode = ZoomFitWidth;
86
    d->zoomFactor = 1.0;
87 88 89
    d->mouseMode = MouseNormal;
    d->mouseOnLink = false;
    d->delayTimer = 0;
90
    d->dirtyLayout = false;
91 92 93

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

95 96 97 98 99
    // widget setup: setup focus, accept drops and track mouse
    viewport()->setFocusProxy( this );
    viewport()->setFocusPolicy( StrongFocus );
    viewport()->setPaletteBackgroundColor( Qt::gray );
    setResizePolicy( Manual );
100 101
    setAcceptDrops( true );
    viewport()->setMouseTracking( true );
102 103 104

    // conntect the padding of the viewport to pixmaps requests
    connect( this, SIGNAL(contentsMoving(int, int)), this, SLOT(slotRequestVisiblePixmaps(int, int)) );
105 106 107

    // set a corner button to resize the view to the page size
    QPushButton * resizeButton = new QPushButton( viewport() );
108
    resizeButton->setPixmap( SmallIcon("crop") );
109 110 111 112 113 114 115 116 117 118 119 120
    setCornerWidget( resizeButton );
    resizeButton->setEnabled( false );
    // connect(...);
}

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

void PageView::setupActions( KActionCollection * ac, KConfigGroup * config )
{
121
    // Zoom actions ( higher scales takes lots of memory! )
122 123
    d->aZoom = new KSelectAction( i18n( "Zoom" ), "viewmag", 0, ac, "zoom_to" );
    connect( d->aZoom, SIGNAL( activated( const QString & ) ), this, SLOT( slotZoom( const QString& ) ) );
124 125
    d->aZoom->setEditable( true );
    updateZoomText();
126 127 128 129 130 131 132 133 134 135 136

    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 ) ) );

137 138 139
    d->aZoomFitText = new KToggleAction( i18n("Fit Text"), "viewmagfit", 0, ac, "zoom_fit_text" );
    connect( d->aZoomFitText, SIGNAL( toggled( bool ) ), SLOT( slotFitToTextToggled( bool ) ) );

140
    // View-Layout actions
141 142 143 144
    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() );
145

146 147 148 149
    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() );
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

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

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

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

    // Other actions
    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 );
176 177
    config->writeEntry( "ViewTwoPages", d->aViewTwoPages->isChecked() );
    config->writeEntry( "ViewContinous", d->aViewContinous->isChecked() );
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
}


//BEGIN KPDFDocumentObserver inherited methods 
void PageView::pageSetup( const QValueVector<KPDFPage*> & pageSet, bool /*documentChanged*/ )
{ /* TODO: preserve (reuse) existing pages if !documentChanged */
    // delete all pages
    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 )
    {
195 196
        PageWidget * p = new PageWidget( viewport(), *setIt );
        p->setFocusProxy( this );
197 198 199
        d->pages.push_back( p );
    }

200
    // invalidate layout
201
    d->dirtyLayout = true;
202 203
}

204
void PageView::pageSetCurrent( int pageNumber, float position )
205
{
206 207
    if ( d->dirtyLayout )
        slotRelayoutPages();
208

209 210 211
    // select next page
    d->vectorIndex = 0;
    d->page = 0;
212 213 214 215

    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
    {
216
        if ( (*pIt)->pageNumber() == pageNumber )
217
        {
218
            d->page = *pIt;
219 220
            break;
        }
221
        d->vectorIndex ++;
222 223
    }

224
    if ( d->page )
225
    {
226 227 228 229
        int xPos = childX( d->page ) + d->page->widthHint() / 2,
            yPos = childY( d->page ) + (int)((float)d->page->heightHint() * position);
        center( xPos, yPos + visibleHeight() / 2 - 10 );
        slotRequestVisiblePixmaps();
230 231
        if ( d->zoomMode != ZoomFixed )
            updateZoomText();
232 233 234
    }
}

235
void PageView::notifyPixmapChanged( int pageNumber )
236
{
237 238 239
    QValueVector< PageWidget * >::iterator pIt = d->pages.begin(), pEnd = d->pages.end();
    for ( ; pIt != pEnd; ++pIt )
        if ( (*pIt)->pageNumber() == pageNumber )
240
        {
241
            (*pIt)->update();
242 243 244 245 246 247 248 249 250 251 252 253 254 255
            break;
        }
}
//END KPDFDocumentObserver inherited methods

//BEGIN widget events 
void PageView::contentsMousePressEvent( QMouseEvent * e )
{
    switch ( d->mouseMode )
    {
    case MouseNormal:    // drag / click start
        if ( e->button() & LeftButton )
        {
            d->mouseGrabPos = e->globalPos();
256
            d->mouseStartPos = d->mouseGrabPos;
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
            setCursor( sizeAllCursor );
        }
        else if ( e->button() & RightButton )
            emit rightClick();

        /* TODO Albert
            note: 'Page' is an 'information container' and has to deal with clean
            data (such as the '(int)page & (float)position' where link refers to,
            not a LinkAction struct.. better an own struct). 'Document' is the place
            to put xpdf/Splash dependant stuff and fill up pages with interpreted
            data. I think is a *clean* way to handle everything.
            d->pressedLink = *PAGE* or *DOCUMENT* ->findLink( normalizedX, normY );
        */
        break;

    case MouseSelection: // ? set 1st corner of the selection rect ?

    case MouseEdit:      // ? place the beginning of [tool] ?
        break;
    }
}

279
void PageView::contentsMouseReleaseEvent( QMouseEvent * e )
280
{
281
    PageWidget * page = pickPageOnPoint( e->x(), e->y() );
282 283 284
    switch ( d->mouseMode )
    {
    case MouseNormal:    // end drag / follow link
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        if ( e->button() & LeftButton )
        {
            setCursor( arrowCursor );
            // check if it was a click, in that case select the page
            if ( e->globalPos() == d->mouseStartPos && page )
                d->document->slotSetCurrentPage( page->pageNumber() );
        }
        else if ( e->button() == Qt::RightButton && page )
        {
            // If over a page display a popup menu
            //FIXME ADD BOOKMARKING STUFF IN DOCUMENT !!!!!!!!!
            KPDFPage * kpdfPage = (KPDFPage *)d->document->page( page->pageNumber() );
            KPopupMenu * m_popup = new KPopupMenu( this, "rmb popup" );
            m_popup->insertTitle( i18n( "Page %1" ).arg( page->pageNumber() ) );
            if ( kpdfPage->isBookmarked() )
                m_popup->insertItem( SmallIcon("bookmark"), i18n("Remove Bookmark"), 1 );
            else
                m_popup->insertItem( SmallIcon("bookmark"), 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(QCursor::pos()) )
            {
            case 1:
                kpdfPage->bookmark( !kpdfPage->isBookmarked() );
                break;
            case 2:
                slotTwoPagesToggled( false );
                slotFitToWidthToggled( true );
                d->document->slotSetCurrentPage( page->pageNumber() );
                break;
            case 3:
                //TODO switch to edit
                break;
            }
        }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 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
        /* TODO Albert
            PageLink * link = *PAGE* ->findLink(e->x()/m_ppp, e->y()/m_ppp);
            if ( link == d->pressedLink )
                //go to link, use:
                document->slotSetCurrentPagePosition( (int)link->page(), (float)link->position() );
                //and all the views will update and display the right page at the right position
            d->pressedLink = 0;
        */
        break;

    case MouseSelection: // ? d->page->setPixmapOverlaySelection( QRect ) ?

    case MouseEdit:      // ? apply [tool] ?
        break;
    }
}

void PageView::contentsMouseMoveEvent( QMouseEvent * e )
{
    switch ( d->mouseMode )
    {
    case MouseNormal:    // move page / change mouse cursor if over links
        if ( e->state() & LeftButton )
        {
            QPoint delta = d->mouseGrabPos - e->globalPos();
            scrollBy( delta.x(), delta.y() );
            d->mouseGrabPos = e->globalPos();
        }
        /* TODO Albert
            LinkAction* action = *PAGE* ->findLink(e->x()/m_ppp, e->y()/m_ppp);
            setCursor(action != 0 ? );
            experimental version using Page->hasLink( int pageX, int pageY )
            and haslink has a fake true response on
        */
        // EROS FIXME find right page for query
        /*if ( d->page && e->state() == NoButton &&  )
        {
            bool onLink = d->page->hasLink( e->x() - d->pageRect.left(), e->y() - d->pageRect.top() );
            // set cursor only when entering / leaving (setCursor has not an internal cache)
            if ( onLink != d->mouseOnLink )
            {
                d->mouseOnLink = onLink;
                setCursor( onLink ? pointingHandCursor : arrowCursor );
            }
        }
        */
        break;

    case MouseSelection: // ? update selection contour ?

    case MouseEdit:      // ? update graphics ?
        break;
    }
}

void PageView::viewportResizeEvent( QResizeEvent * )
{
    // start a timer that will refresh the pixmap after 0.5s
    if ( !d->delayTimer )
    {
        d->delayTimer = new QTimer( this );
381
        connect( d->delayTimer, SIGNAL( timeout() ), this, SLOT( slotRelayoutPages() ) );
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    }
    d->delayTimer->start( 400, true );
}

void PageView::keyPressEvent( QKeyEvent * e )
{
    switch ( e->key() )
    {
    case Key_Up:
        if ( atTop() )
            scrollUp();
        else
            verticalScrollBar()->subtractLine();
        break;
    case Key_Down:
        if ( atBottom() )
            scrollDown();
        else
            verticalScrollBar()->addLine();
        break;
    case Key_Left:
        horizontalScrollBar()->subtractLine();
        break;
    case Key_Right:
        horizontalScrollBar()->addLine();
        break;
408 409 410 411 412
    case Key_PageUp:
        verticalScrollBar()->subtractPage();
        break;
    case Key_PageDown:
        verticalScrollBar()->addPage();
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        break;
    default:
        e->ignore();
        return;
    }
    e->accept();
}

void PageView::wheelEvent( QWheelEvent *e )
{
    int delta = e->delta();
    e->accept();
    if ( (e->state() & ControlButton) == ControlButton ) {
        if ( e->delta() > 0 )
            slotZoomOut();
        else
            slotZoomIn();
    }
431
    else if ( delta <= -120 && atBottom() && !d->viewContinous )
432
        scrollDown();
433
    else if ( delta >= 120 && atTop() && !d->viewContinous )
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        scrollUp();
    else
        QScrollView::wheelEvent( e );
}

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
453
void PageView::slotZoom( const QString & /*nz*/ )
454
{
455
    updateZoom( ZoomFixed );
456 457 458 459
}

void PageView::slotZoomIn()
{
460
    updateZoom( ZoomIn );
461 462 463 464
}

void PageView::slotZoomOut()
{
465
    updateZoom( ZoomOut );
466 467 468 469
}

void PageView::slotFitToWidthToggled( bool on )
{
470
    if ( on ) updateZoom( ZoomFitWidth );
471 472 473 474
}

void PageView::slotFitToPageToggled( bool on )
{
475
    if ( on ) updateZoom( ZoomFitPage );
476 477 478 479
}

void PageView::slotFitToTextToggled( bool on )
{
480
    if ( on ) updateZoom( ZoomFitText );
481 482
}

483 484
void PageView::slotTwoPagesToggled( bool on )
{
485 486 487 488
    int newColumns = on ? 2 : 1;
    if ( d->viewColumns != newColumns )
    {
        d->viewColumns = newColumns;
489
        slotRelayoutPages();
490
    }
491 492
}

493 494
void PageView::slotContinousToggled( bool on )
{
495 496 497
    if ( d->viewContinous != on )
    {
        d->viewContinous = on;
498
        slotRelayoutPages();
499
    }
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
}

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

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

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

void PageView::slotToggleScrollBars( bool on )
{
    setHScrollBarMode( on ? AlwaysOn : AlwaysOff );
    setVScrollBarMode( on ? AlwaysOn : AlwaysOff );
}

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
void PageView::slotRequestVisiblePixmaps( int newLeft, int newTop )
{
//    // if an update is already scheduled or the widget is hidden, don't proceed
//     if ( (m_delayTimer && m_delayTimer->isActive()) || !isShown() )
//         return;

    // 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 )
538
    {
539 540 541 542 543 544 545
        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 );
546
    }
547 548 549
}
//END internal SLOTS

550 551
void PageView::slotRelayoutPages()
// called by: pageSetup, viewportResizeEvent, slotTwoPagesToggled, slotContinousToggled, updateZoom
552 553 554 555 556 557 558 559 560 561 562 563 564
{
    // 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(),
        viewportHeight = clipper()->height();

    if ( d->viewContinous == TRUE )
565
    {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        // 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 )
583
        {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
            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 )
601
            {
602 603
                cIdx = 0;
                rIdx++;
604 605
            }
        }
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

        // 2) arrange widgets inside cells
        int insertX = 0,
            insertY = (int)(5.0 + 10.0 * d->zoomFactor);
        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,
                          insertY + (rHeight - pHeight) / 2 );
            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);
            }
        }

        // 3) update scrollview's contents size and recenter view
        int fullWidth = 0,
            fullHeight = cIdx ? (insertY + rowHeight[ rIdx ] + 10) : insertY,
            oldWidth = contentsWidth(),
            oldHeight = contentsHeight();
        for ( int i = 0; i < nCols; i++ )
            fullWidth += colWidth[ i ];
        resizeContents( fullWidth, fullHeight );
        if ( oldWidth > 0 && oldHeight > 0 )
            center( fullWidth * (contentsX() + visibleWidth() / 2) / oldWidth,
                    fullHeight * (contentsY() + visibleHeight() / 2) / oldHeight );
        else
            center( fullWidth / 2, 0 );

        delete [] colWidth;
        delete [] rowHeight;
    }
    else // viewContinous is FALSE
    {
        // hide all widgets except the displayable ones
        QValueVector< PageWidget * >::iterator dIt = d->pages.begin(), dEnd = d->pages.end();
        for ( ; dIt != dEnd; ++dIt )
            (*dIt)->hide();
        //
        resizeContents( viewportWidth, viewportHeight );
660
    }
661 662

    // reset dirty state
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    d->dirtyLayout = false;
}

void PageView::updateZoom( ZoomMode newZoomMode )
{
    if ( newZoomMode == ZoomFixed )
    {
        if ( d->aZoom->currentText() == i18n("Fit Width") )
            newZoomMode = ZoomFitWidth;
        else if ( d->aZoom->currentText() == i18n("Fit Page") )
            newZoomMode = ZoomFitPage;
    }

    float newFactor = d->zoomFactor;
    KAction * checkedZoomAction = 0;
    switch ( newZoomMode )
    {
    case ZoomFixed:{
        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;
    }

    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();
        // update actions state
        d->aZoomFitWidth->setChecked( checkedZoomAction == d->aZoomFitWidth );
        d->aZoomFitPage->setChecked( checkedZoomAction == d->aZoomFitPage );
        d->aZoomFitText->setChecked( checkedZoomAction == d->aZoomFitText );
        // 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;
        if ( !inserted && newFactor < (value - 0.001) )
            value = newFactor;
        else
            idx ++;
        if ( value > (newFactor - 0.001) && value < (newFactor + 0.001) )
            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 );
768 769
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
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
        if ( x > pLeft && x < pRight && y < pBottom )
        {
            if ( y > pTop )
                page = p;
            break;
        }
    }
    return page;
}

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
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
        d->document->slotSetCurrentPagePosition( d->pages[ d->vectorIndex - 1 ]->pageNumber(), 1.0 );
    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
        d->document->slotSetCurrentPagePosition( d->pages[ d->vectorIndex + 1 ]->pageNumber(), 0.0 );
    else
    {    // go towards the bottom of current page
        int newValue = QMIN( verticalScrollBar()->value() + height() - 50,
                             verticalScrollBar()->maxValue() );
        verticalScrollBar()->setValue( newValue );
    }
}

#include "pageview.moc"